repo_id
stringclasses 205
values | file_path
stringlengths 33
141
| content
stringlengths 1
307k
| __index_level_0__
int64 0
0
|
---|---|---|---|
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/vector_system.cc | #include "drake/systems/framework/vector_system.h"
namespace drake {
namespace systems {
template <typename T>
EventStatus VectorSystem<T>::CalcDiscreteUpdate(
const Context<T>& context, DiscreteValues<T>* discrete_state) const {
// Short-circuit when there's no work to do.
if (discrete_state->num_groups() == 0) {
return EventStatus::DidNothing();
}
const VectorX<T>& input_vector = EvalVectorInput(context);
const auto input_block = input_vector.head(input_vector.rows());
// Obtain the block form of xd before the update (i.e., the prior state).
DRAKE_ASSERT(context.has_only_discrete_state());
const VectorX<T>& state_vector = context.get_discrete_state(0).value();
const Eigen::VectorBlock<const VectorX<T>> state_block =
state_vector.head(state_vector.rows());
// Obtain the block form of xd after the update (i.e., the next state).
DRAKE_ASSERT(discrete_state != nullptr);
Eigen::VectorBlock<VectorX<T>> discrete_update_block =
discrete_state->get_mutable_value();
// Delegate to subclass.
DoCalcVectorDiscreteVariableUpdates(context, input_block, state_block,
&discrete_update_block);
return EventStatus::Succeeded();
}
} // namespace systems
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::VectorSystem)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/diagram_discrete_values.h | #pragma once
#include <memory>
#include <utility>
#include <vector>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/pointer_cast.h"
#include "drake/common/value.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/discrete_values.h"
#include "drake/systems/framework/framework_common.h"
namespace drake {
namespace systems {
/// DiagramDiscreteValues is a DiscreteValues container comprised recursively of
/// a sequence of child DiscreteValues objects. The API allows this to be
/// treated as though it were a single DiscreteValues object whose groups are
/// the concatenation of the groups in each child.
///
/// The child objects may be owned or not. When this is used to aggregate
/// LeafSystem discrete values in a Diagram, the child objects are not owned.
/// When this is cloned, deep copies are made that are owned here.
template <typename T>
class DiagramDiscreteValues final: public DiscreteValues<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DiagramDiscreteValues)
/// Constructs a DiagramDiscreteValues object that is composed of other
/// DiscreteValues, which are not owned by this object and must outlive it.
///
/// The DiagramDiscreteValues vector xd = [xd₁ xd₂ ...] where each of the xdᵢ
/// is an array of BasicVector objects. These will have the same
/// ordering as the @p subdiscretes parameter, which should be the order of
/// the Diagram itself. That is, the substates should be indexed by
/// SubsystemIndex in the same order as the subsystems are.
explicit DiagramDiscreteValues(std::vector<DiscreteValues<T>*> subdiscretes)
: DiscreteValues<T>(Flatten(subdiscretes)),
subdiscretes_(std::move(subdiscretes)) {
DRAKE_ASSERT(internal::IsNonNull(subdiscretes_));
}
/// Constructs a DiagramDiscreteValues object that is composed (recursively)
/// of other DiscreteValues objects, ownership of which is transferred here.
explicit DiagramDiscreteValues(
std::vector<std::unique_ptr<DiscreteValues<T>>> owned_subdiscretes)
: DiagramDiscreteValues<T>(internal::Unpack(owned_subdiscretes)) {
owned_subdiscretes_ = std::move(owned_subdiscretes);
DRAKE_ASSERT(internal::IsNonNull(owned_subdiscretes_));
}
/// Destructor deletes any owned DiscreteValues objects but does nothing if
/// the referenced DiscreteValues objects are unowned.
~DiagramDiscreteValues() override {}
/// Creates a deep copy of this %DiagramDiscreteValues object, with the same
/// substructure but with new, owned data. Intentionally shadows the
/// DiscreteValues::Clone() method but with a more-specific return type so
/// you don't have to downcast.
std::unique_ptr<DiagramDiscreteValues> Clone() const {
// Note that DoClone() below cannot be overridden so we can count on the
// concrete type being DiagramDiscreteValues.
return static_pointer_cast<DiagramDiscreteValues>(DoClone());
}
/// Returns the number of DiscreteValues objects referenced by this
/// %DiagramDiscreteValues object, necessarily the same as the number of
/// subcontexts in the containing DiagramContext.
int num_subdiscretes() const {
return static_cast<int>(subdiscretes_.size());
}
/// Returns a const reference to one of the referenced DiscreteValues
/// objects which may or may not be owned locally.
const DiscreteValues<T>& get_subdiscrete(SubsystemIndex index) const {
DRAKE_DEMAND(0 <= index && index < num_subdiscretes());
DRAKE_DEMAND(subdiscretes_[index] != nullptr);
return *subdiscretes_[index];
}
/// Returns a mutable reference to one of the referenced DiscreteValues
/// objects which may or may not be owned locally.
DiscreteValues<T>& get_mutable_subdiscrete(SubsystemIndex index) {
return const_cast<DiscreteValues<T>&>(get_subdiscrete(index));
}
private:
// This completely replaces the base class default DoClone() so must
// take care of the base class members as well as the local ones. That's done
// by invoking a constructor that delegates to the base.
// The returned concrete object is a DiagramDiscreteValues<T>.
std::unique_ptr<DiscreteValues<T>> DoClone() const final {
std::vector<std::unique_ptr<DiscreteValues<T>>> owned_subdiscretes;
// Make deep copies regardless of whether they were owned.
for (auto discrete : subdiscretes_)
owned_subdiscretes.push_back(discrete->Clone());
return std::make_unique<DiagramDiscreteValues>(
std::move(owned_subdiscretes));
}
// Given a vector of DiscreteValues pointers, each potentially containing
// multiple BasicVectors, return a longer vector of pointers to all the
// contained BasicVectors, unpacked in order. Because each of the referenced
// DiscreteValues has been similarly unpacked, the result is a complete, flat
// list of all the leaf BasicVectors below `this` DiagramDiscreteValues.
std::vector<BasicVector<T>*> Flatten(
const std::vector<DiscreteValues<T>*>& in) const {
std::vector<BasicVector<T>*> out;
for (const DiscreteValues<T>* xd : in) {
const std::vector<BasicVector<T>*>& xd_data = xd->get_data();
out.insert(out.end(), xd_data.begin(), xd_data.end());
}
return out;
}
// Pointers to the underlying DiscreteValues objects that provide the actual
// values. If these are owned, the pointers are equal to the pointers in
// owned_subdiscretes_.
std::vector<DiscreteValues<T>*> subdiscretes_;
// Owned pointers to DiscreteValues objects that hold the actual values.
// The only purpose of these pointers is to maintain ownership. They may be
// populated at construction time, and are never accessed thereafter.
std::vector<std::unique_ptr<DiscreteValues<T>>> owned_subdiscretes_;
};
} // namespace systems
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::DiagramDiscreteValues)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/event.h | #pragma once
#include <limits>
#include <memory>
#include <unordered_set>
#include <utility>
#include <variant>
#include "drake/common/drake_copyable.h"
#include "drake/common/value.h"
#include "drake/systems/framework/context.h"
#include "drake/systems/framework/continuous_state.h"
#include "drake/systems/framework/event_status.h"
namespace drake {
namespace systems {
// Forward declaration to avoid circular dependencies.
template <typename T> class System;
/** @defgroup events_description System Events
@ingroup systems
This page describes how Drake Systems can respond (through an Event) to changes
("triggers") in time, state, and inputs.
The state of simple dynamical systems, like the ODE ẋ = x, can be
propagated through time using straightforward numerical integration. More
sophisticated systems (e.g., systems modeled using piecewise differential
algebraic equations, systems dependent upon mouse button clicks, and
@ref discrete_systems) require more sophisticated state updating mechanisms.
We call those state updates "events", the conditions that cause these events
"triggers", and the mechanisms that compute the updates "handlers". We discuss
these concepts in detail on this page. The Simulator class documentation
describes the technical process underlying how events are handled in great
detail.
### Exposition
Events occur between discrete, finite advancements of systems' time
and state. In the absence of events, a simulator would happily advance time and
any continuous state without stopping. The occurrence of an event pauses the
time and state evolution in order to allow a system to change its state
discontinuously, to communicate with the "outside world", and even to just
count the number of event occurrences.
### Types of events and triggers
The diagram below distinguishes between the condition that is responsible for
detecting the event (the "trigger") and the action that is taken when the event
is dispatched (the "event handler").
-- > handler1
triggers -- > dispatcher -- > handler2
Events -- > etc.
Handler actions fall into several categories based on event type, as
described next.
#### %Event types
Events are grouped by the component(s) of a system's State that can be altered:
- "publish" events can modify no state: they are useful for broadcasting data
outside of the novel system and any containing diagrams, for terminating
a simulation, for detecting errors, and for forcing boundaries between
integration steps.
- "discrete update" events can alter the discrete state of a system.
- "unrestricted update" events can alter every component of state but time:
continuous state, discrete state, and abstract state.
Note that continuous state is nominally updated through the
process of solving an ODE initial value problem (i.e., "integrating") rather
than through a specialized event.
Updates are performed in a particular sequence. For example, unrestricted
updates are performed before discrete updates. The Simulator documentation
describes the precise update ordering.
#### %Event triggers
Events can be triggered in various ways including:
- upon initialization
- as a certain time is crossed (whether once or repeatedly, i.e.,
periodically)
- per simulation step
- as a WitnessFunction crosses zero
- "by force", e.g., the system's CalcUnrestrictedUpdate() function is invoked
by some user code
### How events are handled
State advances with time in dynamical systems. If the dynamical system is
simulated, then Drake's Simulator, or another solver (see @ref event_glossary
"glossary") is responsible for detecting when events trigger, dispatching the
appropriate handler function, and updating the state as time advances. The
update functions modify only copies of state so that every update function in a
class (e.g., all unrestricted updates) sees the same pre-update state
regardless of the sequence of event updates).
Events can also be dispatched manually ("by force"), i.e., outside of a solver.
As noted above, one could call CalcUnrestrictedUpdate() to determine how a
system's state would change and, optionally, update that state manually. Here
is a simple example illustrating a forced publish:
```
SystemX y;
std::unique_ptr<Context<T>> context = y.CreateDefaultContext();
y.Publish(*context);
```
### Information for leaf system authors
#### Declaring update functions
The way to update state through events is to declare an update handler in your
LeafSystem-derived-class.
A number of convenience functions are available in LeafSystem for declaring
various trigger and event update combinations; see, e.g.,
LeafSystem::DeclarePeriodicPublishEvent(),
LeafSystem::DeclarePerStepDiscreteUpdateEvent(), and
LeafSystem::DeclareInitializationUnrestrictedUpdateEvent().
The following sample code shows how to declare a publish event that is
triggered at regular time intervals:
```
template <typename T>
class MySystem : public LeafSystem<T> {
MySystem() {
const double period = 1.0;
const double offset = 0.0;
this->DeclarePeriodicPublishEvent(period, offset, &MySystem::MyPublish);
}
// Called once per second when MySystem is simulated.
EventStatus MyPublish(const Context<T>&) const { ... }
};
```
#### Trigger data carried with Events
It can be impractical or infeasible to create a different handler function for
every possible trigger that a leaf system might need to consider. The
alternative is to create a single event handler and map multiple triggers to
it via multiple %Event objects that specify the same handler. Then the handler
may need a way to determine which condition triggered it.
For this purpose, every %Event stores the type of trigger associated with it
and, if relevant, some extra data that provides greater insight into why the
event handler was invoked. The latter is stored in an `std::variant` field
that is currently defined for periodic-triggered timing information and for
witness-triggered localization information. For example:
```
template <typename T>
class MySystem : public LeafSystem<T> {
MySystem() {
const double period1 = 1.0;
const double period2 = 2.0;
const double offset = 0.0;
// Declare a publish event with one period.
this->DeclarePeriodicEvent(period1, offset, PublishEvent<T>(
TriggerType::kPeriodic,
[this](const Context<T>& context, const PublishEvent<T>& event) ->
EventStatus {
return MyPublish(context, event);
}));
// Declare a second publish event with another period.
this->DeclarePeriodicEvent(period2, offset, PublishEvent<T>(
TriggerType::kPeriodic,
[this](const Context<T>& context, const PublishEvent<T>& event) ->
EventStatus {
return MyPublish(context, event);
}));
}
// A single update handler for all triggered events.
EventStatus MyPublish(const Context<T>&, const PublishEvent<T>& e) const {
if (e.get_trigger_type() == TriggerType::kPeriodic) {
std::cout << "Event period: "
<< e.template get_event_data<PeriodicEventData>()->period_sec()
<< std::endl;
}
}
};
```
@see PeriodicEventData, WitnessTriggeredEventData
#### %Event status
%Event handlers can return an EventStatus type to modulate the behavior of a
solver. Returning EventStatus::kFailed from the event handler indicates
that the event handler was unable to update the state (because, e.g., the
simulation step was too big) and thus the solver should take corrective action.
Or an event handler can return EventStatus::kReachedTermination to indicate
that the solver should stop computing; this is useful if the event handler
detects that a simulated walking robot has fallen over and that the end of a
reinforcement learning episode has been observed, for example.
### Glossary
@anchor event_glossary
- **dispatch**: the process of the solver collecting events that trigger
simultaneously and then distributing those events to their
handlers.
- **forced event**: when an event is triggered manually through user
code rather than by a solver.
- **handle/handler**: an event is "handled" when the triggering condition has
been identified and the "handler" function is called.
- **solver**: a process that controls or tracks the time and state evolution
of a System.
- **trigger**: the condition responsible for causing an event.
*/
template <class T>
class WitnessFunction;
// Forward declaration of the event container classes.
// -- Containers for homogeneous events.
template <typename EventType>
class EventCollection;
template <typename EventType>
class LeafEventCollection;
// -- Containers for heterogeneous events.
template <typename T>
class CompositeEventCollection;
template <typename T>
class LeafCompositeEventCollection;
/**
* An event data variant describing an event that recurs on a fixed period. The
* events are triggered at time = offset_sec + i * period_sec, where i is a
* non-negative integer.
*/
class PeriodicEventData {
public:
PeriodicEventData() {}
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(PeriodicEventData);
/// Gets the period with which this event should recur.
double period_sec() const { return period_sec_; }
/// Sets the period with which this event should recur.
void set_period_sec(double period_sec) { period_sec_ = period_sec; }
/// Gets the time after zero when this event should first occur.
double offset_sec() const { return offset_sec_; }
/// Sets the time after zero when this event should first occur.
void set_offset_sec(double offset_sec) { offset_sec_ = offset_sec; }
bool operator==(const PeriodicEventData& other) const {
return other.period_sec() == period_sec() &&
other.offset_sec() == offset_sec();
}
private:
double period_sec_{0.0};
double offset_sec_{0.0};
};
/**
* An event data variant for storing data from a witness function triggering to
* be passed to event handlers. A witness function isolates time to a (typically
* small) window during which the witness function crosses zero. The time and
* state at both sides of this window are passed to the event handler so that
* the system can precisely determine the reason that the witness function
* triggered.
*/
template <class T>
class WitnessTriggeredEventData {
public:
WitnessTriggeredEventData() {}
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(WitnessTriggeredEventData);
/// Gets the witness function that triggered the event handler.
const WitnessFunction<T>* triggered_witness() const {
return triggered_witness_;
}
/// Sets the witness function that triggered the event handler.
void set_triggered_witness(const WitnessFunction<T>* triggered_witness) {
triggered_witness_ = triggered_witness;
}
/// Gets the time at the left end of the window. Default is NaN (which
/// indicates that the value is invalid).
const T& t0() const { return t0_; }
/// Sets the time at the left end of the window. Note that `t0` should be
/// smaller than `tf` after both values are set.
void set_t0(const T& t0) { t0_ = t0; }
/// Gets the time at the right end of the window. Default is NaN (which
/// indicates that the value is invalid).
const T& tf() const { return tf_; }
/// Sets the time at the right end of the window. Note that `tf` should be
/// larger than `t0` after both values are set.
void set_tf(const T& tf) { tf_ = tf; }
/// Gets a pointer to the continuous state at the left end of the isolation
/// window.
const ContinuousState<T>* xc0() const { return xc0_; }
/// Sets a pointer to the continuous state at the left end of the isolation
/// window.
void set_xc0(const ContinuousState<T>* xc0) { xc0_ = xc0; }
/// Gets a pointer to the continuous state at the right end of the isolation
/// window.
const ContinuousState<T>* xcf() const { return xcf_; }
/// Sets a pointer to the continuous state at the right end of the isolation
/// window.
void set_xcf(const ContinuousState<T>* xcf) { xcf_ = xcf; }
private:
const WitnessFunction<T>* triggered_witness_{nullptr};
T t0_{std::numeric_limits<double>::quiet_NaN()};
T tf_{std::numeric_limits<double>::quiet_NaN()};
const ContinuousState<T>* xc0_{nullptr};
const ContinuousState<T>* xcf_{nullptr};
};
/**
* Predefined types of triggers for events. Used at run time to determine why
* the associated event has occurred.
*/
enum class TriggerType {
kUnknown,
/**
* This trigger indicates that an associated event is triggered at system
* initialization.
*/
kInitialization,
/**
* This trigger indicates that an associated event is triggered by directly
* calling the corresponding public system API for event handling (e.g.
* Publish(context)).
*/
kForced,
/**
* This trigger indicates that an associated event is triggered by the
* system proceeding to a single, arbitrary time. Timed events are commonly
* created in System::CalcNextUpdateTime().
*/
kTimed,
/**
* This type indicates that an associated event is triggered by the system
* proceeding to a time t ∈ {tᵢ = t₀ + p * i} for some period p, time
* offset t₀, and i is a non-negative integer. @see PeriodicEventData.
* Periodic events are commonly created in System::CalcNextUpdateTime().
*/
kPeriodic,
/**
* This trigger indicates that an associated event is triggered whenever a
* `solver` takes a `step`. A `solver` is an abstract construct that
* controls or tracks the time and state evolution of a System. A simulator is
* a `solver`- it advances time a finite duration by integrating a system,
* modifying its state accordingly- as is a process that receives some numeric
* state from IPC that is then used to, e.g., update abstract state.
* Steps may occur at irregular time intervals: a step typically coincides
* with a point in time where it is advantageous to poll for events, like
* immediately after an integrator has advanced time and state.
*
* Per-step events are most commonly created in System::GetPerStepEvents(). A
* very common use of such per-step events is to update a discrete or abstract
* state variable that changes whenever the continuous state advances;
* examples are computing the "min" or "max" of some state variable, recording
* a signal in a delay buffer, or publishing. Per-step events are also useful
* to implement feedback controllers interfaced with physical devices; the
* controller can be implemented in the event handler, and the "step" would
* correspond to receiving sensory data from the hardware.
*/
kPerStep,
/**
* This trigger indicates that an associated event is triggered by the zero
* crossing of a witness function. @see WitnessTriggeredEventData.
*/
kWitness,
};
/**
* This set-type alias provides a convenient API vocabulary for systems to
* specify multiple trigger types.
*/
using TriggerTypeSet = std::unordered_set<TriggerType, DefaultHash>;
/** Abstract base class that represents an event. The base event contains two
main pieces of information: an enum trigger type and an optional attribute
that can be used to explain why the event is triggered.
Concrete derived classes contain a function pointer to an optional callback that
handles the event. No-op is the default handling behavior. The System framework
supports three concrete event types: PublishEvent, DiscreteUpdateEvent, and
UnrestrictedUpdateEvent distinguished by their callback functions' write access
level to the State.
The most common and convenient use of events and callbacks will happen via the
LeafSystem Declare*Event() methods. To that end, the callback signature always
passes the `const %System<T>&` as the first argument, so that %LeafSystem does
not need to capture `this` into the lambda; typically only a pointer-to-member-
function is captured. Capturing any more than that would defeat std::function's
small buffer optimization and cause heap allocations when scheduling events.
%Event handling occurs during a simulation of a system. The logic that describes
when particular event types are handled is described in the class documentation
for Simulator. */
template <typename T>
class Event {
public:
virtual ~Event() = default;
// TODO(eric.cousineau): Deprecate and remove this alias.
using TriggerType = systems::TriggerType;
/// Returns `true` if this is a DiscreteUpdateEvent.
virtual bool is_discrete_update() const = 0;
/**
* Clones this instance.
*/
std::unique_ptr<Event> Clone() const {
return std::unique_ptr<Event>(DoClone());
}
/**
* Returns the trigger type.
*/
TriggerType get_trigger_type() const { return trigger_type_; }
/**
* Returns true if this event has associated data of the given
* `EventDataType`.
*
* @tparam EventDataType the expected data type for an event that has this
* trigger type (PeriodicEventData or WitnessTriggeredEventData).
*/
template <typename EventDataType>
bool has_event_data() const {
return std::holds_alternative<EventDataType>(event_data_);
}
/**
* Returns a const pointer to the event data. The returned value
* can be nullptr, which means this event does not have any associated
* data of the given `EventDataType`.
*
* @tparam EventDataType the expected data type for an event that has this
* trigger type (PeriodicEventData or WitnessTriggeredEventData).
*/
template <typename EventDataType>
const EventDataType* get_event_data() const {
return std::get_if<EventDataType>(&event_data_);
}
/**
* Returns a mutable pointer to the event data. The returned value
* can be nullptr, which means this event does not have any associated
* data of the given `EventDataType`.
*
* @tparam EventDataType the expected data type for an event that has this
* trigger type (PeriodicEventData or WitnessTriggeredEventData).
*/
template <typename EventDataType>
EventDataType* get_mutable_event_data() {
return std::get_if<EventDataType>(&event_data_);
}
#if !defined(DRAKE_DOXYGEN_CXX)
/* (Internal use only) Sets the trigger type. */
void set_trigger_type(const TriggerType trigger_type) {
trigger_type_ = trigger_type; }
/* (Internal use only) Sets data to one of the available variants. */
template <typename EventDataType>
void set_event_data(EventDataType data) {
event_data_ = std::move(data);
}
#endif
/**
* Adds a clone of `this` event to the event collection `events`, with
* the given trigger type. If `this` event has an unknown trigger type, then
* any trigger type is acceptable. Otherwise the given trigger type must
* match the trigger type stored in `this` event.
* @pre `trigger_type` must match the current trigger type unless that is
* unknown.
* @pre `events` must not be null.
*/
void AddToComposite(TriggerType trigger_type,
CompositeEventCollection<T>* events) const {
DRAKE_DEMAND(events != nullptr);
DRAKE_DEMAND(trigger_type_ == TriggerType::kUnknown ||
trigger_type_ == trigger_type);
DoAddToComposite(trigger_type, &*events);
}
/**
* Provides an alternate signature for adding an Event that already has the
* correct trigger type set. Must not have an unknown trigger type.
*/
void AddToComposite(CompositeEventCollection<T>* events) const {
DRAKE_DEMAND(events != nullptr);
DRAKE_DEMAND(trigger_type_ != TriggerType::kUnknown);
DoAddToComposite(trigger_type_, &*events);
}
protected:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Event);
/** Constructs an empty Event. */
Event() = default;
#if !defined(DRAKE_DOXYGEN_CXX)
/* (Internal use only) */
explicit Event(const TriggerType& trigger) : trigger_type_(trigger) {}
#endif
/**
* Derived classes must implement this to add a clone of this Event to
* the event collection and unconditionally set its trigger type.
*/
virtual void DoAddToComposite(TriggerType trigger_type,
CompositeEventCollection<T>* events) const = 0;
/**
* Derived classes must implement this method to clone themselves. Any
* Event-specific data is cloned using the Clone() method. Data specific
* to the class derived from Event must be cloned by the implementation.
*/
[[nodiscard]] virtual Event* DoClone() const = 0;
private:
TriggerType trigger_type_{TriggerType::kUnknown};
std::variant<std::monostate, PeriodicEventData, WitnessTriggeredEventData<T>>
event_data_;
};
/**
* Structure for comparing two PeriodicEventData objects for use in a map
* container, using an arbitrary comparison method.
*/
struct PeriodicEventDataComparator {
bool operator()(const PeriodicEventData& a,
const PeriodicEventData& b) const {
if (a.period_sec() == b.period_sec())
return a.offset_sec() < b.offset_sec();
return a.period_sec() < b.period_sec();
}
};
/**
* This class represents a publish event. It has an optional callback function
* to do custom handling of this event. @see System::Publish for more details.
* @see LeafSystem for more convenient interfaces to publish events via the
* Declare*PublishEvent() methods.
*/
template <typename T>
class PublishEvent final : public Event<T> {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(PublishEvent);
bool is_discrete_update() const override { return false; }
/** Constructs an empty PublishEvent. */
PublishEvent() = default;
/** Constructs a PublishEvent with the given callback function. */
explicit PublishEvent(
const std::function<EventStatus(const System<T>&, const Context<T>&,
const PublishEvent<T>&)>& callback)
: callback_(callback) {}
#if !defined(DRAKE_DOXYGEN_CXX)
/* (Internal use only) */
explicit PublishEvent(const TriggerType& trigger_type) {
this->set_trigger_type(trigger_type);
}
/* (Internal use only) */
template <typename Function>
PublishEvent(const TriggerType& trigger_type, const Function& callback) {
this->set_trigger_type(trigger_type);
callback_ = callback;
}
#endif
// TODO(jwnimmer-tri) Annotate [[nodiscard]] on the return value.
// Possibly fix CamelCase at the same time, e.g., InvokeCallback().
/**
* Calls the optional callback or system callback function, if one exists,
* with @p system, @p context, and `this`.
*/
EventStatus handle(const System<T>& system, const Context<T>& context) const {
return (callback_ != nullptr) ? callback_(system, context, *this)
: EventStatus::DidNothing();
}
private:
void DoAddToComposite(TriggerType trigger_type,
CompositeEventCollection<T>* events) const final {
PublishEvent event(*this);
event.set_trigger_type(trigger_type);
events->AddPublishEvent(std::move(event));
}
// Clones PublishEvent-specific data.
[[nodiscard]] PublishEvent<T>* DoClone() const final {
return new PublishEvent(*this);
}
// Optional callback function that handles this event.
// It is valid for no callback to be set.
std::function<EventStatus(const System<T>&, const Context<T>&,
const PublishEvent<T>&)>
callback_;
};
/**
* This class represents a discrete update event. It has an optional callback
* function to do custom handling of this event, and that can write updates to a
* mutable, non-null DiscreteValues object. @see LeafSystem for more convenient
* interfaces to discrete update events via the Declare*DiscreteUpdateEvent()
* methods.
*/
template <typename T>
class DiscreteUpdateEvent final : public Event<T> {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(DiscreteUpdateEvent);
bool is_discrete_update() const override { return true; }
/** Constructs an empty DiscreteUpdateEvent. */
DiscreteUpdateEvent() = default;
/** Constructs a DiscreteUpdateEvent with the given callback function. */
explicit DiscreteUpdateEvent(
const std::function<EventStatus(const System<T>&, const Context<T>&,
const DiscreteUpdateEvent<T>&,
DiscreteValues<T>*)>& callback)
: callback_(callback) {}
#if !defined(DRAKE_DOXYGEN_CXX)
/* (Internal use only) */
explicit DiscreteUpdateEvent(const TriggerType& trigger_type) {
this->set_trigger_type(trigger_type);
}
/* (Internal use only) */
template <typename Function>
DiscreteUpdateEvent(const TriggerType& trigger_type,
const Function& callback) {
this->set_trigger_type(trigger_type);
callback_ = callback;
}
#endif
// TODO(jwnimmer-tri) Annotate [[nodiscard]] on the return value.
// Possibly fix CamelCase at the same time, e.g., InvokeCallback().
/**
* Calls the optional callback function, if one exists, with @p system, @p
* context, `this` and @p discrete_state.
*/
EventStatus handle(const System<T>& system, const Context<T>& context,
DiscreteValues<T>* discrete_state) const {
return (callback_ != nullptr)
? callback_(system, context, *this, discrete_state)
: EventStatus::DidNothing();
}
private:
void DoAddToComposite(TriggerType trigger_type,
CompositeEventCollection<T>* events) const final {
DiscreteUpdateEvent<T> event(*this);
event.set_trigger_type(trigger_type);
events->AddDiscreteUpdateEvent(std::move(event));
}
// Clones DiscreteUpdateEvent-specific data.
[[nodiscard]] DiscreteUpdateEvent<T>* DoClone() const final {
return new DiscreteUpdateEvent(*this);
}
// Optional callback functions that handle this event.
// It is valid for no callback to be set.
std::function<EventStatus(const System<T>&, const Context<T>&,
const DiscreteUpdateEvent<T>&, DiscreteValues<T>*)>
callback_;
};
/**
* This class represents an unrestricted update event. It has an optional
* callback function to do custom handling of this event, and that can write
* updates to a mutable, non-null State object. @see LeafSystem for more
* convenient interfaces to unrestricted update events via the
* Declare*UnrestrictedUpdateEvent() methods.
*/
template <typename T>
class UnrestrictedUpdateEvent final : public Event<T> {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(UnrestrictedUpdateEvent);
bool is_discrete_update() const override { return false; }
/** Constructs an empty UnrestrictedUpdateEvent. */
UnrestrictedUpdateEvent() = default;
/** Constructs an UnrestrictedUpdateEvent with the given callback function. */
explicit UnrestrictedUpdateEvent(
const std::function<EventStatus(const System<T>&, const Context<T>&,
const UnrestrictedUpdateEvent<T>&,
State<T>*)>& callback)
: callback_(callback) {}
#if !defined(DRAKE_DOXYGEN_CXX)
/* (Internal use only) */
explicit UnrestrictedUpdateEvent(const TriggerType& trigger_type) {
this->set_trigger_type(trigger_type);
}
/* (Internal use only) */
template <typename Function>
UnrestrictedUpdateEvent(const TriggerType& trigger_type,
const Function& callback) {
this->set_trigger_type(trigger_type);
callback_ = callback;
}
#endif
// TODO(jwnimmer-tri) Annotate [[nodiscard]] on the return value.
// Possibly fix CamelCase at the same time, e.g., InvokeCallback().
/**
* Calls the optional callback function, if one exists, with @p system, @p
* context, `this` and @p state.
*/
EventStatus handle(const System<T>& system, const Context<T>& context,
State<T>* state) const {
return (callback_ != nullptr) ? callback_(system, context, *this, state)
: EventStatus::DidNothing();
}
private:
void DoAddToComposite(TriggerType trigger_type,
CompositeEventCollection<T>* events) const final {
UnrestrictedUpdateEvent<T> event(*this);
event.set_trigger_type(trigger_type);
events->AddUnrestrictedUpdateEvent(std::move(event));
}
// Clones event data specific to UnrestrictedUpdateEvent.
UnrestrictedUpdateEvent<T>* DoClone() const final {
return new UnrestrictedUpdateEvent(*this);
}
// Optional callback function that handles this event.
// It is valid for no callback to be set.
std::function<EventStatus(const System<T>&, const Context<T>&,
const UnrestrictedUpdateEvent<T>&, State<T>*)>
callback_;
};
} // namespace systems
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::WitnessTriggeredEventData)
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::Event)
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::PublishEvent)
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::DiscreteUpdateEvent)
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::UnrestrictedUpdateEvent)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/cache_entry.h | #pragma once
#include <functional>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include "drake/common/drake_copyable.h"
#include "drake/common/value.h"
#include "drake/systems/framework/context_base.h"
#include "drake/systems/framework/framework_common.h"
#include "drake/systems/framework/value_producer.h"
namespace drake {
namespace systems {
/** A %CacheEntry belongs to a System and represents the properties of one of
that System's cached computations. %CacheEntry objects are assigned CacheIndex
values in the order they are declared; these are unique within a single System
and can be used for quick access to both the %CacheEntry and the corresponding
CacheEntryValue in the System's Context.
%CacheEntry objects are allocated automatically for known System computations
like output ports and time derivatives, and may also be allocated by user code
for other cached computations.
A cache entry's value is always stored as an AbstractValue, which can hold a
concrete value of any copyable type. However, once a value has been allocated
using a particular concrete type, the type cannot be changed.
%CacheEntry objects support four important operations:
- Allocate() returns an object that can hold the cached value.
- Calc() unconditionally computes the cached value.
- Eval() returns a reference to the cached value, first updating with Calc()
if it was out of date.
- GetKnownUpToDate() returns a reference to the current value that you are
certain must already be up to date.
The allocation and calculation functions must be provided at the time a
cache entry is declared. That is typically done in a System constructor, in
a manner very similar to the declaration of output ports. */
class CacheEntry {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(CacheEntry)
// All the nontrivial parameters here are moved to the CacheEntry which is
// why they aren't references.
/** (Advanced) Constructs a cache entry within a System and specifies the
resources it needs.
This method is intended only for use by the framework which provides much
nicer APIs for end users. See
@ref DeclareCacheEntry_documentation "DeclareCacheEntry" for the
user-facing API documentation.
The ValueProducer embeds both an allocator and calculator function.
The supplied allocator must return a suitable AbstractValue in which to
hold the result. The supplied calculator function must write to an
AbstractValue of the same underlying concrete type as is returned by the
allocator. The allocator function is not invoked here during construction of
the cache entry. Instead allocation is deferred until the allocator can be
provided with a complete Context, which cannot occur until the full Diagram
containing this subsystem has been completed. That way the initial type, size,
or value can be Context-dependent. The supplied prerequisite tickets are
interpreted as belonging to the same subsystem that owns this %CacheEntry.
The list of prerequisites cannot be empty -- a cache entry that really has
no prerequisites must say so explicitly by providing a list containing only
`nothing_ticket()` as a prerequisite. The subsystem pointer must not be null,
and the cache index and ticket must be valid. The description is an arbitrary
string not interpreted in any way by Drake.
@throws std::exception if the prerequisite list is empty.
@see drake::systems::SystemBase::DeclareCacheEntry() */
CacheEntry(const internal::SystemMessageInterface* owning_system,
CacheIndex index, DependencyTicket ticket, std::string description,
ValueProducer value_producer,
std::set<DependencyTicket> prerequisites_of_calc);
/** Returns a reference to the set of prerequisites needed by this cache
entry's Calc() function. These are all within the same subsystem that
owns this %CacheEntry. */
const std::set<DependencyTicket>& prerequisites() const {
return prerequisites_of_calc_;
}
/** (Advanced) Returns a mutable reference to the set of prerequisites needed
by this entry's Calc() function. Any tickets in this set are interpreted as
referring to prerequisites within the same subsystem that owns this
%CacheEntry. Modifications take effect the next time the containing System is
asked to create a Context.
A cache entry should normally be given its complete set of prerequisites
at the time it is declared (typically in a System constructor). If
possible, defer declaration of cache entries until all their prerequisites
have been declared so that all necessary tickets are available. In Systems
with complicated extended construction phases it may be awkward or impossible
to know all the prerequisites at that time. In that case, consider choosing
a comprehensive prerequisite like `all_input_ports_ticket()` that can include
as-yet-undeclared prerequisites. If performance requirements preclude that
approach, then an advanced user may use this method to add more prerequisites
as their tickets become available. */
std::set<DependencyTicket>& mutable_prerequisites() {
return prerequisites_of_calc_;
}
/** Invokes this cache entry's allocator function to allocate a concrete
object suitable for holding the value to be held in this cache entry, and
returns that as an AbstractValue. The returned object will never be null.
@throws std::exception if the allocator function returned null. */
std::unique_ptr<AbstractValue> Allocate() const;
/** Unconditionally computes the value this cache entry should have given a
particular context, into an already-allocated object.
@pre `context` is a subcontext that is compatible with the subsystem that owns
this cache entry.
@pre `value` is non null and has exactly the same concrete type as that of
the object returned by this entry's Allocate() method. */
void Calc(const ContextBase& context, AbstractValue* value) const;
/** Returns a reference to the up-to-date value of this cache entry contained
in the given Context. This is the preferred way to obtain a cached value. If
the value is not already up to date with respect to its prerequisites, or if
caching is disabled for this entry, then this entry's Calc() method is used
first to update the value before the reference is returned. The Calc() method
may be arbitrarily expensive, but this method is constant time and _very_ fast
if the value is already up to date. If you are certain the value should be up
to date already, you may use the GetKnownUpToDate() method instead.
@pre `context` is a subcontext that is compatible with the subsystem that owns
this cache entry.
@throws std::exception if the value doesn't actually have type V. */
template <typename ValueType>
const ValueType& Eval(const ContextBase& context) const {
const AbstractValue& abstract_value = EvalAbstract(context);
return ExtractValueOrThrow<ValueType>(abstract_value, __func__);
}
/** Returns a reference to the up-to-date abstract value of this cache entry
contained in the given Context. If the value is not already up to date with
respect to its prerequisites, or if caching is disabled for this entry, the
Calc() method above is used first to update the value before the reference is
returned. This method is constant time and _very_ fast if the value doesn't
need to be recomputed.
@pre `context` is a subcontext that is compatible with the subsystem that owns
this cache entry. */
// Keep this method as small as possible to encourage inlining; it gets
// called *a lot*.
const AbstractValue& EvalAbstract(const ContextBase& context) const {
const CacheEntryValue& cache_value = get_cache_entry_value(context);
if (cache_value.needs_recomputation()) UpdateValue(context);
return cache_value.get_abstract_value();
}
// Keep this method as small as possible to encourage inlining; it may be
// called *a lot*.
/** Returns a reference to the _known up-to-date_ value of this cache entry
contained in the given Context. The purpose of this method is to avoid
unexpected recomputations in circumstances where you believe the value must
already be up to date. Unlike Eval(), this method will throw an exception
if the value is out of date; it will never attempt a recomputation. The
behavior here is unaffected if caching is disabled for this cache entry --
it looks only at the out_of_date flag which is still maintained when caching
is disabled. This method is constant time and _very_ fast if it succeeds.
@pre `context` is a subcontext that is compatible with the subsystem that owns
this cache entry.
@throws std::exception if the value is out of date or if it does not
actually have type `ValueType`. */
template <typename ValueType>
const ValueType& GetKnownUpToDate(const ContextBase& context) const {
const CacheEntryValue& cache_value = get_cache_entry_value(context);
if (cache_value.is_out_of_date()) ThrowOutOfDate(__func__);
return ExtractValueOrThrow<ValueType>(cache_value.get_abstract_value(),
__func__);
}
// Keep this method as small as possible to encourage inlining; it may be
// called *a lot*.
/** Returns a reference to the _known up-to-date_ abstract value of this cache
entry contained in the given Context. See GetKnownUpToDate() for more
information.
@pre `context` is a subcontext that is compatible with the subsystem that owns
this cache entry.
@throws std::exception if the value is not up to date. */
const AbstractValue& GetKnownUpToDateAbstract(
const ContextBase& context) const {
const CacheEntryValue& cache_value = get_cache_entry_value(context);
if (cache_value.is_out_of_date()) ThrowOutOfDate(__func__);
return cache_value.get_abstract_value();
}
/** Returns `true` if the current value of this cache entry is out of
date with respect to its prerequisites. If this returns `false` then the
Eval() method will not perform any computation when invoked, unless caching
has been disabled for this entry. If this returns `true` the
GetKnownUpToDate() methods will fail if invoked. */
bool is_out_of_date(const ContextBase& context) const {
return get_cache_entry_value(context).is_out_of_date();
}
/** (Debugging) Returns `true` if caching has been disabled for this cache
entry in the given `context`. That means Eval() will recalculate even if the
entry is marked up to date. */
bool is_cache_entry_disabled(const ContextBase& context) const {
return get_cache_entry_value(context).is_cache_entry_disabled();
}
/** (Debugging) Disables caching for this cache entry in the given `context`.
Eval() will recompute the cached value every time it is invoked, regardless
of the state of the out_of_date flag. That should have no effect on any
computed results, other than speed. See class documentation for ideas as to
what might be wrong if you see a change. Note that the `context` is `const`
here; cache entry values are mutable. */
void disable_caching(const ContextBase& context) const {
CacheEntryValue& value = get_mutable_cache_entry_value(context);
value.disable_caching();
}
/** (Debugging) Enables caching for this cache entry in the given `context`
if it was previously disabled. */
void enable_caching(const ContextBase& context) const {
CacheEntryValue& value = get_mutable_cache_entry_value(context);
value.enable_caching();
}
/** (Debugging) Marks this cache entry so that the corresponding
CacheEntryValue object in any allocated Context is created with its
`disabled` flag initially set. This can be useful for debugging when you have
observed a difference between cached and non-cached behavior that can't be
diagnosed with the runtime disable_caching() method.
@see disable_caching() */
void disable_caching_by_default() {
is_disabled_by_default_ = true;
}
/** (Debugging) Returns the current value of this flag. It is `false` unless
a call to `disable_caching_by_default()` has previously been made. */
bool is_disabled_by_default() const { return is_disabled_by_default_; }
/** Return the human-readable description for this %CacheEntry. */
const std::string& description() const { return description_; }
/** (Advanced) Returns a const reference to the CacheEntryValue object that
corresponds to this %CacheEntry, from the supplied Context. The returned
object contains the current value and tracks whether it is up to date with
respect to its prerequisites. If you just need the value, use the Eval()
method rather than this one. This method is constant time and _very_ fast in
all circumstances. */
const CacheEntryValue& get_cache_entry_value(
const ContextBase& context) const {
DRAKE_ASSERT_VOID(owning_system_->ValidateContext(context));
return context.get_cache().get_cache_entry_value(cache_index_);
}
/** (Advanced) Returns a mutable reference to the CacheEntryValue object that
corresponds to this %CacheEntry, from the supplied Context. Note that
`context` is const; cache values are mutable. Don't call this method unless
you know what you're doing. This method is constant time and _very_ fast in
all circumstances. */
CacheEntryValue& get_mutable_cache_entry_value(
const ContextBase& context) const {
DRAKE_ASSERT_VOID(owning_system_->ValidateContext(context));
return context.get_mutable_cache().get_mutable_cache_entry_value(
cache_index_);
}
/** Returns the CacheIndex used to locate this %CacheEntry within the
containing System. */
CacheIndex cache_index() const { return cache_index_; }
/** Returns the DependencyTicket used to register dependencies on the value
of this %CacheEntry. This can also be used to locate the DependencyTracker
that manages dependencies at runtime for the associated CacheEntryValue in
a Context. */
DependencyTicket ticket() const { return ticket_; }
/** (Advanced) Returns `true` if this cache entry was created without
specifying any prerequisites. This can be useful in determining whether
the apparent dependencies should be believed, or whether they may just be
due to some user's ignorance.
@note Currently we can't distinguish between "no prerequisites given"
(in which case we default to `all_sources_ticket()`) and "prerequisite
specified as `all_sources_ticket()`". Either of those cases makes this
method return `true` now, but we intend to change so that _explicit_
specification of `all_sources_ticket()` will be considered non-default. So
don't depend on the current behavior. */
bool has_default_prerequisites() const {
// TODO(sherm1) Make this bulletproof with a way to distinguish
// "took the default" from "specified the default value".
return prerequisites_of_calc_.size() == 1 &&
*prerequisites_of_calc_.begin() ==
DependencyTicket(internal::kAllSourcesTicket);
}
private:
// Unconditionally update the cache value, which has already been determined
// to be in need of recomputation (either because it is out of date or
// because caching was disabled).
void UpdateValue(const ContextBase& context) const {
// We can get a mutable cache entry value from a const context.
CacheEntryValue& mutable_cache_value =
get_mutable_cache_entry_value(context);
AbstractValue& value = mutable_cache_value.GetMutableAbstractValueOrThrow();
// If Calc() throws a recoverable exception, the cache remains out of date.
Calc(context, &value);
mutable_cache_value.mark_up_to_date();
}
// The value was unexpectedly out of date. Issue a helpful message.
void ThrowOutOfDate(const char* api) const {
throw std::logic_error(FormatName(api) + "value out of date.");
}
// The user told us the cache entry would have a particular concrete type
// but it doesn't.
template <typename ValueType>
void ThrowBadValueType(const char* api, const AbstractValue& abstract) const {
throw std::logic_error(FormatName(api) + "wrong value type <" +
NiceTypeName::Get<ValueType>() +
"> specified but actual type was <" +
abstract.GetNiceTypeName() + ">.");
}
// Pull a value of a given type from an abstract value or issue a nice
// message if the type is not correct. Keep this small and inlineable.
template <typename ValueType>
const ValueType& ExtractValueOrThrow(const AbstractValue& abstract,
const char* api) const {
const ValueType* value = abstract.maybe_get_value<ValueType>();
if (!value)
ThrowBadValueType<ValueType>(api, abstract);
return *value;
}
// Check that an AbstractValue provided to Calc() is suitable for this cache
// entry.
void CheckValidAbstractValue(const ContextBase& context,
const AbstractValue& proposed) const;
// Provides an identifying prefix for error messages.
std::string FormatName(const char* api) const;
const internal::SystemMessageInterface* const owning_system_;
const CacheIndex cache_index_;
const DependencyTicket ticket_;
// A human-readable description of this cache entry. Not interpreted by code
// but useful for error messages.
const std::string description_;
const ValueProducer value_producer_;
// The list of prerequisites for the calc_function. Whenever one of these
// changes, the cache value must be recalculated. Note that all possible
// prerequisites are internal to the containing subsystem, so the ticket
// alone is a unique specification of a prerequisite.
std::set<DependencyTicket> prerequisites_of_calc_;
bool is_disabled_by_default_{false};
};
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/system.cc | #include "drake/systems/framework/system.h"
#include <set>
#include <string_view>
#include <vector>
#include <fmt/format.h>
#include "drake/common/unused.h"
#include "drake/systems/framework/system_visitor.h"
namespace drake {
namespace systems {
template <typename T>
System<T>::~System() {}
template <typename T>
void System<T>::Accept(SystemVisitor<T>* v) const {
DRAKE_DEMAND(v != nullptr);
v->VisitSystem(*this);
}
template <typename T>
std::unique_ptr<System<T>> System<T>::Clone() const {
std::unique_ptr<System<T>> result;
// To implement cloning, we'll scalar convert back and forth through some
// intermediate scalar type "U". When T=double, we'll use U=AutoDiffXd since
// its the scalar type most likely to exist. When T={AutoDiffXd,Expression}
// we'll use U=double.
using U = std::conditional_t<std::is_same_v<T, double>, AutoDiffXd, double>;
// Convert T -> U -> T, stopping as soon as we hit a nullptr.
auto intermediate = this->template ToScalarTypeMaybe<U>();
if (intermediate != nullptr) {
result = intermediate->template ToScalarTypeMaybe<T>();
}
// If anything went wrong, throw an exception.
if (result == nullptr) {
throw std::logic_error(
fmt::format("System::Clone(): {} system '{}' does not support Cloning",
this->GetSystemType(), this->GetSystemPathname()));
}
return result;
}
template <typename T>
std::unique_ptr<Context<T>> System<T>::AllocateContext() const {
return dynamic_pointer_cast_or_throw<Context<T>>(
SystemBase::AllocateContext());
}
template <typename T>
std::unique_ptr<CompositeEventCollection<T>>
System<T>::AllocateCompositeEventCollection() const {
auto result = DoAllocateCompositeEventCollection();
result->set_system_id(get_system_id());
return result;
}
template <typename T>
std::unique_ptr<BasicVector<T>> System<T>::AllocateInputVector(
const InputPort<T>& input_port) const {
DRAKE_THROW_UNLESS(input_port.get_data_type() == kVectorValued);
const InputPortBase& self_input_port_base = this->GetInputPortBaseOrThrow(
__func__, input_port.get_index(), /* warn_deprecated = */ false);
DRAKE_THROW_UNLESS(&input_port == &self_input_port_base);
std::unique_ptr<AbstractValue> value = DoAllocateInput(input_port);
return value->get_value<BasicVector<T>>().Clone();
}
template <typename T>
std::unique_ptr<AbstractValue> System<T>::AllocateInputAbstract(
const InputPort<T>& input_port) const {
const int index = input_port.get_index();
DRAKE_ASSERT(index >= 0 && index < num_input_ports());
return DoAllocateInput(input_port);
}
template <typename T>
std::unique_ptr<SystemOutput<T>> System<T>::AllocateOutput() const {
// make_unique can't invoke this private constructor.
auto output = std::unique_ptr<SystemOutput<T>>(new SystemOutput<T>());
for (int i = 0; i < this->num_output_ports(); ++i) {
const auto& output_port = dynamic_cast<const OutputPort<T>&>(
this->GetOutputPortBaseOrThrow(__func__, i,
/* warn_deprecated = */ false));
output->add_port(output_port.Allocate());
}
output->set_system_id(get_system_id());
return output;
}
template <typename T>
std::unique_ptr<Context<T>> System<T>::CreateDefaultContext() const {
std::unique_ptr<Context<T>> context = AllocateContext();
SetDefaultContext(context.get());
return context;
}
template <typename T>
void System<T>::SetDefaultContext(Context<T>* context) const {
this->ValidateContext(context);
// Set the default parameters, checking that the number of parameters does
// not change.
const int num_params = context->num_numeric_parameter_groups();
SetDefaultParameters(*context, &context->get_mutable_parameters());
DRAKE_DEMAND(num_params == context->num_numeric_parameter_groups());
// Set the default state, checking that the number of state variables does
// not change.
const int n_xc = context->num_continuous_states();
const int n_xd = context->num_discrete_state_groups();
const int n_xa = context->num_abstract_states();
SetDefaultState(*context, &context->get_mutable_state());
DRAKE_DEMAND(n_xc == context->num_continuous_states());
DRAKE_DEMAND(n_xd == context->num_discrete_state_groups());
DRAKE_DEMAND(n_xa == context->num_abstract_states());
}
template <typename T>
void System<T>::SetRandomState(const Context<T>& context, State<T>* state,
RandomGenerator* generator) const {
unused(generator);
SetDefaultState(context, state);
}
template <typename T>
void System<T>::SetRandomParameters(const Context<T>& context,
Parameters<T>* parameters,
RandomGenerator* generator) const {
unused(generator);
SetDefaultParameters(context, parameters);
}
template <typename T>
void System<T>::SetRandomContext(Context<T>* context,
RandomGenerator* generator) const {
ValidateContext(context);
// Set the default state, checking that the number of state variables does
// not change.
const int n_xc = context->num_continuous_states();
const int n_xd = context->num_discrete_state_groups();
const int n_xa = context->num_abstract_states();
SetRandomState(*context, &context->get_mutable_state(), generator);
DRAKE_DEMAND(n_xc == context->num_continuous_states());
DRAKE_DEMAND(n_xd == context->num_discrete_state_groups());
DRAKE_DEMAND(n_xa == context->num_abstract_states());
// Set the default parameters, checking that the number of parameters does
// not change.
const int num_params = context->num_numeric_parameter_groups();
SetRandomParameters(*context, &context->get_mutable_parameters(),
generator);
DRAKE_DEMAND(num_params == context->num_numeric_parameter_groups());
}
template <typename T>
void System<T>::AllocateFixedInputs(Context<T>* context) const {
ValidateContext(context);
for (InputPortIndex i(0); i < num_input_ports(); ++i) {
const InputPortBase& input_port_base = this->GetInputPortBaseOrThrow(
__func__, i, /* warn_deprecated = */ false);
const auto& port = dynamic_cast<const InputPort<T>&>(input_port_base);
if (port.get_data_type() == kVectorValued) {
port.FixValue(context, *AllocateInputVector(port));
} else {
DRAKE_DEMAND(port.get_data_type() == kAbstractValued);
port.FixValue(context, *AllocateInputAbstract(port));
}
}
}
template <typename T>
bool System<T>::HasAnyDirectFeedthrough() const {
return GetDirectFeedthroughs().size() > 0;
}
template <typename T>
bool System<T>::HasDirectFeedthrough(int output_port) const {
std::multimap<int, int> pairs = GetDirectFeedthroughs();
for (const auto& pair : pairs) {
if (pair.second == output_port) return true;
}
return false;
}
template <typename T>
bool System<T>::HasDirectFeedthrough(int input_port, int output_port) const {
std::multimap<int, int> pairs = GetDirectFeedthroughs();
auto range = pairs.equal_range(input_port);
for (auto i = range.first; i != range.second; ++i) {
if (i->second == output_port) return true;
}
return false;
}
template <typename T>
EventStatus System<T>::Publish(const Context<T>& context,
const EventCollection<PublishEvent<T>>& events) const {
ValidateContext(context);
return DispatchPublishHandler(context, events);
}
template <typename T>
void System<T>::ForcedPublish(const Context<T>& context) const {
const EventStatus status =
Publish(context, this->get_forced_publish_events());
status.ThrowOnFailure(__func__);
}
template <typename T>
const T& System<T>::EvalPotentialEnergy(const Context<T>& context) const {
ValidateContext(context);
const CacheEntry& entry =
this->get_cache_entry(potential_energy_cache_index_);
return entry.Eval<T>(context);
}
template <typename T>
const T& System<T>::EvalKineticEnergy(const Context<T>& context) const {
ValidateContext(context);
const CacheEntry& entry =
this->get_cache_entry(kinetic_energy_cache_index_);
return entry.Eval<T>(context);
}
template <typename T>
const T& System<T>::EvalConservativePower(const Context<T>& context) const {
ValidateContext(context);
const CacheEntry& entry =
this->get_cache_entry(conservative_power_cache_index_);
return entry.Eval<T>(context);
}
template <typename T>
const T& System<T>::EvalNonConservativePower(const Context<T>& context) const {
ValidateContext(context);
const CacheEntry& entry =
this->get_cache_entry(nonconservative_power_cache_index_);
return entry.Eval<T>(context);
}
template <typename T>
SystemConstraintIndex System<T>::AddExternalConstraint(
ExternalSystemConstraint constraint) {
const auto& calc = constraint.get_calc<T>();
if (calc) {
constraints_.emplace_back(std::make_unique<SystemConstraint<T>>(
this, calc, constraint.bounds(), constraint.description()));
} else {
constraints_.emplace_back(std::make_unique<SystemConstraint<T>>(
this, fmt::format(
"{} (disabled for this scalar type)",
constraint.description())));
}
external_constraints_.emplace_back(std::move(constraint));
return SystemConstraintIndex(constraints_.size() - 1);
}
template <typename T>
void System<T>::CalcTimeDerivatives(const Context<T>& context,
ContinuousState<T>* derivatives) const {
DRAKE_DEMAND(derivatives != nullptr);
ValidateContext(context);
ValidateCreatedForThisSystem(derivatives);
DoCalcTimeDerivatives(context, derivatives);
}
template <typename T>
void System<T>::CalcImplicitTimeDerivativesResidual(
const Context<T>& context, const ContinuousState<T>& proposed_derivatives,
EigenPtr<VectorX<T>> residual) const {
DRAKE_DEMAND(residual != nullptr);
if (residual->size() != this->implicit_time_derivatives_residual_size()) {
throw std::logic_error(fmt::format(
"CalcImplicitTimeDerivativesResidual(): expected "
"residual vector of size {} but got one of size {}.\n"
"Use AllocateImplicitTimeDerivativesResidual() to "
"obtain a vector of the correct size.",
this->implicit_time_derivatives_residual_size(), residual->size()));
}
ValidateContext(context);
ValidateCreatedForThisSystem(proposed_derivatives);
DoCalcImplicitTimeDerivativesResidual(context, proposed_derivatives,
residual);
}
template <typename T>
EventStatus System<T>::CalcDiscreteVariableUpdate(
const Context<T>& context,
const EventCollection<DiscreteUpdateEvent<T>>& events,
DiscreteValues<T>* discrete_state) const {
ValidateContext(context);
ValidateCreatedForThisSystem(discrete_state);
return DispatchDiscreteVariableUpdateHandler(context, events, discrete_state);
}
template <typename T>
void System<T>::ApplyDiscreteVariableUpdate(
const EventCollection<DiscreteUpdateEvent<T>>& events,
DiscreteValues<T>* discrete_state, Context<T>* context) const {
ValidateContext(context);
ValidateCreatedForThisSystem(discrete_state);
DoApplyDiscreteVariableUpdate(events, discrete_state, context);
}
template <typename T>
void System<T>::CalcForcedDiscreteVariableUpdate(
const Context<T>& context,
DiscreteValues<T>* discrete_state) const {
const EventStatus status = CalcDiscreteVariableUpdate(
context, this->get_forced_discrete_update_events(), discrete_state);
status.ThrowOnFailure(__func__);
}
template <typename T>
EventStatus System<T>::CalcUnrestrictedUpdate(
const Context<T>& context,
const EventCollection<UnrestrictedUpdateEvent<T>>& events,
State<T>* state) const {
ValidateContext(context);
ValidateCreatedForThisSystem(state);
const int continuous_state_dim = state->get_continuous_state().size();
const int discrete_state_dim = state->get_discrete_state().num_groups();
const int abstract_state_dim = state->get_abstract_state().size();
const EventStatus status =
DispatchUnrestrictedUpdateHandler(context, events, state);
if (continuous_state_dim != state->get_continuous_state().size() ||
discrete_state_dim != state->get_discrete_state().num_groups() ||
abstract_state_dim != state->get_abstract_state().size()) {
throw std::logic_error(
"State variable dimensions cannot be changed "
"in CalcUnrestrictedUpdate().");
}
return status;
}
template <typename T>
void System<T>::ApplyUnrestrictedUpdate(
const EventCollection<UnrestrictedUpdateEvent<T>>& events,
State<T>* state, Context<T>* context) const {
ValidateContext(context);
ValidateCreatedForThisSystem(state);
DoApplyUnrestrictedUpdate(events, state, context);
}
template <typename T>
void System<T>::CalcForcedUnrestrictedUpdate(const Context<T>& context,
State<T>* state) const {
const EventStatus status = CalcUnrestrictedUpdate(
context, this->get_forced_unrestricted_update_events(), state);
status.ThrowOnFailure(__func__);
}
template <typename T>
T System<T>::CalcNextUpdateTime(const Context<T>& context,
CompositeEventCollection<T>* events) const {
ValidateContext(context);
ValidateCreatedForThisSystem(events);
DRAKE_DEMAND(events != nullptr);
events->Clear();
T time{NAN};
DoCalcNextUpdateTime(context, events, &time);
using std::isnan, std::isfinite;
if (isnan(time)) {
throw std::logic_error(
fmt::format("System::CalcNextUpdateTime(): {} system '{}' overrode "
"DoCalcNextUpdateTime() but at time={} it returned with no "
"update time set (or the update time was set to NaN). "
"Return infinity to indicate no next update time.",
this->GetSystemType(), this->GetSystemPathname(),
ExtractDoubleOrThrow(context.get_time())));
}
if (isfinite(time) && !events->HasEvents()) {
throw std::logic_error(fmt::format(
"System::CalcNextUpdateTime(): {} system '{}' overrode "
"DoCalcNextUpdateTime() but at time={} it returned update "
"time {} with an empty Event collection. Return infinity "
"to indicate no next update time; otherwise at least one "
"Event object must be provided even if it does nothing.",
this->GetSystemType(), this->GetSystemPathname(),
ExtractDoubleOrThrow(context.get_time()), ExtractDoubleOrThrow(time)));
}
// If the context contains a perturbed current time, and
// DoCalcNextUpdateTime() returned "right now" (which would be the
// perturbed time here), we need to adjust the returned time to the actual
// time. (Simulator::Initialize() perturbs time in that way.)
if (context.get_true_time() && time == context.get_time())
time = *context.get_true_time();
return time;
}
template <typename T>
const DiscreteValues<T>& System<T>::EvalUniquePeriodicDiscreteUpdate(
const Context<T>& context) const {
const CacheEntry& entry =
this->get_cache_entry(unique_periodic_discrete_update_cache_index_);
return entry.Eval<DiscreteValues<T>>(context);
}
// Unit testing for this method is in diagram_test.cc where it is used as
// the leaf computation for the Diagram recursion.
template <typename T>
void System<T>::CalcUniquePeriodicDiscreteUpdate(
const Context<T>& context, DiscreteValues<T>* discrete_values) const {
ValidateContext(context);
ValidateCreatedForThisSystem(discrete_values);
// TODO(sherm1) We only need the DiscreteUpdateEvent portion of the
// CompositeEventCollection but don't have a convenient way to allocate
// that in a Leaf vs. Diagram agnostic way. Add that if needed for speed.
auto collection = AllocateCompositeEventCollection();
std::optional<PeriodicEventData> timing;
FindUniquePeriodicDiscreteUpdatesOrThrow(
__func__, *this, context, &timing,
&collection->get_mutable_discrete_update_events());
if (!timing.has_value()) {
throw std::logic_error(
fmt::format("{}(): there are no periodic discrete "
"update events in this System.", __func__));
}
// This should come up with the same result although calculated independently.
// Too expensive to check in Release, but Debug is leisurely.
DRAKE_ASSERT(*timing == *GetUniquePeriodicDiscreteUpdateAttribute());
// Start with scratch discrete variables equal to the current values.
discrete_values->SetFrom(context.get_discrete_state());
// Then let the event handlers modify them or not.
const EventStatus status = this->CalcDiscreteVariableUpdate(
context, collection->get_discrete_update_events(), discrete_values);
status.ThrowOnFailure(__func__);
}
template <typename T>
void System<T>::GetPeriodicEvents(const Context<T>& context,
CompositeEventCollection<T>* events) const {
ValidateContext(context);
ValidateCreatedForThisSystem(events);
events->Clear();
DoGetPeriodicEvents(context, events);
}
template <typename T>
void System<T>::GetPerStepEvents(const Context<T>& context,
CompositeEventCollection<T>* events) const {
ValidateContext(context);
ValidateCreatedForThisSystem(events);
events->Clear();
DoGetPerStepEvents(context, events);
}
template <typename T>
void System<T>::GetInitializationEvents(
const Context<T>& context,
CompositeEventCollection<T>* events) const {
ValidateContext(context);
ValidateCreatedForThisSystem(events);
events->Clear();
DoGetInitializationEvents(context, events);
}
template <typename T>
void System<T>::ExecuteInitializationEvents(Context<T>* context) const {
auto discrete_updates = AllocateDiscreteVariables();
auto state = context->CloneState();
auto init_events = AllocateCompositeEventCollection();
// NOTE: The execution order here must match the code in
// Simulator::Initialize().
GetInitializationEvents(*context, init_events.get());
// Do unrestricted updates first.
if (init_events->get_unrestricted_update_events().HasEvents()) {
const EventStatus status = CalcUnrestrictedUpdate(
*context, init_events->get_unrestricted_update_events(), state.get());
status.ThrowOnFailure(__func__);
ApplyUnrestrictedUpdate(init_events->get_unrestricted_update_events(),
state.get(), context);
}
// Do restricted (discrete variable) updates next.
if (init_events->get_discrete_update_events().HasEvents()) {
const EventStatus status = CalcDiscreteVariableUpdate(
*context, init_events->get_discrete_update_events(),
discrete_updates.get());
status.ThrowOnFailure(__func__);
ApplyDiscreteVariableUpdate(init_events->get_discrete_update_events(),
discrete_updates.get(), context);
}
// Do any publishes last.
if (init_events->get_publish_events().HasEvents()) {
const EventStatus status =
Publish(*context, init_events->get_publish_events());
status.ThrowOnFailure(__func__);
}
}
template <typename T>
std::optional<PeriodicEventData>
System<T>::GetUniquePeriodicDiscreteUpdateAttribute() const {
std::optional<PeriodicEventData> saved_attr;
auto periodic_events_map = MapPeriodicEventsByTiming();
for (const auto& saved_attr_and_vector : periodic_events_map) {
for (const auto& event : saved_attr_and_vector.second) {
if (event->is_discrete_update()) {
if (saved_attr)
return std::nullopt;
saved_attr = saved_attr_and_vector.first;
break;
}
}
}
return saved_attr;
}
template <typename T>
bool System<T>::IsDifferenceEquationSystem(double* time_period) const {
if (num_continuous_states() || num_abstract_states()) { return false; }
if (num_discrete_state_groups() != 1) {
return false;
}
std::optional<PeriodicEventData> periodic_data =
GetUniquePeriodicDiscreteUpdateAttribute();
if (!periodic_data) { return false; }
if (periodic_data->offset_sec() != 0.0) { return false; }
if (time_period != nullptr) {
*time_period = periodic_data->period_sec();
}
return true;
}
template <typename T>
bool System<T>::IsDifferentialEquationSystem() const {
if (num_discrete_state_groups() || num_abstract_states()) { return false; }
for (int i = 0; i < num_input_ports(); ++i) {
if (get_input_port(i).get_data_type() != PortDataType::kVectorValued) {
return false;
}
}
return true;
}
template <typename T>
std::map<PeriodicEventData, std::vector<const Event<T>*>,
PeriodicEventDataComparator>
System<T>::MapPeriodicEventsByTiming(const Context<T>* context) const {
std::unique_ptr<Context<T>> dummy_context;
const Context<T>* context_to_use = context;
if (context_to_use == nullptr) {
dummy_context = AllocateContext();
context_to_use = dummy_context.get();
}
return DoMapPeriodicEventsByTiming(*context_to_use);
}
template <typename T>
void System<T>::CalcOutput(const Context<T>& context,
SystemOutput<T>* outputs) const {
DRAKE_DEMAND(outputs != nullptr);
ValidateContext(context);
ValidateCreatedForThisSystem(outputs);
for (OutputPortIndex i(0); i < num_output_ports(); ++i) {
const auto& output_port = dynamic_cast<const OutputPort<T>&>(
this->GetOutputPortBaseOrThrow(__func__, i,
/* warn_deprecated = */ false));
// TODO(sherm1) Would be better to use Eval() here but we don't have
// a generic abstract assignment capability that would allow us to
// copy into existing memory in `outputs` (rather than clone). User
// code depends on memory stability in SystemOutput.
output_port.Calc(context, outputs->GetMutableData(i));
}
}
template <typename T>
T System<T>::CalcPotentialEnergy(const Context<T>& context) const {
ValidateContext(context);
return DoCalcPotentialEnergy(context);
}
template <typename T>
T System<T>::CalcKineticEnergy(const Context<T>& context) const {
ValidateContext(context);
return DoCalcKineticEnergy(context);
}
template <typename T>
T System<T>::CalcConservativePower(const Context<T>& context) const {
ValidateContext(context);
return DoCalcConservativePower(context);
}
template <typename T>
T System<T>::CalcNonConservativePower(const Context<T>& context) const {
ValidateContext(context);
return DoCalcNonConservativePower(context);
}
template <typename T>
void System<T>::MapVelocityToQDot(const Context<T>& context,
const VectorBase<T>& generalized_velocity,
VectorBase<T>* qdot) const {
MapVelocityToQDot(context, generalized_velocity.CopyToVector(), qdot);
}
template <typename T>
void System<T>::MapVelocityToQDot(
const Context<T>& context,
const Eigen::Ref<const VectorX<T>>& generalized_velocity,
VectorBase<T>* qdot) const {
this->ValidateContext(context);
DoMapVelocityToQDot(context, generalized_velocity, qdot);
}
template <typename T>
void System<T>::MapQDotToVelocity(const Context<T>& context,
const VectorBase<T>& qdot,
VectorBase<T>* generalized_velocity) const {
MapQDotToVelocity(context, qdot.CopyToVector(), generalized_velocity);
}
template <typename T>
void System<T>::MapQDotToVelocity(const Context<T>& context,
const Eigen::Ref<const VectorX<T>>& qdot,
VectorBase<T>* generalized_velocity) const {
this->ValidateContext(context);
DoMapQDotToVelocity(context, qdot, generalized_velocity);
}
template <typename T>
const Context<T>& System<T>::GetSubsystemContext(
const System<T>& subsystem,
const Context<T>& context) const {
ValidateContext(context);
auto ret = DoGetTargetSystemContext(subsystem, &context);
if (ret != nullptr) return *ret;
throw std::logic_error(
fmt::format("GetSubsystemContext(): {} subsystem '{}' is not "
"contained in {} System '{}'.",
subsystem.GetSystemType(), subsystem.GetSystemPathname(),
this->GetSystemType(), this->GetSystemPathname()));
}
template <typename T>
Context<T>& System<T>::GetMutableSubsystemContext(const System<T>& subsystem,
Context<T>* context) const {
DRAKE_ASSERT(context != nullptr);
// Make use of the const method to avoid code duplication.
const Context<T>& subcontext = GetSubsystemContext(subsystem, *context);
return const_cast<Context<T>&>(subcontext);
}
template <typename T>
const Context<T>& System<T>::GetMyContextFromRoot(
const Context<T>& root_context) const {
if (!root_context.is_root_context())
throw std::logic_error(
"GetMyContextFromRoot(): given context must be a root context.");
const internal::SystemParentServiceInterface* parent_service =
this->get_parent_service();
if (!parent_service) // This is the root System.
return root_context;
return static_cast<const System<T>&>(parent_service->GetRootSystemBase())
.GetSubsystemContext(*this, root_context);
}
template <typename T>
Context<T>& System<T>::GetMyMutableContextFromRoot(
Context<T>* root_context) const {
DRAKE_DEMAND(root_context != nullptr);
// Make use of the const method to avoid code duplication.
const Context<T>& subcontext = GetMyContextFromRoot(*root_context);
return const_cast<Context<T>&>(subcontext);
}
template <typename T>
const Context<T>* System<T>::DoGetTargetSystemContext(
const System<T>& target_system, const Context<T>* context) const {
if (&target_system == this) return context;
return nullptr;
}
template <typename T>
State<T>* System<T>::DoGetMutableTargetSystemState(
const System<T>& target_system, State<T>* state) const {
if (&target_system == this) return state;
return nullptr;
}
template <typename T>
const State<T>* System<T>::DoGetTargetSystemState(
const System<T>& target_system, const State<T>* state) const {
if (&target_system == this) return state;
return nullptr;
}
template <typename T>
const ContinuousState<T>* System<T>::DoGetTargetSystemContinuousState(
const System<T>& target_system,
const ContinuousState<T>* xc) const {
if (&target_system == this) return xc;
return nullptr;
}
template <typename T>
CompositeEventCollection<T>*
System<T>::DoGetMutableTargetSystemCompositeEventCollection(
const System<T>& target_system,
CompositeEventCollection<T>* events) const {
if (&target_system == this) return events;
return nullptr;
}
template <typename T>
const CompositeEventCollection<T>*
System<T>::DoGetTargetSystemCompositeEventCollection(
const System<T>& target_system,
const CompositeEventCollection<T>* events) const {
if (&target_system == this) return events;
return nullptr;
}
template <typename T>
const InputPort<T>& System<T>::GetSoleInputPort() const {
// Give a nice message if there were no inputs at all.
if (num_input_ports() == 0) {
throw std::logic_error(fmt::format(
"System::get_input_port(): {} system '{}' does not have any inputs",
this->GetSystemType(), this->GetSystemPathname()));
}
// Check if there is exactly one non-deprecated input port (and return it).
int num_non_deprecated = 0;
InputPortIndex non_deprecated_index;
for (InputPortIndex i{0}; i < num_input_ports(); i++) {
const InputPortBase& port_base = this->GetInputPortBaseOrThrow(
__func__, i, /* warn_deprecated = */ false);
if (port_base.get_deprecation() == std::nullopt) {
++num_non_deprecated;
non_deprecated_index = i;
}
}
if (num_non_deprecated == 1) {
return get_input_port(non_deprecated_index);
}
// Too many inputs.
throw std::logic_error(fmt::format(
"System::get_input_port(): {} system '{}' has {} inputs, so this "
"convenience function cannot be used; instead, use another overload "
"e.g. get_input_port(InputPortIndex) or GetInputPort(string)",
this->GetSystemType(), this->GetSystemPathname(), num_input_ports()));
}
template <typename T>
const InputPort<T>* System<T>::get_input_port_selection(
std::variant<InputPortSelection, InputPortIndex> port_index) const {
if (std::holds_alternative<InputPortIndex>(port_index)) {
return &get_input_port(std::get<InputPortIndex>(port_index));
}
switch (std::get<InputPortSelection>(port_index)) {
case InputPortSelection::kUseFirstInputIfItExists:
if (num_input_ports() > 0) {
return &get_input_port(0);
}
return nullptr;
case InputPortSelection::kNoInput:
return nullptr;
}
return nullptr;
}
template <typename T>
const InputPort<T>& System<T>::GetInputPort(
const std::string& port_name) const {
for (InputPortIndex i{0}; i < num_input_ports(); i++) {
const InputPortBase& port_base = this->GetInputPortBaseOrThrow(
__func__, i, /* warn_deprecated = */ false);
if (port_name == port_base.get_name()) {
return get_input_port(i);
}
}
std::vector<std::string_view> port_names;
port_names.reserve(num_input_ports());
for (InputPortIndex i{0}; i < num_input_ports(); i++) {
const InputPortBase& port_base = this->GetInputPortBaseOrThrow(
__func__, i, /* warn_deprecated = */ false);
port_names.push_back(port_base.get_name());
}
if (port_names.empty()) {
port_names.push_back("it has no input ports");
}
throw std::logic_error(fmt::format(
"System {} does not have an input port named {} "
"(valid port names: {})",
GetSystemName(), port_name, fmt::join(port_names, ", ")));
}
template <typename T>
bool System<T>::HasInputPort(
const std::string& port_name) const {
for (InputPortIndex i{0}; i < num_input_ports(); i++) {
const InputPortBase& port_base = this->GetInputPortBaseOrThrow(
__func__, i, /* warn_deprecated = */ false);
if (port_name == port_base.get_name()) {
// Call the getter (ignoring its return value), to allow deprecation
// warnings to trigger.
get_input_port(i);
return true;
}
}
return false;
}
template <typename T>
const OutputPort<T>& System<T>::GetSoleOutputPort() const {
// Give a nice message if there were no outputs at all.
if (num_output_ports() == 0) {
throw std::logic_error(fmt::format(
"System::get_output_port(): {} system '{}' does not have any outputs",
this->GetSystemType(), this->GetSystemPathname()));
}
// Check if there is exactly one non-deprecated output port (and return it).
int num_non_deprecated = 0;
OutputPortIndex non_deprecated_index;
for (OutputPortIndex i{0}; i < num_output_ports(); i++) {
const OutputPortBase& port_base = this->GetOutputPortBaseOrThrow(
__func__, i, /* warn_deprecated = */ false);
if (port_base.get_deprecation() == std::nullopt) {
++num_non_deprecated;
non_deprecated_index = i;
}
}
if (num_non_deprecated == 1) {
return get_output_port(non_deprecated_index);
}
// Too many outputs.
throw std::logic_error(fmt::format(
"System::get_output_port(): {} system '{}' has {} outputs, so this "
"convenience function cannot be used; instead, use another overload "
"e.g. get_output_port(OutputPortIndex) or GetOutputPort(string)",
this->GetSystemType(), this->GetSystemPathname(), num_output_ports()));
}
template <typename T>
const OutputPort<T>* System<T>::get_output_port_selection(
std::variant<OutputPortSelection, OutputPortIndex> port_index) const {
if (std::holds_alternative<OutputPortIndex>(port_index)) {
return &get_output_port(std::get<OutputPortIndex>(port_index));
}
switch (std::get<OutputPortSelection>(port_index)) {
case OutputPortSelection::kUseFirstOutputIfItExists:
if (num_output_ports() > 0) {
return &get_output_port(0);
}
return nullptr;
case OutputPortSelection::kNoOutput:
return nullptr;
}
return nullptr;
}
template <typename T>
const OutputPort<T>& System<T>::GetOutputPort(
const std::string& port_name) const {
for (OutputPortIndex i{0}; i < num_output_ports(); i++) {
const OutputPortBase& port_base = this->GetOutputPortBaseOrThrow(
__func__, i, /* warn_deprecated = */ false);
if (port_name == port_base.get_name()) {
return get_output_port(i);
}
}
std::vector<std::string_view> port_names;
port_names.reserve(num_output_ports());
for (OutputPortIndex i{0}; i < num_output_ports(); i++) {
port_names.push_back(get_output_port_base(i).get_name());
}
if (port_names.empty()) {
port_names.push_back("it has no output ports");
}
throw std::logic_error(fmt::format(
"System {} does not have an output port named {} "
"(valid port names: {})",
GetSystemName(), port_name, fmt::join(port_names, ", ")));
}
template <typename T>
bool System<T>::HasOutputPort(
const std::string& port_name) const {
for (OutputPortIndex i{0}; i < num_output_ports(); i++) {
const OutputPortBase& port_base = this->GetOutputPortBaseOrThrow(
__func__, i, /* warn_deprecated = */ false);
if (port_name == port_base.get_name()) {
// Call the getter (ignoring its return value), to allow deprecation
// warnings to trigger.
get_output_port(i);
return true;
}
}
return false;
}
template <typename T>
int System<T>::num_constraints() const {
return static_cast<int>(constraints_.size());
}
template <typename T>
const SystemConstraint<T>& System<T>::get_constraint(
SystemConstraintIndex constraint_index) const {
if (constraint_index < 0 || constraint_index >= num_constraints()) {
throw std::out_of_range("System " + get_name() + ": Constraint index " +
std::to_string(constraint_index) +
" is out of range. There are only " +
std::to_string(num_constraints()) +
" constraints.");
}
return *constraints_[constraint_index];
}
template <typename T>
boolean<T> System<T>::CheckSystemConstraintsSatisfied(
const Context<T>& context, double tol) const {
ValidateContext(context);
DRAKE_DEMAND(tol >= 0.0);
boolean<T> result{true};
for (const auto& constraint : constraints_) {
result = result && constraint->CheckSatisfied(context, tol);
// If T is a real number (not a symbolic expression), we can bail out
// early with a diagnostic when the first constraint fails.
if (scalar_predicate<T>::is_bool && !result) {
DRAKE_LOGGER_DEBUG(
"Context fails to satisfy SystemConstraint {}",
constraint->description());
return result;
}
}
return result;
}
template <typename T>
VectorX<T> System<T>::CopyContinuousStateVector(
const Context<T>& context) const {
return context.get_continuous_state().CopyToVector();
}
template <typename T>
std::unique_ptr<System<AutoDiffXd>> System<T>::ToAutoDiffXd() const {
return System<T>::ToAutoDiffXd(*this);
}
template <typename T>
std::unique_ptr<System<AutoDiffXd>> System<T>::ToAutoDiffXdMaybe() const {
return ToScalarTypeMaybe<AutoDiffXd>();
}
template <typename T>
std::unique_ptr<System<symbolic::Expression>> System<T>::ToSymbolic() const {
return System<T>::ToSymbolic(*this);
}
template <typename T>
std::unique_ptr<System<symbolic::Expression>>
System<T>::ToSymbolicMaybe() const {
return ToScalarTypeMaybe<symbolic::Expression>();
}
template <typename T>
void System<T>::FixInputPortsFrom(const System<double>& other_system,
const Context<double>& other_context,
Context<T>* target_context) const {
ValidateContext(target_context);
other_system.ValidateContext(other_context);
for (int i = 0; i < num_input_ports(); ++i) {
const InputPortBase& input_port_base = this->GetInputPortBaseOrThrow(
__func__, i, /* warn_deprecated = */ false);
const InputPortBase& other_port_base = other_system.GetInputPortBaseOrThrow(
__func__, i, /* warn_deprecated = */ false);
const auto& input_port =
dynamic_cast<const InputPort<T>&>(input_port_base);
const auto& other_port =
dynamic_cast<const InputPort<double>&>(other_port_base);
if (!other_port.HasValue(other_context)) {
continue;
}
switch (input_port.get_data_type()) {
case kVectorValued: {
// For vector-valued input ports, we placewise initialize a fixed
// input vector using the explicit conversion from double to T.
const VectorX<double>& other_vec = other_port.Eval(other_context);
auto our_vec = this->AllocateInputVector(input_port);
for (int j = 0; j < our_vec->size(); ++j) {
(*our_vec)[j] = T(other_vec[j]);
}
input_port.FixValue(target_context, *our_vec);
continue;
}
case kAbstractValued: {
// For abstract-valued input ports, we just clone the value and fix
// it to the port.
const auto& other_value =
other_port.Eval<AbstractValue>(other_context);
input_port.FixValue(target_context, other_value);
continue;
}
}
DRAKE_UNREACHABLE();
}
}
template <typename T>
const SystemScalarConverter& System<T>::get_system_scalar_converter() const {
return system_scalar_converter_;
}
template <typename T>
void System<T>::GetWitnessFunctions(
const Context<T>& context,
std::vector<const WitnessFunction<T>*>* w) const {
DRAKE_DEMAND(w != nullptr);
DRAKE_DEMAND(w->empty());
ValidateContext(context);
DoGetWitnessFunctions(context, w);
}
template <typename T>
T System<T>::CalcWitnessValue(
const Context<T>& context,
const WitnessFunction<T>& witness_func) const {
ValidateContext(context);
return DoCalcWitnessValue(context, witness_func);
}
template <typename T>
void System<T>::DoGetWitnessFunctions(const Context<T>&,
std::vector<const WitnessFunction<T>*>*) const {
}
template <typename T>
System<T>::System(SystemScalarConverter converter)
: system_scalar_converter_(std::move(converter)) {
// Note that configuration and kinematics tickets also include dependence
// on parameters and accuracy, but not time or input ports.
// Potential and kinetic energy, and conservative power that measures
// the transfer between them, must _not_ be (explicitly) time dependent.
// See API documentation above for Eval{Potential|Kinetic}Energy() and
// EvalConservativePower() to see why.
// TODO(sherm1) Due to issue #9171 we cannot always recognize which
// variables contribute to configuration so we'll invalidate on all changes
// except for time and inputs. Once #9171 is resolved, we should use the
// more specific configuration, kinematics, and mass tickets.
const std::set<DependencyTicket> energy_prereqs_for_9171{
accuracy_ticket(), all_state_ticket(), all_parameters_ticket()};
potential_energy_cache_index_ =
DeclareCacheEntry("potential energy",
ValueProducer(this, &System<T>::CalcPotentialEnergy),
energy_prereqs_for_9171) // After #9171: configuration + mass.
.cache_index();
kinetic_energy_cache_index_ =
DeclareCacheEntry("kinetic energy",
ValueProducer(this, &System<T>::CalcKineticEnergy),
energy_prereqs_for_9171) // After #9171: kinematics + mass.
.cache_index();
conservative_power_cache_index_ =
DeclareCacheEntry("conservative power",
ValueProducer(this, &System<T>::CalcConservativePower),
energy_prereqs_for_9171) // After #9171: kinematics + mass.
.cache_index();
// Only non-conservative power can have an explicit time or input
// port dependence. See API documentation above for
// EvalNonConservativePower() to see why.
nonconservative_power_cache_index_ =
DeclareCacheEntry("non-conservative power",
ValueProducer(this, &System<T>::CalcNonConservativePower),
{all_sources_ticket()}) // This is correct.
.cache_index();
// We must assume that time derivatives can depend on *any* context source.
time_derivatives_cache_index_ =
this->DeclareCacheEntryWithKnownTicket(
xcdot_ticket(), "time derivatives",
ValueProducer(
this,
&System<T>::AllocateTimeDerivatives,
&System<T>::CalcTimeDerivatives),
{all_sources_ticket()})
.cache_index();
// TODO(sherm1) Ideally a Diagram-level DiscreteValues cache object allocated
// here would reference its LeafSystem-level DiscreteValues cache objects
// rather than owning all these objects itself, and invoking
// EvalUniquePeriodicDiscreteUpdate() on the Diagram would update all the
// LeafSystem entries also. That would require a specialized version
// of AllocateDiscreteVariables() that would build the Diagram object from
// references to the already-allocated subsystem cache entries.
unique_periodic_discrete_update_cache_index_ =
this->DeclareCacheEntryWithKnownTicket(
xd_unique_periodic_update_ticket(),
"unique periodic discrete variable update",
ValueProducer(this, &System<T>::AllocateDiscreteVariables,
&System<T>::CalcUniquePeriodicDiscreteUpdate),
{all_sources_ticket()})
.cache_index();
}
template <typename T>
InputPort<T>& System<T>::DeclareInputPort(
std::variant<std::string, UseDefaultName> name, PortDataType type,
int size, std::optional<RandomDistribution> random_type) {
const InputPortIndex port_index(num_input_ports());
const DependencyTicket port_ticket(this->assign_next_dependency_ticket());
auto eval = [this, port_index](const ContextBase& context_base) {
return this->EvalAbstractInput(context_base, port_index);
};
auto alloc = [this, port_index]() {
return this->AllocateInputAbstract(this->get_input_port(port_index));
};
auto port = internal::FrameworkFactory::Make<InputPort<T>>(
this, this, get_system_id(), NextInputPortName(std::move(name)),
port_index, port_ticket, type, size, random_type, std::move(eval),
std::move(alloc));
InputPort<T>* port_ptr = port.get();
this->AddInputPort(std::move(port));
return *port_ptr;
}
template <typename T>
SystemConstraintIndex System<T>::AddConstraint(
std::unique_ptr<SystemConstraint<T>> constraint) {
DRAKE_DEMAND(constraint != nullptr);
DRAKE_DEMAND(&constraint->get_system() == this);
if (!external_constraints_.empty()) {
throw std::logic_error(fmt::format(
"System {} cannot add an internal constraint (named {}) "
"after an external constraint (named {}) has already been added",
GetSystemName(), constraint->description(),
external_constraints_.front().description()));
}
constraint->set_system_id(this->get_system_id());
constraints_.push_back(std::move(constraint));
return SystemConstraintIndex(constraints_.size() - 1);
}
template <typename T>
void System<T>::DoCalcTimeDerivatives(const Context<T>& context,
ContinuousState<T>* derivatives) const {
// This default implementation is only valid for Systems with no continuous
// state. Other Systems must override this method!
unused(context);
DRAKE_DEMAND(derivatives->size() == 0);
}
template <typename T>
void System<T>::DoCalcImplicitTimeDerivativesResidual(
const Context<T>& context, const ContinuousState<T>& proposed_derivatives,
EigenPtr<VectorX<T>> residual) const {
// As documented, we can assume residual is non-null, its length matches the
// declared size, and proposed_derivatives is compatible with this System.
// However, this default implementation has an additional restriction: the
// declared residual size must match the number of continuous states (that's
// the default if no one says otherwise).
if (residual->size() != proposed_derivatives.size()) {
throw std::logic_error(fmt::format(
"System::DoCalcImplicitTimeDerivativesResidual(): "
"This default implementation requires that the declared residual size "
"(here {}) matches the number of continuous state variables ({}). "
"You must override this method if your residual is a different size.",
residual->size(), proposed_derivatives.size()));
}
proposed_derivatives.get_vector().CopyToPreSizedVector(residual);
*residual -= EvalTimeDerivatives(context).CopyToVector();
}
template <typename T>
void System<T>::DoCalcNextUpdateTime(const Context<T>& context,
CompositeEventCollection<T>* events,
T* time) const {
unused(context, events);
*time = std::numeric_limits<double>::infinity();
}
template <typename T>
void System<T>::DoGetPeriodicEvents(
const Context<T>& context,
CompositeEventCollection<T>* events) const {
unused(context, events);
}
template <typename T>
void System<T>::DoGetPerStepEvents(
const Context<T>& context,
CompositeEventCollection<T>* events) const {
unused(context, events);
}
template <typename T>
void System<T>::DoGetInitializationEvents(
const Context<T>& context,
CompositeEventCollection<T>* events) const {
unused(context, events);
}
template <typename T>
T System<T>::DoCalcPotentialEnergy(const Context<T>& context) const {
unused(context);
return T(0);
}
template <typename T>
T System<T>::DoCalcKineticEnergy(const Context<T>& context) const {
unused(context);
return T(0);
}
template <typename T>
T System<T>::DoCalcConservativePower(const Context<T>& context) const {
unused(context);
return T(0);
}
template <typename T>
T System<T>::DoCalcNonConservativePower(const Context<T>& context) const {
unused(context);
return T(0);
}
template <typename T>
void System<T>::DoMapQDotToVelocity(const Context<T>& context,
const Eigen::Ref<const VectorX<T>>& qdot,
VectorBase<T>* generalized_velocity) const {
unused(context);
// In the particular case where generalized velocity and generalized
// configuration are not even the same size, we detect this error and abort.
// This check will thus not identify cases where the generalized velocity
// and time derivative of generalized configuration are identically sized
// but not identical!
const int n = qdot.size();
// You need to override System<T>::DoMapQDottoVelocity!
DRAKE_THROW_UNLESS(generalized_velocity->size() == n);
generalized_velocity->SetFromVector(qdot);
}
template <typename T>
void System<T>::DoMapVelocityToQDot(
const Context<T>& context,
const Eigen::Ref<const VectorX<T>>& generalized_velocity,
VectorBase<T>* qdot) const {
unused(context);
// In the particular case where generalized velocity and generalized
// configuration are not even the same size, we detect this error and abort.
// This check will thus not identify cases where the generalized velocity
// and time derivative of generalized configuration are identically sized
// but not identical!
const int n = generalized_velocity.size();
// You need to override System<T>::DoMapVelocityToQDot!
DRAKE_THROW_UNLESS(qdot->size() == n);
qdot->SetFromVector(generalized_velocity);
}
template <typename T>
Eigen::VectorBlock<VectorX<T>> System<T>::GetMutableOutputVector(
SystemOutput<T>* output, int port_index) const {
DRAKE_ASSERT(0 <= port_index && port_index < num_output_ports());
DRAKE_DEMAND(output != nullptr);
ValidateCreatedForThisSystem(output);
BasicVector<T>* output_vector = output->GetMutableVectorData(port_index);
DRAKE_ASSERT(output_vector != nullptr);
DRAKE_ASSERT(output_vector->size() == get_output_port(port_index).size());
return output_vector->get_mutable_value();
}
template <typename T>
std::function<void(const AbstractValue&)>
System<T>::MakeFixInputPortTypeChecker(
InputPortIndex port_index) const {
const InputPortBase& port_base = this->GetInputPortBaseOrThrow(
__func__, port_index, /* warn_deprecated = */ false);
const InputPort<T>& port = static_cast<const InputPort<T>&>(port_base);
const std::string& port_name = port.get_name();
const std::string path_name = this->GetSystemPathname();
// Note that our lambdas below will capture all necessary items by-value,
// so that they do not rely on this System still being alive. (We do not
// allow a Context and System to have pointers to each other.)
switch (port.get_data_type()) {
case kAbstractValued: {
// For abstract inputs, we only need to ensure that both runtime values
// share the same base T in the Value<T>. Even if the System declared a
// model_value that was a subtype of T, there is no EvalInputValue
// sugar that allows the System to evaluate the input by downcasting to
// that subtype, so here we should not insist that some dynamic_cast
// would succeed. If the user writes the downcast on their own, it's
// fine to let them also handle detailed error reporting on their own.
const std::type_info& expected_type =
this->AllocateInputAbstract(port)->static_type_info();
return [&expected_type, port_index, path_name, port_name](
const AbstractValue& actual) {
if (actual.static_type_info() != expected_type) {
SystemBase::ThrowInputPortHasWrongType(
"FixInputPortTypeCheck", path_name, port_index, port_name,
NiceTypeName::Get(expected_type),
NiceTypeName::Get(actual.type_info()));
}
};
}
case kVectorValued: {
// For vector inputs, check that the size is the same.
// TODO(jwnimmer-tri) We should type-check the vector, eventually.
const std::unique_ptr<BasicVector<T>> model_vector =
this->AllocateInputVector(port);
const int expected_size = model_vector->size();
return [expected_size, port_index, path_name, port_name](
const AbstractValue& actual) {
const BasicVector<T>* const actual_vector =
actual.maybe_get_value<BasicVector<T>>();
if (actual_vector == nullptr) {
SystemBase::ThrowInputPortHasWrongType(
"FixInputPortTypeCheck", path_name, port_index, port_name,
NiceTypeName::Get<Value<BasicVector<T>>>(),
NiceTypeName::Get(actual));
}
// Check that vector sizes match.
if (actual_vector->size() != expected_size) {
SystemBase::ThrowInputPortHasWrongType(
"FixInputPortTypeCheck", path_name, port_index, port_name,
fmt::format("{} with size={}",
NiceTypeName::Get<BasicVector<T>>(),
expected_size),
fmt::format("{} with size={}",
NiceTypeName::Get(*actual_vector),
actual_vector->size()));
}
};
}
}
DRAKE_UNREACHABLE();
}
template <typename T>
const BasicVector<T>* System<T>::EvalBasicVectorInputImpl(
const char* func, const Context<T>& context,
InputPortIndex port_index) const {
// Make sure this is the right kind of port before worrying about whether
// it is connected up properly.
const InputPortBase& port = GetInputPortBaseOrThrow(
func, port_index, /* warn_deprecated = */ true);
if (port.get_data_type() != kVectorValued)
ThrowNotAVectorInputPort(func, port_index);
// If there is no value at all, the port is not connected which is not
// a problem here.
const AbstractValue* const abstract_value =
EvalAbstractInputImpl(func, context, port_index);
if (abstract_value == nullptr) {
return nullptr;
}
// We have a vector port with a value, it better be a BasicVector!
const auto* basic_vector = &abstract_value->get_value<BasicVector<T>>();
// Shouldn't have been possible to create this vector-valued port with
// the wrong size.
DRAKE_DEMAND(basic_vector->size() == port.size());
return basic_vector;
}
template <typename T>
void System<T>::AddExternalConstraints(
const std::vector<ExternalSystemConstraint>& constraints) {
for (const auto& item : constraints) {
AddExternalConstraint(item);
}
}
} // namespace systems
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::System)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/value_producer.h | #pragma once
#include <functional>
#include <memory>
#include <typeinfo>
#include <utility>
#include "drake/common/drake_copyable.h"
#include "drake/common/value.h"
#include "drake/systems/framework/abstract_value_cloner.h"
#include "drake/systems/framework/context_base.h"
namespace drake {
namespace systems {
/** %ValueProducer computes an AbstractValue output based on a ContextBase
input. This is commonly used for declaring output ports and cache entries.
It provides two functions for that purpose:
- Allocate() returns new storage that is suitably typed to hold the output.
- Calc() takes a context as input and writes to an output pointer.
For example, given this example calculator lambda:
<!-- The below is repeated in the unit test as DocumentationExample1; keep
it in sync between here and the unit test. -->
@code
std::function calc = [](const Context<T>& context, std::string* output) {
*output = std::to_string(context.get_time());
};
@endcode
We can capture it into a producer and then call it:
@code
ValueProducer producer(calc);
std::unique_ptr<AbstractValue> storage = producer.Allocate();
const LeafContext<T> context;
producer.Calc(context, storage.get());
EXPECT_THAT(storage->get_value<std::string>(), ::testing::StartsWith("0.0"));
@endcode
Sugar is provided to create %ValueProducer objects from function pointers that
operate on un-erased types, so that the user can ignore the details of type
erasure and Context<T> downcasting. Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details. */
class ValueProducer final {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(ValueProducer)
/** Signature of a function suitable for allocating an object that can hold
a value compatible with our Calc function. The result is always returned as
an AbstractValue but must contain the correct concrete type. */
using AllocateCallback = std::function<std::unique_ptr<AbstractValue>()>;
/** Signature of a function suitable for calculating a context-dependent
value, given a place to put the value. The function may presume that the
storage pointed to by the second argument will be of the proper type (as
returned by an AllocateCallback), but should not presume that the storage
has been initialized with any particular value; the function should always
fully overwrite the output storage with a new value. */
using CalcCallback = std::function<void(const ContextBase&, AbstractValue*)>;
/** Creates an invalid object; calls to Allocate or Calc will throw. */
ValueProducer();
/** @name Constructor overloads
@anchor ValueProducer_constructors
Create a ValueProducer by providing it a with calculation callback and
(if necessary) a way to allocate storage, in cases where the storage cannot
be default constructed.
<!-- The below is repeated in the unit test as DocumentationExample2; keep
it in sync between here and the unit test. -->
In many cases, your calculator function would be a class member function
like this:
@code
class MyClass {
void MyCalc(const Context<T>& context, std::string* output) const {
*output = std::to_string(context.get_time());
}
};
@endcode
and wrapping it would look like this:
@code
MyClass my_class;
ValueProducer foo = ValueProducer(&my_class, &MyClass::MyCalc);
@endcode
<!-- The below is repeated in the unit test as DocumentationExample3; keep
it in sync between here and the unit test. -->
If the type of the output value is cheap to copy, then the function may
return it by-value, instead of as an output argument:
@code
class MyClass {
double MyCalc(const Context<double>& context) const {
return context.get_time();
}
};
MyClass my_class;
ValueProducer foo = ValueProducer(&my_class, &MyClass::MyCalc);
@endcode
<!-- The below is repeated in the unit test as DocumentationExample4; keep
it in sync between here and the unit test. -->
If the type of the output is not default constructible, then you must provide
ValueProducer with an example value to use for pre-allocation:
@code
class MyClass {
void MyCalc(const Context<T>& context, BasicVector<T>* output) const {
output->get_mutable_value()[0] = context.get_time();
}
};
MyClass my_class;
BasicVector<T> model_value(1);
ValueProducer foo = ValueProducer(
&my_class, model_value, &MyClass::MyCalc);
@endcode
In the rare case that you cannot provide an example value when creating the
ValueProducer, you may instead provide an allocation callback. Refer to
more specific documentation below for an example.
For ease of use, the constructor offers overloads to specify the allocate and
calc functions.
The permitted argument types to specify Calc are:
- (1) `calc` is a member function pointer with an output argument.
- (2) `calc` is a member function pointer with a return value †.
- (3) `calc` is a std::function with an output argument.
- (4) `calc` is a std::function with a return value †.
- (5) `calc` is a generic CalcCallback.
† Do not use (2) nor (4) unless the return value is cheap to copy.
The permitted argument types to specify Allocate are:
- (a) `allocate` is via the default constructor.
- (b) `allocate` is via user-supplied model_value.
- (c) `allocate` is a member function pointer.
- (d) `allocate` is a generic AllocateCallback.
All combinations of (1..5) x (a..d) are permitted, except for (5a) because
the output type cannot be inferred from a generic CalcCallback.
All member function pointers must refer to member functions declared *const*.
For `calc` types (3) and (4), to pass bare non-member function pointer instead
of a lambda, you must explicitly convert the pointer to a `std::function`:
@code
void MyCalc(const Context<T>& context, std::string* output) { ... }
ValueProducer producer{std::function(&MyCalc)};
@endcode
The constructors take the following arguments, in order:
- The `instance` pointer (iff member function callback(s) are used).
- The `model_value` example or `allocate` callback (may be omitted).
- The `calc` callback (required).
If either `allocate` or `calc` is a member function pointer, then the class
`instance` to bind must be the first argument. This `instance` pointer is
aliased by the ValueProducer, so must outlive this object. (In practice,
this happens automatically because the SomeClass `instance` will typically
own all ValueProducer objects that call back into it.)
The `model_value` and `allocate` callback may be omitted when the OutputType
is default constructible; this is the most common case. The need for a custom
`allocate` function (i.e., options c or d, above) is extremely rare; prefer
to use the default constructor (option a) or model_value (option b) in almost
all cases.
@tparam SomeContext the subclass of ContextBase required by the calc callback
@tparam SomeOutput the output type of the calc callback
@tparam SomeClass the static type of the class to receive the callback(s)
@tparam SomeInstance the type of the instance to receive the callback(s);
must be castable into SomeClass
@throws std::exception if any argument is null. */
//@{
/** Overload (1a). This is the best choice. Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <class SomeInstance, typename SomeClass, typename SomeContext,
typename SomeOutput>
ValueProducer(
const SomeInstance* instance,
void (SomeClass::*calc)(const SomeContext&, SomeOutput*) const)
: ValueProducer(make_allocate_mode_a<SomeOutput>(),
make_calc_mode_1(instance, calc)) {}
/** Overload (1b). This is the second-best choice. Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <class SomeInstance, typename SomeClass, typename SomeContext,
typename SomeOutput>
ValueProducer(
const SomeInstance* instance,
const SomeOutput& model_value,
void (SomeClass::*calc)(const SomeContext&, SomeOutput*) const)
: ValueProducer(make_allocate_mode_b(model_value),
make_calc_mode_1(instance, calc)) {}
/** Overload (1c). Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <class SomeInstance, typename SomeClass, typename SomeContext,
typename SomeOutput>
ValueProducer(
const SomeInstance* instance,
std::unique_ptr<SomeOutput> (SomeClass::*allocate)() const,
void (SomeClass::*calc)(const SomeContext&, SomeOutput*) const)
: ValueProducer(make_allocate_mode_c(instance, allocate),
make_calc_mode_1(instance, calc)) {}
/* Overload (1d). Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <class SomeInstance, typename SomeClass, typename SomeContext,
typename SomeOutput>
ValueProducer(
const SomeInstance* instance,
AllocateCallback allocate,
void (SomeClass::*calc)(const SomeContext&, SomeOutput*) const)
: ValueProducer(std::move(allocate),
make_calc_mode_1(instance, calc)) {}
/** Overload (2a). Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <class SomeInstance, typename SomeClass, typename SomeContext,
typename SomeOutput>
ValueProducer(
const SomeInstance* instance,
SomeOutput (SomeClass::*calc)(const SomeContext&) const)
: ValueProducer(make_allocate_mode_a<SomeOutput>(),
make_calc_mode_2(instance, calc)) {}
/** Overload (2b). Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <class SomeInstance, typename SomeClass, typename SomeContext,
typename SomeOutput>
ValueProducer(
const SomeInstance* instance,
const SomeOutput& model_value,
SomeOutput (SomeClass::*calc)(const SomeContext&) const)
: ValueProducer(make_allocate_mode_b(model_value),
make_calc_mode_2(instance, calc)) {}
/** Overload (2c). Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <class SomeInstance, typename SomeClass, typename SomeContext,
typename SomeOutput>
ValueProducer(
const SomeInstance* instance,
std::unique_ptr<SomeOutput> (SomeClass::*allocate)() const,
SomeOutput (SomeClass::*calc)(const SomeContext&) const)
: ValueProducer(make_allocate_mode_c(instance, allocate),
make_calc_mode_2(instance, calc)) {}
/** Overload (2d). Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <class SomeInstance, typename SomeClass, typename SomeContext,
typename SomeOutput>
ValueProducer(
const SomeInstance* instance,
AllocateCallback allocate,
SomeOutput (SomeClass::*calc)(const SomeContext&) const)
: ValueProducer(std::move(allocate),
make_calc_mode_2(instance, calc)) {}
/** Overload (3a). Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <typename SomeContext, typename SomeOutput>
explicit ValueProducer(
std::function<void(const SomeContext&, SomeOutput*)> calc)
: ValueProducer(make_allocate_mode_a<SomeOutput>(),
make_calc_mode_3(std::move(calc))) {}
/** Overload (3b). Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <typename SomeContext, typename SomeOutput>
ValueProducer(
const SomeOutput& model_value,
std::function<void(const SomeContext&, SomeOutput*)> calc)
: ValueProducer(make_allocate_mode_b(model_value),
make_calc_mode_3(std::move(calc))) {}
/** Overload (3c). Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <class SomeInstance, typename SomeClass, typename SomeContext,
typename SomeOutput>
ValueProducer(
const SomeInstance* instance,
std::unique_ptr<SomeOutput> (SomeClass::*allocate)() const,
std::function<void(const SomeContext&, SomeOutput*)> calc)
: ValueProducer(make_allocate_mode_c(instance, allocate),
make_calc_mode_3(std::move(calc))) {}
/** Overload (3d). Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <typename SomeContext, typename SomeOutput>
ValueProducer(
AllocateCallback allocate,
std::function<void(const SomeContext&, SomeOutput*)> calc)
: ValueProducer(std::move(allocate),
make_calc_mode_3(std::move(calc))) {}
/** Overload (4a). Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <typename SomeContext, typename SomeOutput>
explicit ValueProducer(
std::function<SomeOutput(const SomeContext&)> calc)
: ValueProducer(make_allocate_mode_a<SomeOutput>(),
make_calc_mode_4(std::move(calc))) {}
/** Overload (4b). Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <typename SomeContext, typename SomeOutput>
ValueProducer(
const SomeOutput& model_value,
std::function<SomeOutput(const SomeContext&)> calc)
: ValueProducer(make_allocate_mode_b(model_value),
make_calc_mode_4(std::move(calc))) {}
/** Overload (4c). Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <class SomeInstance, typename SomeClass, typename SomeContext,
typename SomeOutput>
ValueProducer(
const SomeInstance* instance,
std::unique_ptr<SomeOutput> (SomeClass::*allocate)() const,
std::function<SomeOutput(const SomeContext&)> calc)
: ValueProducer(make_allocate_mode_c(instance, allocate),
make_calc_mode_4(std::move(calc))) {}
/** Overload (4d). Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <typename SomeContext, typename SomeOutput>
ValueProducer(
AllocateCallback allocate,
std::function<SomeOutput(const SomeContext&)> calc)
: ValueProducer(std::move(allocate),
make_calc_mode_4(std::move(calc))) {}
// Overload (5a) is omitted because we cannot infer the type of SomeOutput
// from a generic CalcCallback.
/** Overload (5b). Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <typename SomeOutput,
typename = std::enable_if_t<!std::is_convertible_v<
SomeOutput, AllocateCallback>>>
ValueProducer(
const SomeOutput& model_value,
CalcCallback calc)
: ValueProducer(make_allocate_mode_b(model_value),
std::move(calc)) {}
/** Overload (5c). Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@exclude_from_pydrake_mkdoc{Not bound} */
template <class SomeInstance, typename SomeClass, typename SomeOutput>
ValueProducer(
const SomeInstance* instance,
std::unique_ptr<SomeOutput> (SomeClass::*allocate)() const,
CalcCallback calc)
: ValueProducer(make_allocate_mode_c(instance, allocate),
std::move(calc)) {}
/** Overload (5d). Refer to the
@ref ValueProducer_constructors "Constructor overloads" for details.
@pydrake_mkdoc_identifier{overload_5d} */
ValueProducer(AllocateCallback allocate, CalcCallback calc);
//@}
~ValueProducer();
/** Returns true iff the allocate and calc callbacks are both non-null.
(The only way they can be null is if the ValueProducer was default constructed
or moved from.) */
bool is_valid() const;
/** This static function is provided for users who need an empty CalcCallback.
Passing `&ValueProducer::NoopCalc` as ValueProducer's last constructor
argument will create a function that does not compute anything, but can still
allocate. */
static void NoopCalc(const ContextBase&, AbstractValue*);
/** Invokes the allocate function provided to the constructor.
@throws std::exception if is_valid() is false. */
std::unique_ptr<AbstractValue> Allocate() const;
/** Invokes the calc function provided to the constructor.
@throws std::exception if is_valid() is false. */
void Calc(const ContextBase& context, AbstractValue* output) const;
private:
/** Reports that a callback pointer was null. */
[[noreturn]] static void ThrowBadNull();
/** Reports that a dynamic_cast failed. */
[[noreturn]] static void ThrowBadCast(
const std::type_info& actual_type,
const std::type_info& desired_type);
template <typename SomeClass, class SomeInstance>
static const SomeClass* instance_cast(const SomeInstance* instance) {
if (instance == nullptr) {
ThrowBadNull();
}
const auto* typed_instance = dynamic_cast<const SomeClass*>(instance);
if (typed_instance == nullptr) {
ThrowBadCast(typeid(*instance), typeid(SomeInstance));
}
return typed_instance;
}
template <class SomeContext>
static const SomeContext& context_cast(const ContextBase& context) {
const auto* typed_context = dynamic_cast<const SomeContext*>(&context);
if (typed_context == nullptr) {
ThrowBadCast(typeid(context), typeid(SomeContext));
}
return *typed_context;
}
// For overload series (1).
template <class SomeInstance, typename SomeClass, typename SomeContext,
typename SomeOutput>
static CalcCallback make_calc_mode_1(
const SomeInstance* instance,
void (SomeClass::*calc)(const SomeContext&, SomeOutput*) const) {
static_assert(std::is_base_of_v<ContextBase, SomeContext>,
"The inferred type of SomeContext was invalid;"
" typically it should be Context<T>.");
const SomeClass* typed_instance = instance_cast<SomeClass>(instance);
if (calc == nullptr) {
ThrowBadNull();
}
return [typed_instance, calc](const ContextBase& context,
AbstractValue* result) {
const SomeContext& typed_context = context_cast<SomeContext>(context);
SomeOutput& typed_result = result->get_mutable_value<SomeOutput>();
(typed_instance->*calc)(typed_context, &typed_result);
};
}
// For overload series (2).
template <class SomeInstance, typename SomeClass, typename SomeContext,
typename SomeOutput>
static CalcCallback make_calc_mode_2(
const SomeInstance* instance,
SomeOutput (SomeClass::*calc)(const SomeContext&) const) {
static_assert(std::is_base_of_v<ContextBase, SomeContext>,
"The inferred type of SomeContext was invalid;"
" typically it should be Context<T>.");
const SomeClass* typed_instance = instance_cast<SomeClass>(instance);
if (calc == nullptr) {
ThrowBadNull();
}
return [typed_instance, calc](const ContextBase& context,
AbstractValue* result) {
const SomeContext& typed_context = context_cast<SomeContext>(context);
SomeOutput& typed_result = result->get_mutable_value<SomeOutput>();
typed_result = (typed_instance->*calc)(typed_context);
};
}
// For overload series (3).
template <typename SomeContext, typename SomeOutput>
static CalcCallback make_calc_mode_3(
std::function<void(const SomeContext&, SomeOutput*)>&& calc) {
static_assert(std::is_base_of_v<ContextBase, SomeContext>,
"The inferred type of SomeContext was invalid;"
" typically it should be Context<T>.");
if (calc == nullptr) {
ThrowBadNull();
}
return [captured_calc = std::move(calc)](const ContextBase& context,
AbstractValue* result) {
const SomeContext& typed_context = context_cast<SomeContext>(context);
SomeOutput& typed_result = result->get_mutable_value<SomeOutput>();
captured_calc(typed_context, &typed_result);
};
}
// For overload series (4).
template <typename SomeContext, typename SomeOutput>
static CalcCallback make_calc_mode_4(
std::function<SomeOutput(const SomeContext&)>&& calc) {
static_assert(std::is_base_of_v<ContextBase, SomeContext>,
"The inferred type of SomeContext was invalid;"
" typically it should be Context<T>.");
if (calc == nullptr) {
ThrowBadNull();
}
return [captured_calc = std::move(calc)](const ContextBase& context,
AbstractValue* result) {
const SomeContext& typed_context = context_cast<SomeContext>(context);
SomeOutput& typed_result = result->get_mutable_value<SomeOutput>();
typed_result = captured_calc(typed_context);
};
}
// For overload series (a).
template <typename SomeOutput>
static AllocateCallback make_allocate_mode_a() {
static_assert(
std::is_default_constructible_v<SomeOutput>,
"When ValueProducer is used with an output type that is not default"
" constructible, then you must provide either a model_value or an"
" allocate callback function.");
return static_cast<std::unique_ptr<drake::AbstractValue>(*)()>(
&AbstractValue::Make<SomeOutput>);
}
// For overload series (b).
template <typename SomeOutput>
static AllocateCallback make_allocate_mode_b(const SomeOutput& model_value) {
return internal::AbstractValueCloner(model_value);
}
// For overload series (c).
template <class SomeInstance, typename SomeClass, typename SomeOutput>
static AllocateCallback make_allocate_mode_c(
const SomeInstance* instance,
std::unique_ptr<SomeOutput> (SomeClass::*allocate)() const) {
const SomeClass* typed_instance = instance_cast<SomeClass>(instance);
if (allocate == nullptr) {
ThrowBadNull();
}
return [typed_instance, allocate]() {
std::unique_ptr<SomeOutput> result = (typed_instance->*allocate)();
return std::make_unique<Value<SomeOutput>>(std::move(result));
};
}
AllocateCallback allocate_;
CalcCallback calc_;
};
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/diagram_output_port.cc | #include "drake/systems/framework/diagram_output_port.h"
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::DiagramOutputPort)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/witness_function.h | #pragma once
#include <limits>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_bool.h"
#include "drake/common/drake_copyable.h"
#include "drake/systems/framework/event_collection.h"
#include "drake/systems/framework/system_base.h"
namespace drake {
namespace systems {
template <class T>
class System;
enum class WitnessFunctionDirection {
/// This witness function will never be triggered.
kNone,
/// Witness function triggers when the function crosses or touches zero
/// after an initial positive evaluation.
kPositiveThenNonPositive,
/// Witness function triggers when the function crosses or touches zero
/// after an initial negative evaluation.
kNegativeThenNonNegative,
/// Witness function triggers *any time* the function crosses/touches zero,
/// *except* when the witness function evaluates to zero at the beginning
/// of the interval. Conceptually equivalent to kPositiveThenNonNegative OR
/// kNegativeThenNonNegative.
kCrossesZero,
};
/// Class that stores a function that is able to help determine the time and
/// state at which a step of the initial value problem integration of a System
/// should end, which may be done for any number of purposes, including
/// publishing or state reinitialization (i.e., event handling). System authors
/// declare witness functions through LeafSystem::MakeWitnessFunction().
///
/// For the ensuing discussion, consider two times (`t₀` and `t₁ > t₀`) and
/// states corresponding to those times (`x(t₀)` and `x(t₁)`). A
/// witness function, `w(t, x)`, "triggers" only when it crosses zero at a time
/// `t*` where `t₀ < t* ≤ t₁`. Note the half-open interval. For an example of a
/// witness function, consider the "signed distance" (i.e., Euclidean distance
/// when bodies are disjoint and minimum translational distance when bodies
/// intersect) between two rigid bodies; this witness function can be used to
/// determine both the time of impact for rigid bodies and their states at that
/// time of impact.
///
/// Precision in the definition of the witness function is necessary, because we
/// want the witness function to trigger only once if, for example,
/// `w(t₀, x(t₀)) ≠ 0`, `w(t₁, x(t₁)) = 0`, and `w(t₂, x(t₂)) ≠ 0`, for some
/// t₂ > t₁. In other words, if the witness function is evaluated over the
/// intervals [t₀, t₁] and [t₁, t₂], meaning that the zero occurs precisely at
/// an interval endpoint, the witness function should trigger once. Similarly,
/// the witness function should trigger exactly once if `w(t₀, x(t₀)) ≠ 0`,
/// `w(t*, x(t*)) = 0`, and `w(t₁, x(t₁)) = 0`, for `t* ∈ (t₀, t₁)`. We can
/// define the trigger condition formally over interval `[t₀, t₁]` using the
/// function:<pre>
/// T(w, t₀, x(t₀), t₁) = 1 if w(t₀, x(t₀)) ≠ 0 and
/// w(t₀, x(t₀))⋅w(t₁, x(t₁)) ≤ 0
/// 0 if w(t₀, x(t₀)) = 0 or
/// w(t₀, x(t₀))⋅w(t₁, x(t₁)) > 0
/// </pre>
/// We wish for the witness function to trigger if the trigger function
/// evaluates to one. The trigger function can be further modified, if
/// desired, to incorporate the constraint that the witness function should
/// trigger only when crossing from positive values to negative values, or vice
/// versa.
///
/// A good witness function should not cross zero repeatedly over a small
/// interval of time (relative to the maximum designated integration step size)
/// or over small changes in state; when a witness function has
/// been "bracketed" over an interval of time (i.e., it changes sign), that
/// witness function will ideally cross zero only once in that interval.
///
/// A witness function trigger time is isolated only to a small interval of
/// time (as described in Simulator). The disadvantage of this scheme is that it
/// always requires the length of the interval to be reduced to the requisite
/// length *and that each function evaluation (which requires numerical
/// integration) is extraordinarily expensive*. If, for example, the (slow)
/// bisection algorithm were used to isolate the time interval, the number of
/// integrations necessary to cut the interval from a length of ℓ to a length of
/// ε will be log₂(ℓ / ε). Bisection is just one of several possible algorithms
/// for isolating the time interval, though it's a reliable choice and always
/// converges linearly.
template <class T>
class WitnessFunction final {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(WitnessFunction)
/** Signature of a function suitable for calculating a value of a particular
witness function. */
using CalcCallback = std::function<T(const Context<T>&)>;
// The only permitted method to construct a witness function is through
// LeafSystem::MakeWitnessFunction(), so we hide the constructors from
// Doxygen.
#ifndef DRAKE_DOXYGEN_CXX
// Constructs the witness function using the given non-null System and its
// upcast SystemBase pointer, description (used primarily for debugging and
// logging), direction type, calculator function, and Event that is to be
// dispatched when this witness function triggers. Example events are
// publish, discrete variable update, unrestricted update, or nullptr to
// indicate no event type (i.e., no event will be called when this witness
// function triggers).
//
// @note Constructing a witness function with no corresponding event forces
// Simulator's integration of an ODE to end a step at the witness
// isolation time, as it would if there were an event, but then take no
// other action. For example, isolating a function's minimum or
// maximum values can be realized with a witness that triggers on a sign
// change of the function's time derivative, ensuring that the actual
// extreme value is present in the discretized trajectory.
// @warning the pointer to the System must be valid as long or longer than
// the lifetime of the witness function.
template <class MySystem>
WitnessFunction(const System<T>* system,
const SystemBase* system_base,
std::string description,
const WitnessFunctionDirection& direction,
T (MySystem::*calc)(const Context<T>&) const,
std::unique_ptr<Event<T>> event = nullptr)
: WitnessFunction(
system, system_base, std::move(description), direction,
[system, calc](const Context<T>& context) {
auto calc_system = static_cast<const MySystem*>(system);
return (calc_system->*calc)(context);
},
std::move(event)) {
DRAKE_DEMAND(dynamic_cast<const MySystem*>(system) != nullptr);
}
// See documentation for above constructor, which applies here without
// reservations.
WitnessFunction(const System<T>* system,
const SystemBase* system_base,
std::string description,
const WitnessFunctionDirection& direction,
std::function<T(const Context<T>&)> calc,
std::unique_ptr<Event<T>> event = nullptr)
: system_(system), system_base_(system_base),
description_(std::move(description)),
direction_type_(direction), event_(std::move(event)),
calc_function_(std::move(calc)) {
DRAKE_DEMAND(system != nullptr);
DRAKE_DEMAND(system_base != nullptr);
// Check the precondition on identical parameters; note that comparing as
// void* is only valid because we have single inheritance.
DRAKE_DEMAND(static_cast<const void*>(system) == system_base);
const bool has_calc = static_cast<bool>(calc_function_);
DRAKE_THROW_UNLESS(has_calc);
if (event_) {
event_->set_trigger_type(TriggerType::kWitness);
}
}
#endif
/// Gets the description of this witness function (used primarily for logging
/// and debugging).
const std::string& description() const { return description_; }
/// Gets the direction(s) under which this witness function triggers.
WitnessFunctionDirection direction_type() const { return direction_type_; }
/// Evaluates the witness function at the given context.
T CalcWitnessValue(const Context<T>& context) const {
system_base_->ValidateContext(context);
return calc_function_(context);
}
/// Gets a reference to the System used by this witness function.
const System<T>& get_system() const { return *system_; }
/// Checks whether the witness function should trigger using given
/// values at w0 and wf. Note that this function is not specific to a
/// particular witness function.
boolean<T> should_trigger(const T& w0, const T& wf) const {
WitnessFunctionDirection type = direction_type();
const T zero(0);
switch (type) {
case WitnessFunctionDirection::kNone:
return (T(0) > T(0));
case WitnessFunctionDirection::kPositiveThenNonPositive:
return (w0 > zero && wf <= zero);
case WitnessFunctionDirection::kNegativeThenNonNegative:
return (w0 < zero && wf >= zero);
case WitnessFunctionDirection::kCrossesZero:
return ((w0 > zero && wf <= zero) ||
(w0 < zero && wf >= zero));
}
DRAKE_UNREACHABLE();
}
/// Gets the event that will be dispatched when the witness function
/// triggers. A null pointer indicates that no event will be dispatched.
const Event<T>* get_event() const { return event_.get(); }
/// Gets a mutable pointer to the event that will occur when the witness
/// function triggers.
Event<T>* get_mutable_event() { return event_.get(); }
private:
// A pointer to the system and its base class.
const System<T>* const system_;
const SystemBase* const system_base_;
// The description of this witness function (used primarily for debugging and
// logging).
const std::string description_;
// Direction(s) under which this witness function triggers.
const WitnessFunctionDirection direction_type_;
// Unique pointer to the event.
const std::unique_ptr<Event<T>> event_;
// The witness function calculator function pointer.
const CalcCallback calc_function_;
};
} // namespace systems
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::WitnessFunction)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/value_checker.h | #pragma once
#include <memory>
#include <stdexcept>
#include <string>
#include "drake/common/drake_throw.h"
#include "drake/common/nice_type_name.h"
#include "drake/common/value.h"
#include "drake/systems/framework/basic_vector.h"
namespace drake {
namespace systems {
namespace internal {
/// Checks some BasicVector invariants on @p basic_vector.
///
/// Because this function uses shady implementation tricks, it should ONLY be
/// called from within DRAKE_ASSERT_VOID or unit test code.
///
/// This function is likely to be expensive (on the order of a full copy), so
/// should be used sparingly. In particular, only a few select locations
/// within the Systems Framework itself should likely call this function.
///
/// @throws std::exception if invariants are violated or basic_vector is nullptr
template <typename T>
void CheckBasicVectorInvariants(const BasicVector<T>* basic_vector) {
DRAKE_THROW_UNLESS(basic_vector != nullptr);
std::unique_ptr<BasicVector<T>> cloned_base = basic_vector->Clone();
const BasicVector<T>* const cloned_vector = cloned_base.get();
DRAKE_THROW_UNLESS(cloned_vector != nullptr);
const auto& original_type = typeid(*basic_vector);
const auto& cloned_type = typeid(*cloned_vector);
if (original_type != cloned_type) {
const std::string original_name = NiceTypeName::Get(*basic_vector);
const std::string cloned_name = NiceTypeName::Get(*cloned_vector);
throw std::runtime_error(
"CheckBasicVectorInvariants failed: " + original_name + "::Clone "
"produced a " + cloned_name + " object instead of the same type");
}
}
/// If @p abstract_value is a Value<BasicVector<T>>, then checks some
/// BasicVector invariants. Otherwise, does nothing.
///
/// Because this function uses shady implementation tricks, it should ONLY be
/// called from within DRAKE_ASSERT_VOID or unit test code.
///
/// This function is likely to be expensive (on the order of a full copy), so
/// should be used sparingly. In particular, only a few select locations
/// within the Systems Framework itself should likely call this function.
///
/// @tparam T the supposed element type of the Value<BasicVector<T>> that has
/// been erased into an AbstractValue
///
/// @throws std::exception if invariants are violated or abstract_value is
/// nullptr
template <typename T>
void CheckVectorValueInvariants(const AbstractValue* abstract_value) {
DRAKE_THROW_UNLESS(abstract_value != nullptr);
const auto* const basic_vector =
abstract_value->maybe_get_value<BasicVector<T>>();
if (basic_vector != nullptr) {
// We are a Value<BasicVector<T>>, so check the invariants.
CheckBasicVectorInvariants<T>(basic_vector);
}
}
} // namespace internal
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/cache.h | #pragma once
/** @file
Declares CacheEntryValue and Cache, which is the container for cache entry
values. */
#include <cstdint>
#include <memory>
#include <set>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include "drake/common/copyable_unique_ptr.h"
#include "drake/common/drake_assert.h"
#include "drake/common/reset_on_copy.h"
#include "drake/common/value.h"
#include "drake/systems/framework/framework_common.h"
namespace drake {
namespace systems {
class DependencyGraph;
//==============================================================================
// CACHE ENTRY VALUE
//==============================================================================
/** (Advanced) This is the representation in the Context for the value of one of
a System's CacheEntry objects. Most users will not use this class directly --
System and CacheEntry provide the most common APIs, and Context provides
additional useful methods.
@see System, CacheEntry, Context for user-facing APIs.
A %CacheEntryValue consists of a single type-erased value, a serial number,
an `out_of_date` flag, and a DependencyTracker ticket. Details:
- "Out of date" means that some prerequisite of this cache entry's computation
has been changed in the current Context since the stored value was last
computed, and thus must be recomputed prior to use. On the other hand, if the
entry is _not_ out of date, then it is "up to date" meaning that if you were
to recompute it using the current Context values you would get the identical
result (so don't bother!).
- The "serial number" is an integer that is incremented whenever the value is
modified, or made available for mutable access. You can use it to recognize
that you are looking at the same value as you saw at some earlier time. It is
also useful for performance studies since it is a count of how many times this
value was recomputed. Note that marking the value "out of date" is _not_ a
modification; that does not change the serial number. The serial number is
maintained internally and cannot be user-modified.
- The DependencyTicket ("ticket") stored here identifies the DependencyTracker
("tracker") associated with this cache entry. The tracker maintains lists of
all upstream prerequisites and downstream dependents of the value stored here,
and also has a pointer to this %CacheEntryValue that it uses for invalidation.
Upstream modifications cause the tracker to set the `out_of_date` flag here,
and mark all downstream dependents out of date also. The tracker lives in
the same subcontext that owns the Cache that owns this %CacheEntryValue.
We sometimes use the terms "invalid" and "invalidate" as synonyms for "out of
date" and "mark out of date".
For debugging purposes, caching may be disabled for an entire Context or for
particular cache entry values. This is independent of the `out_of_date` flag
described above, which is still expected to be operational when caching is
disabled. However, when caching is disabled the Eval() methods will recompute
the contained value even if it is not marked out of date. That should have no
effect other than to slow computation; if results change, something is wrong.
There could be a problem with the specification of dependencies, a bug in user
code such as improper retention of a stale reference, or a bug in the caching
system. */
class CacheEntryValue {
public:
/** @name Does not allow move or assignment; copy constructor is private. */
/** @{ */
CacheEntryValue(CacheEntryValue&&) = delete;
void operator=(const CacheEntryValue&) = delete;
void operator=(CacheEntryValue&&) = delete;
/** @} */
/** Destructs the cache value, but does not issue any notifications to
downstream dependents. */
~CacheEntryValue() = default;
/** Defines the concrete value type by providing an initial AbstractValue
object containing an object of the appropriate concrete type. This value
is marked out of date. It is an error to call this if there is already
a value here; use has_value() if you want to check first. Also, the given
initial value may not be null. The serial number is set to 1. No out-of-date
notifications are sent to downstream dependents. Operation of this
initialization method is not affected by whether the cache is currently
frozen. However, the corresponding value won't be accessible while the cache
remains frozen (since it is out of date).
@throws std::exception if the given value is null or if there is already a
value, or if this %CacheEntryValue is malformed in
some detectable way. */
void SetInitialValue(std::unique_ptr<AbstractValue> init_value) {
if (init_value == nullptr) {
throw std::logic_error(FormatName(__func__) +
"initial value may not be null.");
}
ThrowIfValuePresent(__func__);
value_ = std::move(init_value);
serial_number_ = 1;
mark_out_of_date();
ThrowIfBadCacheEntryValue(); // Sanity check.
}
/** @name Safe methods for value access and modification
These are the recommended methods for accessing and modifying the cache entry
value. They unconditionally check all the relevant preconditions to catch
usage errors. In particular, access is prevented when the value is out of
date, and modification is permitted only when (a) the value is _already_ out
of date (typically because a prerequisite changed), or (b) caching is
disabled for this entry. For performance-sensitive code, you may need to use
the parallel set of methods below that check preconditions only in Debug
builds, but be sure you are gaining significant performance before giving up
on Release-build validation. */
//@{
/** Returns a const reference to the contained abstract value, which must
not be out of date with respect to any of its prerequisites. It is
an error to call this if there is no stored value object, or if the value is
out of date.
@throws std::exception if there is no value or it is out of date.
@see get_abstract_value() */
const AbstractValue& GetAbstractValueOrThrow() const {
return GetAbstractValueOrThrowHelper(__func__);
}
/** Returns a const reference to the contained value of known type V. It is
an error to call this if there is no stored value, or the value is out of
date, or the value doesn't actually have type V.
@throws std::exception if there is no stored value, or if it is out of
date, or it doesn't actually have type V.
@see get_value() */
template <typename V>
const V& GetValueOrThrow() const {
return GetValueOrThrowHelper<V>(__func__);
}
/** Assigns a new value to a cache entry and marks it up to date.
The cache entry must already contain a value object of type V to which the
new value is assigned, and that value must currently be marked out of date.
The supplied new value _must_ have been calculated using the current values
in the owning Context, and we assume that here although this method cannot
check that assumption. Consequently, this method clears the `out_of_date`
flag. No out-of-date notifications are issued by this method; we assume
downstream dependents were marked out of date at the time this value went out
of date. The serial number is incremented.
This method is the safest and most convenient way to assign a new value.
However it requires that a new value be computed and then copied into the
cache entry, which is fine for small types V but may be too expensive for
large ones. You can alternatively obtain a mutable reference to the value
already contained in the cache entry and update it in place via
GetMutableValueOrThrow().
@throws std::exception if there is no value, or the value is already up
to date, of it doesn't actually have type V.
@throws std::exception if the cache is frozen.
@see set_value(), GetMutableValueOrThrow() */
template <typename V>
void SetValueOrThrow(const V& new_value) {
SetValueOrThrowHelper<V>(__func__, new_value);
++serial_number_;
mark_up_to_date();
}
/** (Advanced) Returns a mutable reference to the contained value after
incrementing the serial number. This is for the purpose of performing an
update or extended computation in place. If possible, use the safer and more
straightforward method SetValueOrThrow() rather than this method. Mutable
access is only permitted if the value is already marked out of date (meaning
that all downstream dependents have already been notified). It is an error to
call this if there is no stored value, or it is already up to date. Since this
is intended for relatively expensive computations, these preconditions are
checked even in Release builds. If you have a small, fast computation to
perform, use set_value() instead. If your computation completes successfully,
you must mark the entry up to date yourself using mark_up_to_date() if you
want anyone to be able to use the new value.
@throws std::exception if there is no value, or if the value is already
up to date.
@throws std::exception if the cache is frozen.
@see SetValueOrThrow(), set_value(), mark_up_to_date() */
AbstractValue& GetMutableAbstractValueOrThrow() {
return GetMutableAbstractValueOrThrowHelper(__func__);
}
/** (Advanced) Convenience method that returns a mutable reference to the
contained value downcast to its known concrete type. Throws an exception if
the contained value does not have the indicated concrete type. Note that you
must call mark_up_to_date() after modifying the value through the returned
reference. See GetMutableAbstractValueOrThrow() above for more information.
@throws std::exception if there is no value, or if the value is already
up to date, of it doesn't actually have type V.
@throws std::exception if the cache is frozen.
@see SetValueOrThrow(), set_value(), mark_up_to_date()
@tparam V The known actual value type. */
template <typename V>
V& GetMutableValueOrThrow() {
AbstractValue& value = GetMutableAbstractValueOrThrowHelper(__func__);
return value.get_mutable_value<V>();
}
/** (Advanced) Returns a reference to the contained value _without_ checking
whether the value is out of date. This can be used to check type and size
information but should not be used to look at the value unless you _really_
know what you're doing.
@throws std::exception if there is no contained value. */
const AbstractValue& PeekAbstractValueOrThrow() const {
ThrowIfNoValuePresent(__func__);
return *value_;
}
/** (Advanced) Convenience method that provides access to the contained value
downcast to its known concrete type, _without_ checking whether the value is
out of date. This can be used to check type and size information but should
not be used to look at the value unless you _really_ know what you're doing.
@throws std::exception if there is no contained value, or if the contained
value does not actually have type V.
@tparam V The known actual value type. */
template <typename V>
const V& PeekValueOrThrow() const {
ThrowIfNoValuePresent(__func__);
return value_->get_value<V>();
}
//@}
/** @name Fast-but-dangerous methods for highest performance
These methods check for errors only in Debug builds, but plunge
blindly onward in Release builds so that they will execute as fast as
possible. You should use them only in places where performance requirements
preclude Release-build checks. The best way to determine that is to time the
code using the always-checked methods vs. these ones. If that's not practical,
use these only when the containing code is in a very high-rate loop, and
is a substantial fraction of the total code being executed there. */
//@{
/** Returns a const reference to the contained abstract value, which must
not be out of date with respect to any of its prerequisites. It is an error
to call this if there is no stored value, or it is out of date. Because this
is used in performance-critical contexts, these requirements will be
checked only in Debug builds. If you are not in a performance-critical
situation (and you probably are not!), use GetAbstractValueOrThrow()
instead. */
const AbstractValue& get_abstract_value() const {
#ifdef DRAKE_ASSERT_IS_ARMED
return GetAbstractValueOrThrowHelper(__func__);
#else
return *value_;
#endif
}
/** Returns a const reference to the contained value of known type V. It is
an error to call this if there is no stored value, or the value is out of
date, or the value doesn't actually have type V. Because this is expected to
be used in performance-critical, inner-loop circumstances, these requirements
will be checked only in Debug builds. If you are not in a performance-critical
situation (and you probably are not!), use `GetValueOrThrow<V>`() instead.
@tparam V The known actual value type. */
template <typename V>
const V& get_value() const {
#ifdef DRAKE_ASSERT_IS_ARMED
return GetValueOrThrowHelper<V>(__func__);
#else
return value_->get_value<V>();
#endif
}
/** Assigns a new value to a cache entry and marks it up to date.
The cache value must already have a value object of type V to which the
new value is assigned, and that value must not already be up to date.
The new value is assumed to be up to date with its prerequisites, so the
`out_of_date` flag is cleared. No out-of-date notifications are issued by this
method; we assume downstream dependents were marked out of date at the time
this value went out of date. The serial number is incremented. If you are not
in a performance-critical situation (and you probably are not!), use
`SetValueOrThrow<V>()` instead.
@throws std::exception if the cache is frozen.
@tparam V The known actual value type. */
template <typename V>
void set_value(const V& new_value) {
#ifdef DRAKE_ASSERT_IS_ARMED
SetValueOrThrowHelper<V>(__func__, new_value);
#else
ThrowIfFrozen(__func__);
value_->set_value<V>(new_value);
#endif
++serial_number_;
mark_up_to_date();
}
/** (Advanced) Swaps ownership of the stored value object with the given
one. The value is marked out of date and the serial number is incremented.
This is useful for discrete updates of abstract state variables that contain
large objects. Both values must be non-null and of the same concrete type but
we won't check for errors except in Debug builds.
@throws std::exception if the cache is frozen.
*/
void swap_value(std::unique_ptr<AbstractValue>* other_value) {
DRAKE_ASSERT_VOID(ThrowIfNoValuePresent(__func__));
DRAKE_ASSERT_VOID(ThrowIfBadOtherValue(__func__, other_value));
ThrowIfFrozen(__func__);
value_.swap(*other_value);
++serial_number_;
mark_out_of_date();
}
//@}
/** @name Dependency management
Methods here deal with management of the `out_of_date` flag and determining
whether the contained value must be recomputed before use. */
//@{
/** Returns `true` if the current value is out of date with respect to any of
its prerequisites. This refers only to the `out_of_date` flag and is
independent of whether caching is enabled or disabled. Don't call this if
there is no value here; use has_value() if you aren't sure.
@see needs_recomputation() */
bool is_out_of_date() const {
DRAKE_ASSERT_VOID(ThrowIfNoValuePresent(__func__));
return (flags_ & kValueIsOutOfDate) != 0;
}
/** Returns `true` if either (a) the value is out of date, or (b) caching
is disabled for this entry. This is a _very_ fast inline method intended
to be called every time a cache value is obtained with Eval(). This is
equivalent to `is_out_of_date() || is_entry_disabled()` but faster. Don't
call this if there is no value here; use has_value() if you aren't sure.
Note that if this returns true while the cache is frozen, any attempt to
access the value will fail since recomputation is forbidden in that case.
However, operation of _this_ method is unaffected by whether the cache
is frozen. */
bool needs_recomputation() const {
DRAKE_ASSERT_VOID(ThrowIfNoValuePresent(__func__));
return flags_ != kReadyToUse;
}
/** (Advanced) Marks the cache entry value as up to date with respect to
its prerequisites, with no other effects. That is, this method clears the
`out_of_date` flag. In particular, this method does not
modify the value, does not change the serial number, and does not notify
downstream dependents of anything. This is a very dangerous method since it
enables access to the value but can't independently determine whether it is
really up to date. You should not call it unless you really know what you're
doing, or have a death wish. Do not call this method if there is no stored
value object; use has_value() if you aren't sure. This is intended
to be very fast so doesn't check for a value object except in Debug builds.
@note Operation of this method is unaffected by whether the cache is
frozen. It may be useful for testing and debugging in that case but you
should be _very_ careful if you use it -- once you call this the value
will be accessible in the frozen cache, regardless of whether it is any
good! */
void mark_up_to_date() {
DRAKE_ASSERT_VOID(ThrowIfNoValuePresent(__func__));
flags_ &= ~kValueIsOutOfDate;
}
/** (Advanced) Marks the cache entry value as _out-of-date_ with respect to
its prerequisites, with no other effects. In particular, it does not modify
the value, does not change the serial number, and does not notify downstream
dependents. You should not call this method unless you know that dependent
notification has already been taken care of. There are no error conditions;
even an empty cache entry can be marked out of date.
@note Operation of this method is unaffected by whether the cache is frozen.
If you call it in that case the corresponding value will become
inaccessible since it would require recomputation. */
void mark_out_of_date() {
flags_ |= kValueIsOutOfDate;
}
/** Returns the serial number of the contained value. This counts up every
time the contained value changes, or whenever mutable access is granted. */
int64_t serial_number() const { return serial_number_; }
//@}
/** @name Bookkeeping methods
Miscellaneous methods of limited use to most users. */
//@{
/** Returns the human-readable description for this %CacheEntryValue. */
const std::string& description() const { return description_; }
/** Returns the description, preceded by the full pathname of the subsystem
associated with the owning subcontext. */
std::string GetPathDescription() const;
/** Returns `true` if this %CacheEntryValue currently contains a value object
at all, regardless of whether it is up to date. There will be no value object
after default construction, prior to SetInitialValue(). */
bool has_value() const { return value_ != nullptr; }
/** Returns the CacheIndex used to locate this %CacheEntryValue within its
containing subcontext. */
CacheIndex cache_index() const { return cache_index_; }
/** Returns the DependencyTicket used to locate the DependencyTracker that
manages dependencies for this %CacheEntryValue. The ticket refers to a
tracker that is owned by the same subcontext that owns this
%CacheEntryValue. */
DependencyTicket ticket() const { return ticket_; }
//@}
/** @name Testing/debugging utilities
These are used for disabling and re-enabling caching to determine correctness
and effectiveness of caching. Usually all cache entries are disabled or
enabled together using higher-level methods that invoke these ones, but you
can disable just a single entry if necessary. */
//@{
/** Throws an std::exception if there is something clearly wrong with this
%CacheEntryValue object. If the owning subcontext is known, provide a pointer
to it here and we'll check that this cache entry agrees. In addition we check
for other internal inconsistencies.
@throws std::exception for anything that goes wrong, with an appropriate
explanatory message. */
// These invariants hold for all CacheEntryValues except the dummy one.
void ThrowIfBadCacheEntryValue(const internal::ContextMessageInterface*
owning_subcontext = nullptr) const;
/** (Advanced) Disables caching for just this cache entry value. When
disabled, the corresponding entry's Eval() method will unconditionally invoke
Calc() to recompute the value, regardless of the setting of the `out_of_date`
flag. The `disabled` flag is independent of the `out_of_date` flag, which
will continue to be managed even if caching is disabled. It is also
independent of whether the cache is frozen, although in that case any
cache access will fail since recomputation is not permitted in a frozen
cache. Once unfrozen, caching will remain disabled unless enable_caching()
is called. */
void disable_caching() {
flags_ |= kCacheEntryIsDisabled;
}
/** (Advanced) Enables caching for this cache entry value if it was previously
disabled. When enabled (the default condition) the corresponding entry's
Eval() method will check the `out_of_date` flag and invoke Calc() only if the
entry is marked out of date. It is also independent of whether the cache is
frozen; in that case caching will be enabled once the cache is unfrozen. */
void enable_caching() {
flags_ &= ~kCacheEntryIsDisabled;
}
/** (Advanced) Returns `true` if caching is disabled for this cache entry.
This is independent of the `out_of_date` flag, and independent of whether
the cache is currently frozen. */
bool is_cache_entry_disabled() const {
return (flags_ & kCacheEntryIsDisabled) != 0;
}
//@}
private:
// So Cache and no one else can construct and copy CacheEntryValues.
friend class Cache;
// Allow this adapter access to our private constructors on our behalf.
// TODO(sherm1) This friend declaration allows us to hide constructors we
// don't want users to call. But there is still a loophole in that a user
// could create objects of this type and get access indirectly. Consider
// whether that is a real problem that needs to be solved and if so fix it.
friend class copyable_unique_ptr<CacheEntryValue>;
// Default constructor can only be used privately to construct an empty
// CacheEntryValue with description "DUMMY" and a meaningless value.
CacheEntryValue()
: description_("DUMMY"), value_(AbstractValue::Make<int>()) {}
// Creates a new cache value with the given human-readable description and
// (optionally) an abstract value that defines the right concrete type for
// this value. The given cache index and dependency ticket must be valid and
// are recorded here. Unless you have a good reason to do otherwise, make the
// description identical to the CacheEntry for which this is the value.
CacheEntryValue(CacheIndex index, DependencyTicket ticket,
std::string description,
const internal::ContextMessageInterface* owning_subcontext,
std::unique_ptr<AbstractValue> initial_value)
: cache_index_(index),
ticket_(ticket),
description_(std::move(description)),
owning_subcontext_(owning_subcontext),
value_(std::move(initial_value)) {
DRAKE_DEMAND(index.is_valid() && ticket.is_valid());
DRAKE_DEMAND(owning_subcontext != nullptr);
// OK if initial_value is null here.
}
// Copy constructor is private because it requires post-copy cleanup via
// set_owning_subcontext().
CacheEntryValue(const CacheEntryValue&) = default;
// This is the post-copy cleanup method.
void set_owning_subcontext(
const internal::ContextMessageInterface* owning_subcontext) {
DRAKE_DEMAND(owning_subcontext != nullptr);
DRAKE_DEMAND(owning_subcontext_ == nullptr);
owning_subcontext_ = owning_subcontext;
}
// Fully-checked method with API name to use in error messages.
const AbstractValue& GetAbstractValueOrThrowHelper(const char* api) const {
ThrowIfNoValuePresent(api);
ThrowIfOutOfDate(api); // Must *not* be out of date!
return *value_;
}
// Note that serial number is incremented here since caller will be stomping
// on this value.
AbstractValue& GetMutableAbstractValueOrThrowHelper(const char* api) {
ThrowIfNoValuePresent(api);
ThrowIfAlreadyComputed(api); // *Must* be out of date!
ThrowIfFrozen(api);
++serial_number_;
return *value_;
}
// Adds a check on the concrete value type also.
template <typename T>
const T& GetValueOrThrowHelper(const char* api) const {
return GetAbstractValueOrThrowHelper(api).get_value<T>();
}
// Fully-checked method with API name to use in error messages.
template <typename T>
void SetValueOrThrowHelper(const char* api, const T& new_value) const {
ThrowIfNoValuePresent(api);
ThrowIfAlreadyComputed(api); // *Must* be out of date!
ThrowIfFrozen(api);
return value_->set_value<T>(new_value);
}
void ThrowIfNoValuePresent(const char* api) const {
if (!has_value())
throw std::logic_error(FormatName(api) + "no value is present.");
}
void ThrowIfValuePresent(const char* api) const {
if (has_value()) {
throw std::logic_error(FormatName(api) +
"there is already a value object in this CacheEntryValue.");
}
}
// Throws if "other" doesn't have the same concrete type as this value.
// Don't call this unless you've already verified that there is a value.
void ThrowIfBadOtherValue(
const char* api,
const std::unique_ptr<AbstractValue>* other_value_ptr) const;
// This means literally that the out-of-date bit is set; it does not look
// at whether caching is disabled.
void ThrowIfOutOfDate(const char* api) const {
if (is_out_of_date()) {
throw std::logic_error(FormatName(api) +
"the current value is out of date.");
}
}
// This checks that there is *some* reason to recompute -- either out-of-date
// or caching is disabled.
void ThrowIfAlreadyComputed(const char* api) const {
if (!needs_recomputation()) {
throw std::logic_error(FormatName(api) +
"the current value is already up to date.");
}
}
// Invoke from any attempt to set or get mutable access to an out-of-date
// cache entry value.
void ThrowIfFrozen(const char* api) const {
if (owning_subcontext_->is_cache_frozen()) {
throw std::logic_error(FormatName(api) +
"the cache is frozen but this entry is out of date.");
}
}
// Provides an identifying prefix for error messages.
std::string FormatName(const char* api) const {
return "CacheEntryValue(" + GetPathDescription() + ")::" + api + "(): ";
}
// The sense of these flag bits is chosen so that Eval() can check in a single
// instruction whether it must recalculate. Only if flags==0 (kReadyToUse) can
// we reuse the existing value. See needs_recomputation() above.
enum Flags : int {
kReadyToUse = 0b00,
kValueIsOutOfDate = 0b01,
kCacheEntryIsDisabled = 0b10
};
// The index for this CacheEntryValue within its containing subcontext.
CacheIndex cache_index_;
// The ticket for this cache entry's managing DependencyTracker in the
// containing subcontext.
DependencyTicket ticket_;
// A human-readable description of this cache entry. Not interpreted by code
// but useful for error messages.
std::string description_;
// Pointer to the system name service of the owning subcontext. Used for
// error messages.
reset_on_copy<const internal::ContextMessageInterface*>
owning_subcontext_;
// The value, its serial number, and its validity. The value is copyable so
// that we can use a default copy constructor. The serial number is
// 0 on construction but is always >= 1 once we get an initial value.
copyable_unique_ptr<AbstractValue> value_;
int64_t serial_number_{0};
int flags_{kValueIsOutOfDate};
};
//==============================================================================
// CACHE
//==============================================================================
/** (Advanced) Stores all the CacheEntryValue objects owned by a particular
Context, organized to allow fast access using a CacheIndex as an index. Most
users will not use this class directly -- System and CacheEntry provide the
most common APIs, and Context provides additional useful methods.
@see System, CacheEntry, Context for user-facing APIs.
Memory addresses of CacheEntryValue objects are stable once allocated, but
CacheIndex numbers are stable even after a Context has been copied so should be
preferred as a means for identifying particular cache entries. */
class Cache {
public:
/** @name Does not allow move or assignment; copy constructor is private. */
//@{
Cache(Cache&&) = delete;
void operator=(const Cache&) = delete;
void operator=(Cache&&) = delete;
//@}
/** Constructor creates an empty cache referencing the system pathname
service of its owning subcontext. The supplied pointer must not be null. */
explicit Cache(const internal::ContextMessageInterface* owning_subcontext)
: owning_subcontext_(owning_subcontext) {
DRAKE_DEMAND(owning_subcontext != nullptr);
}
/** Destruction deletes all cache entries and their contained values; no
dependency notifications are issued. */
~Cache() = default;
/** Allocates a new CacheEntryValue and provides it a DependencyTracker using
the given CacheIndex and DependencyTicket number. The CacheEntryValue object
is owned by this Cache and the returned reference remains valid if other cache
entry values are created. If there is a pre-existing tracker with the given
ticket number (allowed only for well-known cached computations, such as time
derivatives), it is assigned the new cache entry value to manage. Otherwise a
new DependencyTracker is created. The created tracker object is owned by the
given DependencyGraph, which must be owned by the same Context that owns this
Cache. The graph must already contain trackers for the indicated
prerequisites. The tracker will retain a pointer to the created
CacheEntryValue for invalidation purposes. */
CacheEntryValue& CreateNewCacheEntryValue(
CacheIndex index, DependencyTicket ticket,
const std::string& description,
const std::set<DependencyTicket>& prerequisites,
DependencyGraph* graph);
/** Returns true if there is a CacheEntryValue in this cache that has the
given index. */
bool has_cache_entry_value(CacheIndex index) const {
DRAKE_DEMAND(index.is_valid());
if (index >= cache_size()) return false;
return store_[index] != nullptr;
}
/** Returns the current size of the Cache container, providing for CacheIndex
values from `0..cache_size()-1`. Note that it is possible to have empty slots
in the cache. Use has_cache_entry_value() to determine if there is a cache
entry associated with a particular index. */
int cache_size() const { return static_cast<int>(store_.size()); }
/** Returns a const CacheEntryValue given an index. This is very fast.
Behavior is undefined if the index is out of range [0..cache_size()-1] or
if there is no CacheEntryValue with that index. Use has_cache_entry_value()
first if you aren't sure. */
const CacheEntryValue& get_cache_entry_value(CacheIndex index) const {
DRAKE_ASSERT(has_cache_entry_value(index));
const CacheEntryValue& cache_value = *store_[index];
DRAKE_ASSERT(cache_value.cache_index() == index);
return cache_value;
}
/** Returns a mutable CacheEntryValue given an index. This is very fast.
Behavior is undefined if the index is out of range [0..cache_size()-1] or
if there is no CacheEntryValue with that index. Use has_cache_entry_value()
first if you aren't sure. */
CacheEntryValue& get_mutable_cache_entry_value(CacheIndex index) {
return const_cast<CacheEntryValue&>(get_cache_entry_value(index));
}
/** (Advanced) Disables caching for all the entries in this %Cache. Note that
this is done by setting individual `is_disabled` flags in the entries, so it
can be changed on a per-entry basis later. This has no effect on the
`out_of_date` flags. */
void DisableCaching();
/** (Advanced) Re-enables caching for all entries in this %Cache if any were
previously disabled. Note that this is done by clearing individual
`is_disabled` flags in the entries, so it overrides any disabling that may
have been done to individual entries. This has no effect on the `out_of_date`
flags so subsequent Eval() calls might not initiate recomputation. Use
SetAllEntriesOutOfDate() if you want to force recomputation. */
void EnableCaching();
/** (Advanced) Mark every entry in this cache as "out of date". This forces
the next Eval() request for an entry to perform a recalculation. After that
normal caching behavior resumes. */
void SetAllEntriesOutOfDate();
/** (Advanced) Sets the "is frozen" flag. Cache entry values should check this
before permitting mutable access to values.
@see ContextBase::FreezeCache() for the user-facing API */
void freeze_cache() {
is_cache_frozen_ = true;
}
/** (Advanced) Clears the "is frozen" flag, permitting normal cache
activity.
@see ContextBase::UnfreezeCache() for the user-facing API */
void unfreeze_cache() {
is_cache_frozen_ = false;
}
/** (Advanced) Reports the current value of the "is frozen" flag.
@see ContextBase::is_cache_frozen() for the user-facing API */
bool is_cache_frozen() const { return is_cache_frozen_; }
/** (Internal use only) Returns a mutable reference to a dummy CacheEntryValue
that can serve as a /dev/null-like destination for throw-away writes. */
CacheEntryValue& dummy_cache_entry_value() { return dummy_; }
private:
// So ContextBase and no one else can copy a Cache.
friend class ContextBase;
// Copy constructor duplicates the source %Cache object, with identical
// contents but with the "owning subcontext" back pointers set to null. Those
// must be set properly using RepairCachePointers() once the new subcontext is
// available. This should only be invoked by ContextBase code as part of
// copying an entire Context tree.
Cache(const Cache& source) = default;
// Assumes `this` %Cache is a recent copy that does not yet have its pointers
// to the system name-providing service of the new owning Context, and sets
// those pointers. The supplied pointer must not be null, and there must not
// already be an owning subcontext set here.
void RepairCachePointers(
const internal::ContextMessageInterface* owning_subcontext);
// The system name service of the subcontext that owns this cache. This should
// not be copied since it would still refer to the source subcontext.
reset_on_copy<const internal::ContextMessageInterface*>
owning_subcontext_;
// All CacheEntryValue objects, indexed by CacheIndex.
std::vector<copyable_unique_ptr<CacheEntryValue>> store_;
// A per-Cache (and hence, per-Context) mutable, unused cache entry value
// object, which has no valid CacheIndex or DependencyTicket and has a
// meaningless value. A DependencyTracker may invoke mark_up_to_date()
// harmlessly on this object, but may not depend on its contents in any way as
// they may change unexpectedly. The intention is that this object is used as
// a common throw-away destination for non-cache DependencyTracker
// invalidations so that invalidation can be done unconditionally, and to the
// same memory location within a LeafContext, for speed.
CacheEntryValue dummy_;
// Whether we are currently preventing mutable access to the cache.
bool is_cache_frozen_{false};
};
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/vector_system.h | #pragma once
#include <memory>
#include <optional>
#include <set>
#include <utility>
#include <vector>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/drake_throw.h"
#include "drake/common/eigen_types.h"
#include "drake/common/never_destroyed.h"
#include "drake/common/unused.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/context.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace systems {
/// A base class that specializes LeafSystem for use with only zero or one
/// vector input ports, and only zero or one vector output ports.
///
/// @system
/// name: VectorSystem
/// input_ports:
/// - u0
/// output_ports:
/// - y0
/// @endsystem
///
/// By default, this base class does not declare any state; subclasses may
/// optionally declare continuous or discrete state, but not both; subclasses
/// may not declare abstract state.
///
/// @tparam_default_scalar
template <typename T>
class VectorSystem : public LeafSystem<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(VectorSystem)
~VectorSystem() override = default;
protected:
/// Creates a system with one input port and one output port of the given
/// sizes, when the sizes are non-zero. Either size can be zero, in which
/// case no input (or output) port is created.
///
/// The `direct_feedthrough` specifies whether the input port direct feeds
/// through to the output port. (See SystemBase::GetDirectFeedthroughs().)
/// When not provided, assumes true (the output is direct feedthrough).
/// When false, the DoCalcVectorOutput `input` will be empty (zero-sized).
///
/// Does *not* declare scalar-type conversion support (AutoDiff, etc.). To
/// enable AutoDiff support, use the SystemScalarConverter-based constructor.
/// (For that, see @ref system_scalar_conversion at the example titled
/// "Example using drake::systems::VectorSystem as the base class".)
VectorSystem(int input_size, int output_size,
std::optional<bool> direct_feedthrough = std::nullopt)
: VectorSystem(SystemScalarConverter{}, input_size, output_size,
direct_feedthrough) {}
/// Creates a system with one input port and one output port of the given
/// sizes, when the sizes are non-zero. Either size can be zero, in which
/// case no input (or output) port is created. This constructor allows
/// subclasses to declare scalar-type conversion support (AutoDiff, etc.).
///
/// The `direct_feedthrough` specifies whether the input port direct feeds
/// through to the output port. (See SystemBase::GetDirectFeedthroughs().)
/// When not provided, infers feedthrough from the symbolic form if
/// available, or else assumes true (the output is direct feedthrough).
/// When false, the DoCalcVectorOutput `input` will be empty (zero-sized).
///
/// The scalar-type conversion support will use @p converter.
/// To enable scalar-type conversion support, pass a `SystemTypeTag<S>{}`
/// where `S` must be the exact class of `this` being constructed.
///
/// See @ref system_scalar_conversion for detailed background and examples
/// related to scalar-type conversion support, especially the example titled
/// "Example using drake::systems::VectorSystem as the base class".
VectorSystem(SystemScalarConverter converter, int input_size, int output_size,
std::optional<bool> direct_feedthrough = std::nullopt)
: LeafSystem<T>(std::move(converter)) {
if (input_size > 0) {
this->DeclareInputPort(kUseDefaultName, kVectorValued, input_size);
}
if (output_size > 0) {
std::set<DependencyTicket> prerequisites_of_calc;
if (direct_feedthrough.value_or(true)) {
// Depend on everything.
prerequisites_of_calc = {
this->all_sources_ticket()
};
} else {
// Depend on everything *except* for the inputs.
prerequisites_of_calc = {
this->time_ticket(),
this->accuracy_ticket(),
this->all_state_ticket(),
this->all_parameters_ticket(),
};
}
this->DeclareVectorOutputPort(
kUseDefaultName, output_size,
&VectorSystem::CalcVectorOutput, std::move(prerequisites_of_calc));
}
this->DeclareForcedDiscreteUpdateEvent(
&VectorSystem<T>::CalcDiscreteUpdate);
}
/// Causes the vector-valued input port to become up-to-date, and returns
/// the port's value as an %Eigen vector. If the system has zero inputs,
/// then returns an empty vector.
const VectorX<T>& EvalVectorInput(
const Context<T>& context) const {
// Obtain a reference to u (or the empty vector).
if (this->num_input_ports() > 0) {
return this->get_input_port().Eval(context);
}
static const never_destroyed<VectorX<T>> empty_vector(0);
return empty_vector.access();
}
/// Returns a reference to an %Eigen vector version of the state from within
/// the %Context.
const VectorX<T>& GetVectorState(
const Context<T>& context) const {
// Obtain the block form of xc or xd.
DRAKE_ASSERT(context.num_abstract_states() == 0);
const BasicVector<T>* state_vector{};
if (context.num_discrete_state_groups() == 0) {
const VectorBase<T>& vector_base = context.get_continuous_state_vector();
state_vector = dynamic_cast<const BasicVector<T>*>(&vector_base);
} else {
DRAKE_ASSERT(context.has_only_discrete_state());
state_vector = &context.get_discrete_state(0);
}
DRAKE_DEMAND(state_vector != nullptr);
return state_vector->value();
}
/// Converts the parameters to Eigen::VectorBlock form, then delegates to
/// DoCalcVectorTimeDerivatives().
void DoCalcTimeDerivatives(const Context<T>& context,
ContinuousState<T>* derivatives) const final {
// Short-circuit when there's no work to do.
if (derivatives->size() == 0) {
return;
}
const VectorX<T>& input_vector = EvalVectorInput(context);
const auto input_block = input_vector.head(input_vector.rows());
// Obtain the block form of xc.
DRAKE_ASSERT(context.has_only_continuous_state());
const VectorBase<T>& state_base = context.get_continuous_state_vector();
const VectorX<T>& state_vector =
dynamic_cast<const BasicVector<T>&>(state_base).value();
const Eigen::VectorBlock<const VectorX<T>> state_block =
state_vector.head(state_vector.rows());
// Obtain the block form of xcdot.
VectorBase<T>& derivatives_base = derivatives->get_mutable_vector();
Eigen::VectorBlock<VectorX<T>> derivatives_block =
dynamic_cast<BasicVector<T>&>(derivatives_base).get_mutable_value();
// Delegate to subclass.
DoCalcVectorTimeDerivatives(context, input_block, state_block,
&derivatives_block);
}
/// Converts the parameters to Eigen::VectorBlock form, then delegates to
/// DoCalcVectorOutput().
void CalcVectorOutput(const Context<T>& context,
BasicVector<T>* output) const {
// Should only get here if we've declared an output.
DRAKE_ASSERT(this->num_output_ports() > 0);
// Decide whether we should evaluate our input port and pass its value to
// our subclass's DoCalcVectorOutput method. When should_eval_input is
// false, we will pass an empty vector instead of pulling on our input.
bool should_eval_input = false;
if (this->num_input_ports() > 0) {
// We have an input port, but when our subclass's DoCalcVectorOutput is
// not direct-feedthrough, then evaluating the input port might cause a
// computational loop. We should only evaluate the input when this
// System is declared to be direct-feedthrough (i.e., by asking a System
// base class method such as HasAnyDirectFeedthrough).
//
// However, there is a Catch-22: our LeafSystem base class contains a
// default implementation of feedthrough reporting that uses the
// SystemSymbolicInspector to infer sparsity. The inspector fixes the
// input port to be a symbolic Variable, and then evaluates the output.
// If during that output calculation, this method *again* asked to
// compute the feedthrough, we would re-enter the inspection code and
// cause infinite recursion. We would have a Calc -> HasAny -> Calc ...
// infinite loop.
//
// To break that recursion, we avoid HasAnyDirectFeedthrough when our
// scalar type is a symbolic expression and the input port is fixed. We
// know the inspector must always used a fixed input port (it has no
// diagram that it could use), so this will always bottom out the
// recursion. Even if not being evaluated by the symbolic inspector, if
// the input port is fixed to a symbolic expression then it is no harm to
// evaluate the input, even if the system is not supposed to have
// feedthrough -- it is merely providing extra ignored data to the
// DoCalcVectorOutput helper.
constexpr bool is_symbolic = std::is_same_v<T, symbolic::Expression>;
const bool is_fixed_input =
(context.MaybeGetFixedInputPortValue(0) != nullptr);
if (is_symbolic && is_fixed_input) {
should_eval_input = true;
} else {
should_eval_input = this->HasAnyDirectFeedthrough();
}
}
// Only provide input when direct feedthrough occurs; otherwise, we might
// create a computational loop.
static const never_destroyed<VectorX<T>> empty_vector(0);
const VectorX<T>& input_vector =
should_eval_input ? EvalVectorInput(context) :
empty_vector.access();
const Eigen::VectorBlock<const VectorX<T>> input_block =
input_vector.head(input_vector.rows());
// Obtain the block form of xc or xd.
const VectorX<T>& state_vector = GetVectorState(context);
const Eigen::VectorBlock<const VectorX<T>> state_block =
state_vector.head(state_vector.rows());
// Obtain the block form of y.
Eigen::VectorBlock<VectorX<T>> output_block = output->get_mutable_value();
// Delegate to subclass.
DoCalcVectorOutput(context, input_block, state_block, &output_block);
}
/// Provides a convenience method for %VectorSystem subclasses. This
/// method performs the same logical operation as System::DoCalcOutput but
/// provides VectorBlocks to represent the input, state, and output.
/// Subclasses with outputs should override this method, and not the base
/// class method (which is `final`).
///
/// The @p state will be either empty, the continuous state, or the discrete
/// state, depending on which (or none) was declared at context-creation
/// time.
///
/// The @p input will be empty (zero-sized) when this System is declared to
/// be non-direct-feedthrough.
///
/// By default, this function does nothing if the @p output is empty,
/// and throws an exception otherwise.
virtual void DoCalcVectorOutput(
const Context<T>& context,
const Eigen::VectorBlock<const VectorX<T>>& input,
const Eigen::VectorBlock<const VectorX<T>>& state,
Eigen::VectorBlock<VectorX<T>>* output) const {
unused(context, input, state);
DRAKE_THROW_UNLESS(output->size() == 0);
}
/// Provides a convenience method for %VectorSystem subclasses. This
/// method performs the same logical operation as
/// System::DoCalcTimeDerivatives but provides VectorBlocks to represent the
/// input, continuous state, and derivatives. Subclasses should override
/// this method, and not the base class method (which is `final`).
/// The @p state will be either empty or the continuous state, depending on
/// whether continuous state was declared at context-creation time.
///
/// By default, this function does nothing if the @p derivatives are empty,
/// and throws an exception otherwise.
virtual void DoCalcVectorTimeDerivatives(
const Context<T>& context,
const Eigen::VectorBlock<const VectorX<T>>& input,
const Eigen::VectorBlock<const VectorX<T>>& state,
Eigen::VectorBlock<VectorX<T>>* derivatives) const {
unused(context, input, state);
DRAKE_THROW_UNLESS(derivatives->size() == 0);
}
/// Declares a discrete update rate. You must override
/// DoCalcVectorDiscreteVariableUpdates() to handle the update.
void DeclarePeriodicDiscreteUpdate(double period_sec, double offset_sec) {
this->DeclarePeriodicDiscreteUpdateEvent(
period_sec, offset_sec, &VectorSystem<T>::CalcDiscreteUpdate);
}
/// Provides a convenience method for %VectorSystem subclasses. This
/// method serves as the callback for DeclarePeriodicDiscreteUpdate(),
/// immediately above.
///
/// The @p state will be either empty or the discrete state, depending on
/// whether discrete state was declared at context-creation time.
///
/// By default, this function does nothing if the @p next_state is
/// empty, and throws an exception otherwise.
virtual void DoCalcVectorDiscreteVariableUpdates(
const Context<T>& context,
const Eigen::VectorBlock<const VectorX<T>>& input,
const Eigen::VectorBlock<const VectorX<T>>& state,
Eigen::VectorBlock<VectorX<T>>* next_state) const {
unused(context, input, state);
DRAKE_THROW_UNLESS(next_state->size() == 0);
}
private:
// Confirms the VectorSystem invariants when allocating the context.
void DoValidateAllocatedLeafContext(
const LeafContext<T>& context) const final {
// N.B. The DRAKE_THROW_UNLESS conditions can be triggered by subclass
// mistakes, so are part of our unit tests. The DRAKE_DEMAND conditions
// should be invariants guaranteed by the framework, so are asserted.
// Exactly one input and output.
DRAKE_THROW_UNLESS(this->num_input_ports() <= 1);
DRAKE_THROW_UNLESS(this->num_output_ports() <= 1);
DRAKE_DEMAND(context.num_input_ports() <= 1);
// At most one of either continuous or discrete state.
DRAKE_THROW_UNLESS(context.num_abstract_states() == 0);
const int continuous_size = context.num_continuous_states();
const int num_discrete_groups = context.num_discrete_state_groups();
DRAKE_DEMAND(continuous_size >= 0);
DRAKE_DEMAND(num_discrete_groups >= 0);
DRAKE_THROW_UNLESS(num_discrete_groups <= 1);
DRAKE_THROW_UNLESS((continuous_size == 0) || (num_discrete_groups == 0));
}
// Converts the parameters to Eigen::VectorBlock form, then delegates to
// DoCalcVectorDiscreteVariableUpdates().
EventStatus CalcDiscreteUpdate(const Context<T>& context,
DiscreteValues<T>* discrete_state) const;
};
} // namespace systems
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::VectorSystem)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/diagram.cc | #include "drake/systems/framework/diagram.h"
#include <limits>
#include <set>
#include <stdexcept>
#include <unordered_set>
#include "drake/common/drake_assert.h"
#include "drake/common/string_unordered_set.h"
#include "drake/common/text_logging.h"
#include "drake/systems/framework/abstract_value_cloner.h"
#include "drake/systems/framework/subvector.h"
#include "drake/systems/framework/system_constraint.h"
#include "drake/systems/framework/system_visitor.h"
namespace drake {
namespace systems {
template <typename T>
Diagram<T>::~Diagram() {}
template <typename T>
std::vector<const systems::System<T>*> Diagram<T>::GetSystems() const {
std::vector<const systems::System<T>*> result;
result.reserve(registered_systems_.size());
for (const auto& system : registered_systems_) {
result.push_back(system.get());
}
return result;
}
template <typename T>
void Diagram<T>::Accept(SystemVisitor<T>* v) const {
DRAKE_DEMAND(v != nullptr);
v->VisitDiagram(*this);
}
template <typename T>
const std::map<typename Diagram<T>::InputPortLocator,
typename Diagram<T>::OutputPortLocator>&
Diagram<T>::connection_map() const {
return connection_map_;
}
template <typename T>
std::vector<typename Diagram<T>::InputPortLocator>
Diagram<T>::GetInputPortLocators(
InputPortIndex port_index) const {
DRAKE_DEMAND(port_index >= 0 && port_index < this->num_input_ports());
std::vector<typename Diagram<T>::InputPortLocator> result;
for (const auto& map_pair : input_port_map_) {
if (map_pair.second == port_index) {
result.push_back(map_pair.first);
}
}
return result;
}
template <typename T>
typename Diagram<T>::InputPortLocator
Diagram<T>::GetArbitraryInputPortLocator(InputPortIndex port_index) const {
DRAKE_DEMAND(port_index >= 0 && port_index < this->num_input_ports());
const auto ids = GetInputPortLocators(port_index);
DRAKE_ASSERT(!ids.empty());
return ids[0];
}
template <typename T>
const typename Diagram<T>::OutputPortLocator&
Diagram<T>::get_output_port_locator(OutputPortIndex port_index) const {
DRAKE_DEMAND(port_index >= 0 &&
port_index < static_cast<int>(output_port_ids_.size()));
return output_port_ids_[port_index];
}
template <typename T>
std::multimap<int, int> Diagram<T>::GetDirectFeedthroughs() const {
std::unordered_map<const System<T>*, std::multimap<int, int>> memoize;
std::multimap<int, int> pairs;
for (InputPortIndex u(0); u < this->num_input_ports(); ++u) {
for (OutputPortIndex v(0); v < this->num_output_ports(); ++v) {
if (DiagramHasDirectFeedthrough(u, v, &memoize)) {
pairs.emplace(u, v);
}
}
}
return pairs;
}
template <typename T>
std::unique_ptr<CompositeEventCollection<T>>
Diagram<T>::DoAllocateCompositeEventCollection() const {
const int num_systems = num_subsystems();
std::vector<std::unique_ptr<CompositeEventCollection<T>>> subevents(
num_systems);
for (SubsystemIndex i(0); i < num_systems; ++i) {
subevents[i] = registered_systems_[i]->AllocateCompositeEventCollection();
}
return std::make_unique<DiagramCompositeEventCollection<T>>(
std::move(subevents));
}
template <typename T>
void Diagram<T>::SetDefaultParameters(const Context<T>& context,
Parameters<T>* params) const {
this->ValidateContext(context);
auto diagram_context = dynamic_cast<const DiagramContext<T>*>(&context);
DRAKE_DEMAND(diagram_context != nullptr);
this->ValidateCreatedForThisSystem(params);
int numeric_parameter_offset = 0;
int abstract_parameter_offset = 0;
// Set default parameters of each constituent system.
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
auto& subcontext = diagram_context->GetSubsystemContext(i);
if (!subcontext.num_numeric_parameter_groups() &&
!subcontext.num_abstract_parameters()) {
// Then there is no work to do for this subcontext.
continue;
}
// Make a new Parameters<T> structure with pointers to the mutable
// subsystem parameter values. This does not make a copy of the
// underlying data.
// TODO(russt): Consider implementing a DiagramParameters, analogous to
// DiagramState, to avoid these dynamic allocations if they prove
// expensive.
std::vector<BasicVector<T>*> numeric_params;
for (int j = 0; j < subcontext.num_numeric_parameter_groups(); ++j) {
numeric_params.push_back(¶ms->get_mutable_numeric_parameter(
numeric_parameter_offset + j));
}
numeric_parameter_offset += subcontext.num_numeric_parameter_groups();
std::vector<AbstractValue*> abstract_params;
for (int j = 0; j < subcontext.num_abstract_parameters(); ++j) {
abstract_params.push_back(¶ms->get_mutable_abstract_parameter(
abstract_parameter_offset + j));
}
abstract_parameter_offset += subcontext.num_abstract_parameters();
Parameters<T> subparameters;
subparameters.set_numeric_parameters(
std::make_unique<DiscreteValues<T>>(numeric_params));
subparameters.set_abstract_parameters(
std::make_unique<AbstractValues>(abstract_params));
subparameters.set_system_id(subcontext.get_system_id());
registered_systems_[i]->SetDefaultParameters(subcontext, &subparameters);
}
}
template <typename T>
void Diagram<T>::SetDefaultState(const Context<T>& context,
State<T>* state) const {
this->ValidateContext(context);
auto diagram_context = dynamic_cast<const DiagramContext<T>*>(&context);
DRAKE_DEMAND(diagram_context != nullptr);
this->ValidateCreatedForThisSystem(state);
auto diagram_state = dynamic_cast<DiagramState<T>*>(state);
DRAKE_DEMAND(diagram_state != nullptr);
// Set default state of each constituent system.
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
auto& subcontext = diagram_context->GetSubsystemContext(i);
auto& substate = diagram_state->get_mutable_substate(i);
registered_systems_[i]->SetDefaultState(subcontext, &substate);
}
}
template <typename T>
void Diagram<T>::SetRandomState(const Context<T>& context, State<T>* state,
RandomGenerator* generator) const {
this->ValidateContext(context);
auto diagram_context = dynamic_cast<const DiagramContext<T>*>(&context);
DRAKE_DEMAND(diagram_context != nullptr);
this->ValidateCreatedForThisSystem(state);
auto diagram_state = dynamic_cast<DiagramState<T>*>(state);
DRAKE_DEMAND(diagram_state != nullptr);
// Set state of each constituent system.
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
auto& subcontext = diagram_context->GetSubsystemContext(i);
auto& substate = diagram_state->get_mutable_substate(i);
registered_systems_[i]->SetRandomState(subcontext, &substate, generator);
}
}
template <typename T>
void Diagram<T>::SetRandomParameters(const Context<T>& context,
Parameters<T>* params,
RandomGenerator* generator) const {
this->ValidateContext(context);
auto diagram_context = dynamic_cast<const DiagramContext<T>*>(&context);
DRAKE_DEMAND(diagram_context != nullptr);
this->ValidateCreatedForThisSystem(params);
int numeric_parameter_offset = 0;
int abstract_parameter_offset = 0;
// Set parameters of each constituent system.
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
auto& subcontext = diagram_context->GetSubsystemContext(i);
if (!subcontext.num_numeric_parameter_groups() &&
!subcontext.num_abstract_parameters()) {
// Then there is no work to do for this subcontext.
continue;
}
// Make a new Parameters<T> structure with pointers to the mutable
// subsystem parameter values. This does not make a copy of the
// underlying data.
// TODO(russt): This code is duplicated from SetDefaultParameters.
// Consider extracting it to a helper method (waiting for the rule of
// three).
std::vector<BasicVector<T>*> numeric_params;
std::vector<AbstractValue*> abstract_params;
for (int j = 0; j < subcontext.num_numeric_parameter_groups(); ++j) {
numeric_params.push_back(¶ms->get_mutable_numeric_parameter(
numeric_parameter_offset + j));
}
numeric_parameter_offset += subcontext.num_numeric_parameter_groups();
for (int j = 0; j < subcontext.num_abstract_parameters(); ++j) {
abstract_params.push_back(¶ms->get_mutable_abstract_parameter(
abstract_parameter_offset + j));
}
abstract_parameter_offset += subcontext.num_abstract_parameters();
Parameters<T> subparameters;
subparameters.set_numeric_parameters(
std::make_unique<DiscreteValues<T>>(numeric_params));
subparameters.set_abstract_parameters(
std::make_unique<AbstractValues>(abstract_params));
subparameters.set_system_id(subcontext.get_system_id());
registered_systems_[i]->SetRandomParameters(subcontext, &subparameters,
generator);
}
}
template <typename T>
std::unique_ptr<EventCollection<PublishEvent<T>>>
Diagram<T>::AllocateForcedPublishEventCollection() const {
return AllocateForcedEventCollection<PublishEvent<T>>(
&System<T>::AllocateForcedPublishEventCollection);
}
template <typename T>
std::unique_ptr<EventCollection<DiscreteUpdateEvent<T>>>
Diagram<T>::AllocateForcedDiscreteUpdateEventCollection() const {
return AllocateForcedEventCollection<DiscreteUpdateEvent<T>>(
&System<T>::AllocateForcedDiscreteUpdateEventCollection);
}
template <typename T>
std::unique_ptr<EventCollection<UnrestrictedUpdateEvent<T>>>
Diagram<T>::AllocateForcedUnrestrictedUpdateEventCollection() const {
return AllocateForcedEventCollection<UnrestrictedUpdateEvent<T>>(
&System<T>::AllocateForcedUnrestrictedUpdateEventCollection);
}
template <typename T>
std::unique_ptr<ContinuousState<T>> Diagram<T>::AllocateTimeDerivatives()
const {
std::vector<std::unique_ptr<ContinuousState<T>>> sub_derivatives;
for (const auto& system : registered_systems_) {
sub_derivatives.push_back(system->AllocateTimeDerivatives());
}
auto result = std::make_unique<DiagramContinuousState<T>>(
std::move(sub_derivatives));
result->set_system_id(this->get_system_id());
return result;
}
template <typename T>
std::unique_ptr<DiscreteValues<T>> Diagram<T>::AllocateDiscreteVariables()
const {
std::vector<std::unique_ptr<DiscreteValues<T>>> sub_discretes;
for (const auto& system : registered_systems_) {
sub_discretes.push_back(system->AllocateDiscreteVariables());
}
auto result =
std::make_unique<DiagramDiscreteValues<T>>(std::move(sub_discretes));
result->set_system_id(this->get_system_id());
return result;
}
template <typename T>
void Diagram<T>::DoCalcTimeDerivatives(const Context<T>& context,
ContinuousState<T>* derivatives) const {
auto diagram_context = dynamic_cast<const DiagramContext<T>*>(&context);
DRAKE_DEMAND(diagram_context != nullptr);
auto diagram_derivatives =
dynamic_cast<DiagramContinuousState<T>*>(derivatives);
DRAKE_DEMAND(diagram_derivatives != nullptr);
const int n = diagram_derivatives->num_substates();
DRAKE_DEMAND(num_subsystems() == n);
// Evaluate the derivatives of each constituent system.
for (SubsystemIndex i(0); i < n; ++i) {
const Context<T>& subcontext = diagram_context->GetSubsystemContext(i);
ContinuousState<T>& subderivatives =
diagram_derivatives->get_mutable_substate(i);
registered_systems_[i]->CalcTimeDerivatives(subcontext, &subderivatives);
}
}
template <typename T>
void Diagram<T>::DoCalcImplicitTimeDerivativesResidual(
const Context<T>& context, const ContinuousState<T>& proposed_derivatives,
EigenPtr<VectorX<T>> residual) const {
// Check that the arguments are at least structurally compatible with
// this Diagram.
auto diagram_context = dynamic_cast<const DiagramContext<T>*>(&context);
DRAKE_DEMAND(diagram_context != nullptr);
const auto* diagram_derivatives =
dynamic_cast<const DiagramContinuousState<T>*>(&proposed_derivatives);
DRAKE_DEMAND(diagram_derivatives != nullptr);
const int n = diagram_derivatives->num_substates();
DRAKE_DEMAND(num_subsystems() == n);
// The public method has already verified that the output vector is the right
// length.
// Evaluate the residuals from each constituent system.
int next = 0; // Next available slot in residual vector.
for (SubsystemIndex i(0); i < n; ++i) {
const Context<T>& subcontext = diagram_context->GetSubsystemContext(i);
const ContinuousState<T>& subderivatives =
diagram_derivatives->get_substate(i);
const System<T>& subsystem = *registered_systems_[i];
const int num_sub_residuals =
subsystem.implicit_time_derivatives_residual_size();
// The "const" here is for the returned object; the data to which it
// refers is still mutable because residual is.
const auto segment = residual->segment(next, num_sub_residuals);
subsystem.CalcImplicitTimeDerivativesResidual(subcontext, subderivatives,
&segment);
next += num_sub_residuals;
}
// Make sure we wrote to every element.
DRAKE_DEMAND(next == residual->size());
}
template <typename T>
bool Diagram<T>::HasSubsystemNamed(std::string_view name) const {
for (const auto& child : registered_systems_) {
if (child->get_name() == name) {
return true;
}
}
return false;
}
template <typename T>
const System<T>& Diagram<T>::GetSubsystemByName(std::string_view name) const {
for (const auto& child : registered_systems_) {
if (child->get_name() == name) {
return *child;
}
}
std::vector<std::string> subsystem_names;
subsystem_names.reserve(registered_systems_.size());
for (const auto& child : registered_systems_) {
subsystem_names.emplace_back(child->get_name());
}
throw std::logic_error(fmt::format(
"System {} does not have a subsystem named {}. The existing subsystems "
"are named {{{}}}.",
this->GetSystemName(), name, fmt::join(subsystem_names, ", ")));
}
template <typename T>
const ContinuousState<T>& Diagram<T>::GetSubsystemDerivatives(
const System<T>& subsystem,
const ContinuousState<T>& derivatives) const {
this->ValidateCreatedForThisSystem(derivatives);
auto diagram_derivatives =
dynamic_cast<const DiagramContinuousState<T>*>(&derivatives);
DRAKE_DEMAND(diagram_derivatives != nullptr);
const SubsystemIndex i = GetSystemIndexOrAbort(&subsystem);
return diagram_derivatives->get_substate(i);
}
template <typename T>
const DiscreteValues<T>& Diagram<T>::GetSubsystemDiscreteValues(
const System<T>& subsystem,
const DiscreteValues<T>& discrete_values) const {
this->ValidateCreatedForThisSystem(discrete_values);
auto diagram_discrete_state =
dynamic_cast<const DiagramDiscreteValues<T>*>(&discrete_values);
DRAKE_DEMAND(diagram_discrete_state != nullptr);
const SubsystemIndex i = GetSystemIndexOrAbort(&subsystem);
return diagram_discrete_state->get_subdiscrete(i);
}
template <typename T>
const CompositeEventCollection<T>&
Diagram<T>::GetSubsystemCompositeEventCollection(const System<T>& subsystem,
const CompositeEventCollection<T>& events) const {
this->ValidateCreatedForThisSystem(events);
auto ret = DoGetTargetSystemCompositeEventCollection(subsystem, &events);
DRAKE_DEMAND(ret != nullptr);
return *ret;
}
template <typename T>
CompositeEventCollection<T>&
Diagram<T>::GetMutableSubsystemCompositeEventCollection(
const System<T>& subsystem, CompositeEventCollection<T>* events) const {
this->ValidateCreatedForThisSystem(events);
auto ret = DoGetMutableTargetSystemCompositeEventCollection(
subsystem, events);
DRAKE_DEMAND(ret != nullptr);
return *ret;
}
template <typename T>
State<T>& Diagram<T>::GetMutableSubsystemState(const System<T>& subsystem,
Context<T>* context) const {
this->ValidateContext(context);
Context<T>& subcontext = GetMutableSubsystemContext(subsystem, context);
return subcontext.get_mutable_state();
}
template <typename T>
State<T>& Diagram<T>::GetMutableSubsystemState(const System<T>& subsystem,
State<T>* state) const {
this->ValidateCreatedForThisSystem(state);
auto ret = DoGetMutableTargetSystemState(subsystem, state);
DRAKE_DEMAND(ret != nullptr);
return *ret;
}
template <typename T>
const State<T>& Diagram<T>::GetSubsystemState(const System<T>& subsystem,
const State<T>& state) const {
this->ValidateCreatedForThisSystem(state);
auto ret = DoGetTargetSystemState(subsystem, &state);
DRAKE_DEMAND(ret != nullptr);
return *ret;
}
namespace {
// Filter the options per the subsystem's name.
std::map<std::string, std::string> FilterGraphvizOptions(
const std::map<std::string, std::string>& diagram_options,
const SystemBase& subsystem) {
const std::string key_prefix = subsystem.get_name() + "/";
const size_t key_prefix_size = key_prefix.size();
std::map<std::string, std::string> result;
for (const auto& [key, value] : diagram_options) {
if (key.substr(0, key_prefix_size) == key_prefix) {
result.emplace(key.substr(key_prefix_size), value);
}
}
return result;
}
} // namespace
template <typename T>
typename Diagram<T>::GraphvizFragment Diagram<T>::DoGetGraphvizFragment(
const GraphvizFragmentParams& params) const {
// If we've reached max depth, treat us like a leaf system.
if (params.max_depth <= 0) {
return System<T>::DoGetGraphvizFragment(params);
}
// Recursively assemble the subsystems' fragments.
std::map<const System<T>*, GraphvizFragment> subsystem_fragments;
for (const auto& subsystem : registered_systems_) {
subsystem_fragments.emplace(
subsystem.get(),
subsystem->GetGraphvizFragment(
params.max_depth - 1,
FilterGraphvizOptions(params.options, *subsystem)));
}
// Assemble our fragments into a subgraph.
GraphvizFragment result;
const int64_t id = this->get_system_id().get_value();
// Open the diagram, with its label.
result.fragments.push_back(fmt::format(
R"""(subgraph cluster{}diagram {{
color=black
concentrate=true
label=<<TABLE BORDER="0"><TR><TD>
{}
</TD></TR></TABLE>>;
)""",
id, fmt::join(params.header_lines, "<BR/>\n")));
// Add clusters for input and output ports. This helper function is called up
// to twice (once for input ports, if any; once for output ports, if any).
// It appends the graphviz content to `fragments` and port IDs to `port_ids`.
// The node that holds the ports will use ID `ports_node_id`.
auto print_ports = [](std::vector<std::string>* fragments,
std::vector<std::string>* port_ids,
const std::string& kind /* "input" or "output" */,
const std::string& ports_node_id,
const std::string& color,
const std::vector<std::string>& labels) {
fragments->push_back(fmt::format(
R"""(subgraph cluster{} {{
rank=same
color=lightgrey
style=filled
label="{} ports"
{} [shape=none, label=<
<TABLE BORDER="0" COLOR="{}" CELLSPACING="3" STYLE="rounded">
)""",
ports_node_id, kind, ports_node_id, color));
for (int i = 0; i < ssize(labels); ++i) {
fragments->push_back(
fmt::format(R"""(<TR><TD BORDER="1" PORT="{}">{}</TD></TR>
)""",
i, labels[i]));
port_ids->push_back(fmt::format("{}:{}", ports_node_id, i));
}
fragments->push_back(R"""(</TABLE>
>];
}
)""");
};
if (this->num_input_ports() > 0) {
std::string inputs_node_id = fmt::format("{}in", params.node_id);
print_ports(&result.fragments, &result.input_ports, "input", inputs_node_id,
"blue", GetGraphvizPortLabels(/* input= */ true));
}
if (this->num_output_ports() > 0) {
std::string outputs_node_id = fmt::format("{}out", params.node_id);
print_ports(&result.fragments, &result.output_ports, "output",
outputs_node_id, "green",
GetGraphvizPortLabels(/* input= */ false));
}
// Open a cluster for the subsystems.
result.fragments.push_back(fmt::format(
R"""(subgraph cluster{}subsystems {{
color=white
label=""
)""",
id));
// -- Add the subsystems themselves.
for (const auto& subsystem : registered_systems_) {
GraphvizFragment& sub_frag = subsystem_fragments.at(subsystem.get());
std::move(sub_frag.fragments.begin(), sub_frag.fragments.end(),
std::back_inserter(result.fragments));
}
// -- Add the connections as edges.
for (const auto& edge : connection_map_) {
const System<T>* src_sys = edge.second.first;
const OutputPortIndex src_index = edge.second.second;
const System<T>* dest_sys = edge.first.first;
const InputPortIndex dest_index = edge.first.second;
result.fragments.push_back(fmt::format(
"{}:e -> {}:w\n",
subsystem_fragments.at(src_sys).output_ports.at(src_index),
subsystem_fragments.at(dest_sys).input_ports.at(dest_index)));
}
// -- Add edges from the input and output port nodes to the subsystems that
// actually service that port. These edges are highlighted in blue
// (input) and green (output), matching the port nodes.
for (int i = 0; i < this->num_input_ports(); ++i) {
for (const auto& port_id : GetInputPortLocators(InputPortIndex(i))) {
const System<T>* sub_sys = port_id.first;
const InputPortIndex sub_index = port_id.second;
const std::string& from = result.input_ports.at(i);
const std::string& to =
subsystem_fragments.at(sub_sys).input_ports.at(sub_index);
result.fragments.push_back(
fmt::format("{}:e -> {}:w [color=blue];\n", from, to));
}
}
for (int i = 0; i < this->num_output_ports(); ++i) {
const auto& port_id = output_port_ids_.at(i);
const System<T>* sub_sys = port_id.first;
const OutputPortIndex sub_index = port_id.second;
const std::string& from =
subsystem_fragments.at(sub_sys).output_ports.at(sub_index);
const std::string& to = result.output_ports.at(i);
result.fragments.push_back(
fmt::format("{}:e -> {}:w [color=green];\n", from, to));
}
// Close the cluster for subsystems and then the diagram.
result.fragments.push_back("}\n}\n");
return result;
}
template <typename T>
std::vector<std::string> Diagram<T>::GetGraphvizPortLabels(bool input) const {
return internal::DiagramSystemBaseAttorney::GetGraphvizPortLabels(*this,
input);
}
template <typename T>
SubsystemIndex Diagram<T>::GetSystemIndexOrAbort(const System<T>* sys) const {
auto it = system_index_map_.find(sys);
DRAKE_DEMAND(it != system_index_map_.end());
return it->second;
}
template <typename T>
bool Diagram<T>::AreConnected(const OutputPort<T>& output,
const InputPort<T>& input) const {
InputPortLocator in{&input.get_system(), input.get_index()};
OutputPortLocator out{&output.get_system(), output.get_index()};
const auto range = connection_map_.equal_range(in);
for (auto iter = range.first; iter != range.second; ++iter) {
if (iter->second == out) return true;
}
return false;
}
template <typename T>
Diagram<T>::Diagram() : System<T>(
SystemScalarConverter::MakeWithoutSubtypeChecking<Diagram>()) {}
template <typename T>
Diagram<T>::Diagram(SystemScalarConverter converter)
: System<T>(std::move(converter)) {}
template <typename T>
T Diagram<T>::DoCalcWitnessValue(const Context<T>& context,
const WitnessFunction<T>& witness_func) const {
const System<T>& system = witness_func.get_system();
const Context<T>& subcontext = GetSubsystemContext(system, context);
return witness_func.CalcWitnessValue(subcontext);
}
template <typename T>
void Diagram<T>::AddTriggeredWitnessFunctionToCompositeEventCollection(
Event<T>* event,
CompositeEventCollection<T>* events) const {
DRAKE_DEMAND(events != nullptr);
DRAKE_DEMAND(event != nullptr);
// Get the event data- it will need to be modified.
WitnessTriggeredEventData<T>* data =
event->template get_mutable_event_data<WitnessTriggeredEventData<T>>();
DRAKE_DEMAND(data != nullptr);
// Get the vector of events corresponding to the subsystem.
const System<T>& subsystem = data->triggered_witness()->get_system();
CompositeEventCollection<T>& subevents =
GetMutableSubsystemCompositeEventCollection(subsystem, events);
// Get the continuous states at both window endpoints.
auto diagram_xc0 = dynamic_cast<const DiagramContinuousState<T>*>(
data->xc0());
DRAKE_DEMAND(diagram_xc0 != nullptr);
auto diagram_xcf = dynamic_cast<const DiagramContinuousState<T>*>(
data->xcf());
DRAKE_DEMAND(diagram_xcf != nullptr);
// Modify the pointer to the event data to point to the sub-system
// continuous states.
data->set_xc0(DoGetTargetSystemContinuousState(subsystem, diagram_xc0));
data->set_xcf(DoGetTargetSystemContinuousState(subsystem, diagram_xcf));
// Add the event to the collection.
event->AddToComposite(&subevents);
}
template <typename T>
void Diagram<T>::DoGetWitnessFunctions(
const Context<T>& context,
std::vector<const WitnessFunction<T>*>* witnesses) const {
// A temporary vector is necessary since the vector of witnesses is
// declared to be empty on entry to DoGetWitnessFunctions().
std::vector<const WitnessFunction<T>*> temp_witnesses;
auto diagram_context = dynamic_cast<const DiagramContext<T>*>(&context);
DRAKE_DEMAND(diagram_context != nullptr);
SubsystemIndex index(0);
for (const auto& system : registered_systems_) {
DRAKE_ASSERT(index == GetSystemIndexOrAbort(system.get()));
temp_witnesses.clear();
system->GetWitnessFunctions(diagram_context->GetSubsystemContext(index),
&temp_witnesses);
witnesses->insert(witnesses->end(), temp_witnesses.begin(),
temp_witnesses.end());
++index;
}
}
template <typename T>
const Context<T>* Diagram<T>::DoGetTargetSystemContext(
const System<T>& target_system, const Context<T>* context) const {
if (&target_system == this)
return context;
return GetSubsystemStuff<const Context<T>, const DiagramContext<T>>(
target_system, context,
&System<T>::DoGetTargetSystemContext,
&DiagramContext<T>::GetSubsystemContext);
}
template <typename T>
State<T>* Diagram<T>::DoGetMutableTargetSystemState(
const System<T>& target_system, State<T>* state) const {
if (&target_system == this)
return state;
return GetSubsystemStuff<State<T>, DiagramState<T>>(
target_system, state,
&System<T>::DoGetMutableTargetSystemState,
&DiagramState<T>::get_mutable_substate);
}
template <typename T>
const ContinuousState<T>* Diagram<T>::DoGetTargetSystemContinuousState(
const System<T>& target_system,
const ContinuousState<T>* xc) const {
if (&target_system == this)
return xc;
return GetSubsystemStuff<const ContinuousState<T>,
const DiagramContinuousState<T>>(
target_system, xc,
&System<T>::DoGetTargetSystemContinuousState,
&DiagramContinuousState<T>::get_substate);
}
template <typename T>
const State<T>* Diagram<T>::DoGetTargetSystemState(
const System<T>& target_system, const State<T>* state) const {
if (&target_system == this)
return state;
return GetSubsystemStuff<const State<T>, const DiagramState<T>>(
target_system, state,
&System<T>::DoGetTargetSystemState,
&DiagramState<T>::get_substate);
}
template <typename T>
CompositeEventCollection<T>*
Diagram<T>::DoGetMutableTargetSystemCompositeEventCollection(
const System<T>& target_system,
CompositeEventCollection<T>* events) const {
if (&target_system == this)
return events;
return GetSubsystemStuff<CompositeEventCollection<T>,
DiagramCompositeEventCollection<T>>(
target_system, events,
&System<T>::DoGetMutableTargetSystemCompositeEventCollection,
&DiagramCompositeEventCollection<T>::get_mutable_subevent_collection);
}
template <typename T>
const CompositeEventCollection<T>*
Diagram<T>::DoGetTargetSystemCompositeEventCollection(
const System<T>& target_system,
const CompositeEventCollection<T>* events) const {
if (&target_system == this)
return events;
return GetSubsystemStuff<const CompositeEventCollection<T>,
const DiagramCompositeEventCollection<T>>(
target_system, events,
&System<T>::DoGetTargetSystemCompositeEventCollection,
&DiagramCompositeEventCollection<T>::get_subevent_collection);
}
template <typename T>
void Diagram<T>::DoMapVelocityToQDot(
const Context<T>& context,
const Eigen::Ref<const VectorX<T>>& generalized_velocity,
VectorBase<T>* qdot) const {
// Check that the dimensions of the continuous state in the context match
// the dimensions of the provided generalized velocity and configuration
// derivatives.
const ContinuousState<T>& xc = context.get_continuous_state();
const int nq = xc.get_generalized_position().size();
const int nv = xc.get_generalized_velocity().size();
DRAKE_DEMAND(nq == qdot->size());
DRAKE_DEMAND(nv == generalized_velocity.size());
auto diagram_context = dynamic_cast<const DiagramContext<T>*>(&context);
DRAKE_DEMAND(diagram_context != nullptr);
// Iterate over the subsystems, asking each subsystem to map its subslice of
// velocity to configuration derivatives. This approach is valid because the
// DiagramContinuousState guarantees that the subsystem states are
// concatenated in order.
int v_index = 0; // The next index to read in generalized_velocity.
int q_index = 0; // The next index to write in qdot.
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
// Find the continuous state of subsystem i.
const Context<T>& subcontext = diagram_context->GetSubsystemContext(i);
const ContinuousState<T>& sub_xc = subcontext.get_continuous_state();
// Select the chunk of generalized_velocity belonging to subsystem i.
const int num_v = sub_xc.get_generalized_velocity().size();
if (num_v == 0) continue;
const Eigen::Ref<const VectorX<T>>& v_slice =
generalized_velocity.segment(v_index, num_v);
// Select the chunk of qdot belonging to subsystem i.
const int num_q = sub_xc.get_generalized_position().size();
Subvector<T> dq_slice(qdot, q_index, num_q);
// Delegate the actual mapping to subsystem i itself.
registered_systems_[i]->MapVelocityToQDot(subcontext, v_slice, &dq_slice);
// Advance the indices.
v_index += num_v;
q_index += num_q;
}
}
template <typename T>
void Diagram<T>::DoMapQDotToVelocity(
const Context<T>& context,
const Eigen::Ref<const VectorX<T>>& qdot,
VectorBase<T>* generalized_velocity) const {
// Check that the dimensions of the continuous state in the context match
// the dimensions of the provided generalized velocity and configuration
// derivatives.
const ContinuousState<T>& xc = context.get_continuous_state();
const int nq = xc.get_generalized_position().size();
const int nv = xc.get_generalized_velocity().size();
DRAKE_DEMAND(nq == qdot.size());
DRAKE_DEMAND(nv == generalized_velocity->size());
auto diagram_context = dynamic_cast<const DiagramContext<T>*>(&context);
DRAKE_DEMAND(diagram_context != nullptr);
// Iterate over the subsystems, asking each subsystem to map its subslice of
// configuration derivatives to velocity. This approach is valid because the
// DiagramContinuousState guarantees that the subsystem states are
// concatenated in order.
int q_index = 0; // The next index to read in qdot.
int v_index = 0; // The next index to write in generalized_velocity.
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
// Find the continuous state of subsystem i.
const Context<T>& subcontext = diagram_context->GetSubsystemContext(i);
const ContinuousState<T>& sub_xc = subcontext.get_continuous_state();
// Select the chunk of qdot belonging to subsystem i.
const int num_q = sub_xc.get_generalized_position().size();
if (num_q == 0) continue;
const Eigen::Ref<const VectorX<T>>& dq_slice =
qdot.segment(q_index, num_q);
// Select the chunk of generalized_velocity belonging to subsystem i.
const int num_v = sub_xc.get_generalized_velocity().size();
Subvector<T> v_slice(generalized_velocity, v_index, num_v);
// Delegate the actual mapping to subsystem i itself.
registered_systems_[i]->MapQDotToVelocity(subcontext, dq_slice, &v_slice);
// Advance the indices.
v_index += num_v;
q_index += num_q;
}
}
template <typename T>
void Diagram<T>::DoCalcNextUpdateTime(const Context<T>& context,
CompositeEventCollection<T>* event_info,
T* next_update_time) const {
auto diagram_context = dynamic_cast<const DiagramContext<T>*>(&context);
auto info = dynamic_cast<DiagramCompositeEventCollection<T>*>(event_info);
DRAKE_DEMAND(diagram_context != nullptr);
DRAKE_DEMAND(info != nullptr);
CacheEntryValue& value =
this->get_cache_entry(event_times_buffer_cache_index_)
.get_mutable_cache_entry_value(context);
auto& event_times_buffer = value.GetMutableValueOrThrow<std::vector<T>>();
DRAKE_DEMAND(
static_cast<int>(event_times_buffer.size()) == num_subsystems());
// In assert-enabled builds, enforce the invariant that no stale values in
// event_times_buffer are reused across invocations. In effect,
// event_times_buffer should have the semantics of a stack variable, despite
// being cache-managed heap storage. The enforcement appears in two parts: an
// assert-build-only clearing of the storage to invalid values, and a later
// assertion that the invalid values are all replaced.
auto set_to_nan = [](std::vector<T>* vec) {
std::fill(
vec->begin(), vec->end(),
std::numeric_limits<
typename Eigen::NumTraits<T>::Literal>::quiet_NaN());
};
DRAKE_ASSERT_VOID(set_to_nan(&event_times_buffer));
*next_update_time = std::numeric_limits<double>::infinity();
// Iterate over the subsystems, and harvest the most imminent updates.
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
const Context<T>& subcontext = diagram_context->GetSubsystemContext(i);
CompositeEventCollection<T>& subinfo =
info->get_mutable_subevent_collection(i);
const T sub_time =
registered_systems_[i]->CalcNextUpdateTime(subcontext, &subinfo);
event_times_buffer[i] = sub_time;
if (sub_time < *next_update_time) {
*next_update_time = sub_time;
}
}
// Check that all vector entries were replaced.
auto none_are_nan = [](const std::vector<T>& vec) {
using std::isnan;
return std::none_of(vec.begin(), vec.end(),
[](const T& v) { return isnan(v); });
};
DRAKE_ASSERT(none_are_nan(event_times_buffer));
// For all the subsystems whose next update time is bigger than
// next_update_time, clear their event collections.
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
if (event_times_buffer[i] > *next_update_time)
info->get_mutable_subevent_collection(i).Clear();
}
}
template <typename T>
std::string Diagram<T>::GetUnsupportedScalarConversionMessage(
const std::type_info& source_type,
const std::type_info& destination_type) const {
// Start with the default message for this system.
std::stringstream result;
result << SystemBase::GetUnsupportedScalarConversionMessage(
source_type, destination_type);
// Append extra details, if we are able to.
std::vector<std::string> causes;
for (const auto& system : registered_systems_) {
const auto& converter = system->get_system_scalar_converter();
if (converter.IsConvertible(destination_type, source_type)) {
continue;
}
causes.push_back(internal::DiagramSystemBaseAttorney::
GetUnsupportedScalarConversionMessage(
*system, source_type, destination_type));
}
if (!causes.empty()) {
result << fmt::format(" (because {})", fmt::join(causes, " and "));
}
return result.str();
}
template <typename T>
std::unique_ptr<AbstractValue> Diagram<T>::DoAllocateInput(
const InputPort<T>& input_port) const {
// Ask an arbitrary connected subsystem to perform the allocation.
const auto id = GetArbitraryInputPortLocator(input_port.get_index());
const System<T>* subsystem = id.first;
const InputPortIndex subindex = id.second;
return subsystem->AllocateInputAbstract(
subsystem->get_input_port(subindex));
}
template <typename T>
std::unique_ptr<ContextBase> Diagram<T>::DoAllocateContext() const {
// Reserve inputs as specified during Diagram initialization.
auto context = std::make_unique<DiagramContext<T>>(num_subsystems());
this->InitializeContextBase(&*context);
// Recursively construct each constituent system and its subsystems,
// then add to this diagram Context.
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
const System<T>& system = *registered_systems_[i];
auto subcontext = dynamic_pointer_cast_or_throw<Context<T>>(
system.AllocateContext());
context->AddSystem(i, std::move(subcontext));
}
// Creates this diagram's composite data structures that collect its
// subsystems' resources, which must have already been allocated above. No
// dependencies are set up in these two calls. Note that MakeState()
// establishes the system_id labels for all the helper objects at the root of
// the state tree.
context->MakeParameters();
context->MakeState();
// Subscribe each of the Diagram's composite-entity dependency trackers to
// the trackers for the corresponding constituent entities in the child
// subsystems. This ensures that changes made at the subcontext level are
// propagated correctly to the diagram context level. That includes state
// and parameter changes, as well as local changes that affect composite
// diagram-level computations like xcdot and pe.
context->SubscribeDiagramCompositeTrackersToChildrens();
// Peer-to-peer connections wire a child subsystem's input port to a
// child subsystem's output port. Subscribe each child input port to the
// child output port on which it depends.
for (const auto& connection : connection_map_) {
const OutputPortLocator& src = connection.second;
const InputPortLocator& dest = connection.first;
context->SubscribeInputPortToOutputPort(
ConvertToContextPortIdentifier(src),
ConvertToContextPortIdentifier(dest));
}
// Diagram-external input ports are exported from child subsystems (meaning
// the Diagram input is fed into the input of one of its children.
// Subscribe the child subsystem's input port to its parent Diagram's input
// port on which it depends.
for (InputPortIndex i(0); i < this->num_input_ports(); ++i) {
for (const auto& id : GetInputPortLocators(i)) {
context->SubscribeExportedInputPortToDiagramPort(
i, ConvertToContextPortIdentifier(id));
}
}
// Diagram-external output ports are exported from child subsystem output
// ports. Subscribe each Diagram-level output to the child-level output on
// which it depends.
for (OutputPortIndex i(0); i < this->num_output_ports(); ++i) {
const OutputPortLocator& id = output_port_ids_[i];
context->SubscribeDiagramPortToExportedOutputPort(
i, ConvertToContextPortIdentifier(id));
}
return context;
}
template <typename T>
const AbstractValue* Diagram<T>::EvalConnectedSubsystemInputPort(
const ContextBase& context_base,
const InputPortBase& input_port_base) const {
// Profiling revealed that it is too expensive to do a dynamic_cast here.
// A static_cast is safe as long we validate the SystemId, so that we know
// this Context is ours. Proving that our caller would have already checked
// the SystemId is too complicated, so we'll always just check ourselves.
this->ValidateContext(context_base);
auto& diagram_context =
static_cast<const DiagramContext<T>&>(context_base);
// Profiling revealed that it is too expensive to do a dynamic_cast here.
// A static_cast is safe as long as the given input_port_base was actually
// an InputPort<T>, and since our sole caller is SystemBase which always
// retrieves the input_port_base from `this`, the <T> must be correct.
auto& system = static_cast<const System<T>&>(
internal::PortBaseAttorney::get_system_interface(input_port_base));
const InputPortLocator id{&system, input_port_base.get_index()};
// Find if this input port is exported (connected to an input port of this
// containing diagram).
const auto external_it = input_port_map_.find(id);
const bool is_exported = (external_it != input_port_map_.end());
// Find if this input port is connected to an output port.
// TODO(sherm1) Fix this. Shouldn't have to search.
const auto upstream_it = connection_map_.find(id);
const bool is_connected = (upstream_it != connection_map_.end());
if (!(is_exported || is_connected))
return nullptr;
DRAKE_DEMAND(is_exported ^ is_connected);
if (is_exported) {
// The upstream source is an input to this whole Diagram; evaluate that
// input port and use the result as the value for this one.
const InputPortIndex i = external_it->second;
return this->EvalAbstractInput(diagram_context, i);
}
// The upstream source is an output port of one of this Diagram's child
// subsystems; evaluate it.
// TODO(david-german-tri): Add online algebraic loop detection here.
DRAKE_ASSERT(is_connected);
const OutputPortLocator& prerequisite = upstream_it->second;
return &this->EvalSubsystemOutputPort(diagram_context, prerequisite);
}
template <typename T>
std::string Diagram<T>::GetParentPathname() const {
return this->GetSystemPathname();
}
template <typename T>
const SystemBase& Diagram<T>::GetRootSystemBase() const {
const auto* parent_service = this->get_parent_service();
return parent_service ? parent_service->GetRootSystemBase() : *this;
}
template <typename T>
bool Diagram<T>::DiagramHasDirectFeedthrough(
int input_port, int output_port,
std::unordered_map<const System<T>*, std::multimap<int, int>>* memoize)
const {
DRAKE_ASSERT(input_port >= 0);
DRAKE_ASSERT(input_port < this->num_input_ports());
DRAKE_ASSERT(output_port >= 0);
DRAKE_ASSERT(output_port < this->num_output_ports());
DRAKE_ASSERT(memoize != nullptr);
const auto input_ids = GetInputPortLocators(InputPortIndex(input_port));
std::set<InputPortLocator> target_input_ids(input_ids.begin(),
input_ids.end());
// Search the graph for a direct-feedthrough connection from the output_port
// back to the input_port. Maintain a set of the output port identifiers
// that are known to have a direct-feedthrough path to the output_port.
std::set<OutputPortLocator> active_set;
active_set.insert(output_port_ids_[output_port]);
while (!active_set.empty()) {
const OutputPortLocator current_output_id = *active_set.begin();
const size_t removed_count = active_set.erase(current_output_id);
DRAKE_ASSERT(removed_count == 1);
const System<T>* const sys = current_output_id.first;
auto memoized_feedthroughs = memoize->find(sys);
if (memoized_feedthroughs == memoize->end()) {
bool inserted{};
std::tie(memoized_feedthroughs, inserted) =
memoize->emplace(sys, sys->GetDirectFeedthroughs());
DRAKE_ASSERT(inserted);
}
const std::multimap<int, int>& sys_feedthroughs =
memoized_feedthroughs->second;
for (const auto& [sys_input, sys_output] : sys_feedthroughs) {
if (sys_output == current_output_id.second) {
const InputPortLocator curr_input_id(sys, sys_input);
if (target_input_ids.contains(curr_input_id)) {
// We've found a direct-feedthrough path to the input_port.
return true;
} else {
// We've found an intermediate input port has a direct-feedthrough
// path to the output_port. Add the upstream output port (if there
// is one) to the active set.
auto it = connection_map_.find(curr_input_id);
if (it != connection_map_.end()) {
const OutputPortLocator& upstream_output = it->second;
active_set.insert(upstream_output);
}
}
}
}
}
// If there are no intermediate output ports with a direct-feedthrough path
// to the output_port, there is no direct feedthrough to it from the
// input_port.
return false;
}
template <typename T>
template <typename EventType>
std::unique_ptr<EventCollection<EventType>>
Diagram<T>::AllocateForcedEventCollection(
std::function<
std::unique_ptr<EventCollection<EventType>>(const System<T>*)>
allocator_func) const {
const int num_systems = num_subsystems();
auto ret = std::make_unique<DiagramEventCollection<EventType>>(num_systems);
for (SubsystemIndex i(0); i < num_systems; ++i) {
std::unique_ptr<EventCollection<EventType>> subevent_collection =
allocator_func(registered_systems_[i].get());
// The DiagramEventCollection should own these subevents- this function
// will not maintain its own references to them.
ret->set_and_own_subevent_collection(i, std::move(subevent_collection));
}
return ret;
}
template <typename T>
EventStatus Diagram<T>::DispatchPublishHandler(
const Context<T>& context,
const EventCollection<PublishEvent<T>>& event_info) const {
auto diagram_context = dynamic_cast<const DiagramContext<T>*>(&context);
DRAKE_DEMAND(diagram_context != nullptr);
const DiagramEventCollection<PublishEvent<T>>& info =
dynamic_cast<const DiagramEventCollection<PublishEvent<T>>&>(event_info);
EventStatus overall_status = EventStatus::DidNothing();
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
const EventCollection<PublishEvent<T>>& subinfo =
info.get_subevent_collection(i);
if (subinfo.HasEvents()) {
const Context<T>& subcontext = diagram_context->GetSubsystemContext(i);
const EventStatus per_subsystem_status =
registered_systems_[i]->Publish(subcontext, subinfo);
overall_status.KeepMoreSevere(per_subsystem_status);
// Unlike the discrete & unrestricted event policy, we don't stop handling
// publish events when one fails; we just report the first failure after
// all the publishes are done.
}
}
return overall_status;
}
template <typename T>
EventStatus Diagram<T>::DispatchDiscreteVariableUpdateHandler(
const Context<T>& context,
const EventCollection<DiscreteUpdateEvent<T>>& events,
DiscreteValues<T>* discrete_state) const {
auto diagram_context = dynamic_cast<const DiagramContext<T>*>(&context);
DRAKE_DEMAND(diagram_context != nullptr);
auto diagram_discrete =
dynamic_cast<DiagramDiscreteValues<T>*>(discrete_state);
DRAKE_DEMAND(diagram_discrete != nullptr);
const DiagramEventCollection<DiscreteUpdateEvent<T>>& diagram_events =
dynamic_cast<const DiagramEventCollection<DiscreteUpdateEvent<T>>&>(
events);
EventStatus overall_status = EventStatus::DidNothing();
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
const EventCollection<DiscreteUpdateEvent<T>>& subevents =
diagram_events.get_subevent_collection(i);
if (subevents.HasEvents()) {
const Context<T>& subcontext = diagram_context->GetSubsystemContext(i);
DiscreteValues<T>& subdiscrete =
diagram_discrete->get_mutable_subdiscrete(i);
const EventStatus per_subsystem_status =
registered_systems_[i]->CalcDiscreteVariableUpdate(
subcontext, subevents, &subdiscrete);
overall_status.KeepMoreSevere(per_subsystem_status);
if (overall_status.failed()) break; // Stop at the first disaster.
}
}
return overall_status;
}
template <typename T>
void Diagram<T>::DoApplyDiscreteVariableUpdate(
const EventCollection<DiscreteUpdateEvent<T>>& events,
DiscreteValues<T>* discrete_state, Context<T>* context) const {
// If this method is called, these are all Diagram objects.
const auto& diagram_events =
dynamic_cast<const DiagramEventCollection<DiscreteUpdateEvent<T>>&>(
events);
auto& diagram_discrete =
dynamic_cast<DiagramDiscreteValues<T>&>(*discrete_state);
auto& diagram_context = dynamic_cast<DiagramContext<T>&>(*context);
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
const EventCollection<DiscreteUpdateEvent<T>>& subevents =
diagram_events.get_subevent_collection(i);
if (subevents.HasEvents()) {
DiscreteValues<T>& subdiscrete =
diagram_discrete.get_mutable_subdiscrete(i);
Context<T>& subcontext = diagram_context.GetMutableSubsystemContext(i);
registered_systems_[i]->ApplyDiscreteVariableUpdate(
subevents, &subdiscrete, &subcontext);
}
}
}
template <typename T>
EventStatus Diagram<T>::DispatchUnrestrictedUpdateHandler(
const Context<T>& context,
const EventCollection<UnrestrictedUpdateEvent<T>>& events,
State<T>* state) const {
auto diagram_context = dynamic_cast<const DiagramContext<T>*>(&context);
DRAKE_DEMAND(diagram_context != nullptr);
auto diagram_state = dynamic_cast<DiagramState<T>*>(state);
DRAKE_DEMAND(diagram_state != nullptr);
const DiagramEventCollection<UnrestrictedUpdateEvent<T>>& diagram_events =
dynamic_cast<const DiagramEventCollection<UnrestrictedUpdateEvent<T>>&>(
events);
EventStatus overall_status = EventStatus::DidNothing();
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
const EventCollection<UnrestrictedUpdateEvent<T>>& subevents =
diagram_events.get_subevent_collection(i);
if (subevents.HasEvents()) {
const Context<T>& subcontext = diagram_context->GetSubsystemContext(i);
State<T>& substate = diagram_state->get_mutable_substate(i);
const EventStatus per_subsystem_status =
registered_systems_[i]->CalcUnrestrictedUpdate(subcontext, subevents,
&substate);
overall_status.KeepMoreSevere(per_subsystem_status);
if (overall_status.failed()) break; // Stop at the first disaster.
}
}
return overall_status;
}
template <typename T>
void Diagram<T>::DoApplyUnrestrictedUpdate(
const EventCollection<UnrestrictedUpdateEvent<T>>& events,
State<T>* state, Context<T>* context) const {
// If this method is called, these are all Diagram objects.
const auto& diagram_events =
dynamic_cast<const DiagramEventCollection<UnrestrictedUpdateEvent<T>>&>(
events);
auto& diagram_state = dynamic_cast<DiagramState<T>&>(*state);
auto& diagram_context = dynamic_cast<DiagramContext<T>&>(*context);
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
const EventCollection<UnrestrictedUpdateEvent<T>>& subevents =
diagram_events.get_subevent_collection(i);
if (subevents.HasEvents()) {
State<T>& substate = diagram_state.get_mutable_substate(i);
Context<T>& subcontext = diagram_context.GetMutableSubsystemContext(i);
registered_systems_[i]->ApplyUnrestrictedUpdate(subevents, &substate,
&subcontext);
}
}
}
template <typename T>
template <typename BaseStuff, typename DerivedStuff>
BaseStuff* Diagram<T>::GetSubsystemStuff(
const System<T>& target_system, BaseStuff* my_stuff,
std::function<BaseStuff*(const System<T>*, const System<T>&, BaseStuff*)>
recursive_getter,
std::function<BaseStuff&(DerivedStuff*, SubsystemIndex)> get_child_stuff)
const {
static_assert(
std::is_same_v<BaseStuff, typename std::remove_pointer_t<BaseStuff>>,
"BaseStuff cannot be a pointer");
static_assert(
std::is_same_v<DerivedStuff,
typename std::remove_pointer_t<DerivedStuff>>,
"DerivedStuff cannot be a pointer");
DRAKE_DEMAND(my_stuff != nullptr);
DRAKE_DEMAND(&target_system != this);
DerivedStuff& my_stuff_as_derived = dynamic_cast<DerivedStuff&>(*my_stuff);
SubsystemIndex index(0);
for (const auto& child : registered_systems_) {
BaseStuff& child_stuff = get_child_stuff(&my_stuff_as_derived, index);
BaseStuff* const target_stuff =
recursive_getter(child.get(), target_system, &child_stuff);
if (target_stuff != nullptr) {
return target_stuff;
}
++index;
}
return nullptr;
}
template <typename T>
template <typename NewType>
std::unique_ptr<typename Diagram<NewType>::Blueprint>
Diagram<T>::ConvertScalarType() const {
internal::OwnedSystems<NewType> new_systems;
// Recursively convert all the subsystems.
std::map<const System<T>*, const System<NewType>*> old_to_new_map;
for (const auto& old_system : registered_systems_) {
// Convert old_system to new_system using the old_system's converter.
std::unique_ptr<System<NewType>> new_system =
old_system->get_system_scalar_converter().
template Convert<NewType>(*old_system);
DRAKE_DEMAND(new_system != nullptr);
// Update our mapping and take ownership.
old_to_new_map[old_system.get()] = new_system.get();
new_systems.push_back(std::move(new_system));
}
// Set up the blueprint.
auto blueprint = std::make_unique<typename Diagram<NewType>::Blueprint>();
// Make all the inputs, preserving index assignments.
for (int k = 0; k < this->num_input_ports(); k++) {
const auto name = this->get_input_port(k).get_name();
for (const auto& id : GetInputPortLocators(InputPortIndex(k))) {
const System<NewType>* new_system = old_to_new_map[id.first];
const InputPortIndex port = id.second;
blueprint->input_port_ids.emplace_back(new_system, port);
blueprint->input_port_names.emplace_back(name);
}
}
// Make all the outputs.
for (const OutputPortLocator& id : output_port_ids_) {
const System<NewType>* new_system = old_to_new_map[id.first];
const OutputPortIndex port = id.second;
blueprint->output_port_ids.emplace_back(new_system, port);
}
for (OutputPortIndex i{0}; i < this->num_output_ports(); i++) {
blueprint->output_port_names.emplace_back(
this->get_output_port(i).get_name());
}
// Make all the connections.
for (const auto& edge : connection_map_) {
const InputPortLocator& old_dest = edge.first;
const System<NewType>* const dest_system = old_to_new_map[old_dest.first];
const InputPortIndex dest_port = old_dest.second;
const typename Diagram<NewType>::InputPortLocator new_dest{dest_system,
dest_port};
const OutputPortLocator& old_src = edge.second;
const System<NewType>* const src_system = old_to_new_map[old_src.first];
const OutputPortIndex src_port = old_src.second;
const typename Diagram<NewType>::OutputPortLocator new_src{src_system,
src_port};
blueprint->connection_map[new_dest] = new_src;
}
// Move the new systems into the blueprint.
blueprint->systems = std::move(new_systems);
return blueprint;
}
template <typename T>
std::map<PeriodicEventData, std::vector<const Event<T>*>,
PeriodicEventDataComparator>
Diagram<T>::DoMapPeriodicEventsByTiming(const Context<T>& context) const {
std::map<PeriodicEventData, std::vector<const Event<T>*>,
PeriodicEventDataComparator>
periodic_events_map;
for (int i = 0; i < num_subsystems(); ++i) {
const System<T>& sub_system = *registered_systems_[i];
const Context<T>& sub_context = GetSubsystemContext(sub_system, context);
auto sub_map = sub_system.MapPeriodicEventsByTiming(&sub_context);
for (const auto& sub_attr_events : sub_map) {
const auto& sub_vec = sub_attr_events.second;
auto& vec = periodic_events_map[sub_attr_events.first];
vec.insert(vec.end(), sub_vec.begin(), sub_vec.end());
}
}
return periodic_events_map;
}
// Strategy:
// For each subsystem, obtain its set of uniquely-timed periodic discrete
// updates (if any) in an EventCollection. The first of these sets the timing;
// all others must have the same timing. Once the full collection has been
// assembled, we can use CalcDiscreteVariableUpdate() to get the result.
// See the LeafSystem implementation of this virtual for clarification.
template <typename T>
void Diagram<T>::DoFindUniquePeriodicDiscreteUpdatesOrThrow(
const char* api_name, const Context<T>& context,
std::optional<PeriodicEventData>* timing,
EventCollection<DiscreteUpdateEvent<T>>* events) const {
auto& diagram_collection =
dynamic_cast<DiagramEventCollection<DiscreteUpdateEvent<T>>&>(*events);
for (int i = 0; i < num_subsystems(); ++i) {
const System<T>& sub_system = *registered_systems_[i];
const Context<T>& sub_context = GetSubsystemContext(sub_system, context);
EventCollection<DiscreteUpdateEvent<T>>& sub_collection =
diagram_collection.get_mutable_subevent_collection(i);
System<T>::FindUniquePeriodicDiscreteUpdatesOrThrow(
api_name, sub_system, sub_context, &*timing, &sub_collection);
}
}
template <typename T>
void Diagram<T>::DoGetPeriodicEvents(
const Context<T>& context,
CompositeEventCollection<T>* event_info) const {
auto diagram_context = dynamic_cast<const DiagramContext<T>*>(&context);
auto info = dynamic_cast<DiagramCompositeEventCollection<T>*>(event_info);
DRAKE_DEMAND(diagram_context != nullptr);
DRAKE_DEMAND(info != nullptr);
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
const Context<T>& subcontext = diagram_context->GetSubsystemContext(i);
CompositeEventCollection<T>& subinfo =
info->get_mutable_subevent_collection(i);
registered_systems_[i]->GetPeriodicEvents(subcontext, &subinfo);
}
}
template <typename T>
void Diagram<T>::DoGetPerStepEvents(
const Context<T>& context,
CompositeEventCollection<T>* event_info) const {
auto diagram_context = dynamic_cast<const DiagramContext<T>*>(&context);
auto info = dynamic_cast<DiagramCompositeEventCollection<T>*>(event_info);
DRAKE_DEMAND(diagram_context != nullptr);
DRAKE_DEMAND(info != nullptr);
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
const Context<T>& subcontext = diagram_context->GetSubsystemContext(i);
CompositeEventCollection<T>& subinfo =
info->get_mutable_subevent_collection(i);
registered_systems_[i]->GetPerStepEvents(subcontext, &subinfo);
}
}
template <typename T>
void Diagram<T>::DoGetInitializationEvents(
const Context<T>& context,
CompositeEventCollection<T>* event_info) const {
auto diagram_context = dynamic_cast<const DiagramContext<T>*>(&context);
auto info = dynamic_cast<DiagramCompositeEventCollection<T>*>(event_info);
DRAKE_DEMAND(diagram_context != nullptr);
DRAKE_DEMAND(info != nullptr);
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
const Context<T>& subcontext = diagram_context->GetSubsystemContext(i);
CompositeEventCollection<T>& subinfo =
info->get_mutable_subevent_collection(i);
registered_systems_[i]->GetInitializationEvents(subcontext, &subinfo);
}
}
template <typename T>
Diagram<T>::Diagram(std::unique_ptr<Blueprint> blueprint) : Diagram() {
Initialize(std::move(blueprint));
}
template <typename T>
void Diagram<T>::Initialize(std::unique_ptr<Blueprint> blueprint) {
// We must be given something to own.
DRAKE_DEMAND(!blueprint->systems.empty());
// We must not already own any subsystems.
DRAKE_DEMAND(registered_systems_.empty());
// Move the corresponding data from the blueprint into private member
// variables.
connection_map_ = std::move(blueprint->connection_map);
output_port_ids_ = std::move(blueprint->output_port_ids);
registered_systems_ = std::move(blueprint->systems);
// This cache entry just maintains temporary storage. It is only ever used
// by DoCalcNextUpdateTime(). Since this declaration of the cache entry
// invokes no invalidation support from the cache system, it is the
// responsibility of DoCalcNextUpdateTime() to ensure that no stale data is
// used.
event_times_buffer_cache_index_ =
this->DeclareCacheEntry(
"event_times_buffer", ValueProducer(
std::vector<T>(num_subsystems()),
&ValueProducer::NoopCalc),
{this->nothing_ticket()}).cache_index();
// Generate a map from the System pointer to its index in the registered
// order.
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
system_index_map_[registered_systems_[i].get()] = i;
SystemBase::set_parent_service(registered_systems_[i].get(), this);
}
// Generate constraints for the diagram from the constraints on the
// subsystems.
for (SubsystemIndex i(0); i < num_subsystems(); ++i) {
const auto sys = registered_systems_[i].get();
for (SystemConstraintIndex j(0); j < sys->num_constraints(); ++j) {
const auto c = &(sys->get_constraint(j));
ContextConstraintCalc<T> diagram_calc =
[this, sys, c](const Context<T>& context, VectorX<T>* value) {
c->Calc(this->GetSubsystemContext(*sys, context), value);
};
this->AddConstraint(std::make_unique<SystemConstraint<T>>(
this, diagram_calc, c->bounds(),
sys->get_name() + ":" + c->description()));
}
}
// Every system must appear exactly once.
DRAKE_DEMAND(registered_systems_.size() == system_index_map_.size());
// Every port named in the connection_map_ must actually exist.
DRAKE_ASSERT(PortsAreValid());
// Every subsystem must have a unique name.
DRAKE_THROW_UNLESS(NamesAreUniqueAndNonEmpty());
// Add the inputs to the Diagram topology, and check their invariants.
DRAKE_DEMAND(blueprint->input_port_ids.size() ==
blueprint->input_port_names.size());
std::vector<std::string>::iterator name_iter =
blueprint->input_port_names.begin();
for (const InputPortLocator& id : blueprint->input_port_ids) {
ExportOrConnectInput(id, *name_iter++);
}
DRAKE_DEMAND(output_port_ids_.size() ==
blueprint->output_port_names.size());
name_iter = blueprint->output_port_names.begin();
for (const OutputPortLocator& id : output_port_ids_) {
ExportOutput(id, *name_iter++);
}
// Identify the intersection of the subsystems' scalar conversion support.
// Remove all conversions that at least one subsystem did not support.
SystemScalarConverter& this_scalar_converter =
this->get_mutable_system_scalar_converter();
for (const auto& system : registered_systems_) {
this_scalar_converter.RemoveUnlessAlsoSupportedBy(
system->get_system_scalar_converter());
}
this->set_forced_publish_events(
AllocateForcedEventCollection<PublishEvent<T>>(
&System<T>::AllocateForcedPublishEventCollection));
this->set_forced_discrete_update_events(
AllocateForcedEventCollection<DiscreteUpdateEvent<T>>(
&System<T>::AllocateForcedDiscreteUpdateEventCollection));
this->set_forced_unrestricted_update_events(
AllocateForcedEventCollection<UnrestrictedUpdateEvent<T>>(
&System<T>::AllocateForcedUnrestrictedUpdateEventCollection));
// Total up all needed Context resources, and the size of the implicit time
// derivative residual. Note that we are depending on sub-Diagrams already to
// have been initialized so that their counts are already correct.
SystemBase::ContextSizes& sizes = this->get_mutable_context_sizes();
int residual_size = 0;
for (const auto& system : registered_systems_) {
sizes += SystemBase::get_context_sizes(*system);
residual_size += system->implicit_time_derivatives_residual_size();
}
this->set_implicit_time_derivatives_residual_size(residual_size);
}
template <typename T>
void Diagram<T>::ExportOrConnectInput(
const InputPortLocator& port, std::string name) {
const System<T>* const sys = port.first;
const int port_index = port.second;
// Fail quickly if this system is not part of the diagram.
GetSystemIndexOrAbort(sys);
if (this->HasInputPort(name)) {
input_port_map_[port] = this->GetInputPort(name).get_index();
} else {
// Add this port to our externally visible topology.
const auto& subsystem_input_port = sys->get_input_port(port_index);
const InputPort<T>& new_port = this->DeclareInputPort(
std::move(name), subsystem_input_port.get_data_type(),
subsystem_input_port.size(), subsystem_input_port.get_random_type());
input_port_map_[port] = new_port.get_index();
}
}
template <typename T>
void Diagram<T>::ExportOutput(const OutputPortLocator& port, std::string name) {
const System<T>* const sys = port.first;
const int port_index = port.second;
const auto& source_output_port = sys->get_output_port(port_index);
// TODO(sherm1) Use implicit_cast when available (from abseil).
auto diagram_port = internal::FrameworkFactory::Make<DiagramOutputPort<T>>(
this, // implicit_cast<const System<T>*>(this)
this, // implicit_cast<SystemBase*>(this)
this->get_system_id(),
std::move(name), OutputPortIndex(this->num_output_ports()),
this->assign_next_dependency_ticket(), &source_output_port,
GetSystemIndexOrAbort(&source_output_port.get_system()));
this->AddOutputPort(std::move(diagram_port));
}
template <typename T>
const AbstractValue& Diagram<T>::EvalSubsystemOutputPort(
const DiagramContext<T>& context, const OutputPortLocator& id) const {
const System<T>* const system = id.first;
const OutputPortIndex port_index(id.second);
const OutputPort<T>& port = system->get_output_port(port_index);
const SubsystemIndex i = GetSystemIndexOrAbort(system);
DRAKE_LOGGER_TRACE("Evaluating output for subsystem {}, port {}",
system->GetSystemPathname(), port_index);
const Context<T>& subsystem_context = context.GetSubsystemContext(i);
return port.template Eval<AbstractValue>(subsystem_context);
}
template <typename T>
typename DiagramContext<T>::InputPortIdentifier
Diagram<T>::ConvertToContextPortIdentifier(const InputPortLocator& locator)
const {
typename DiagramContext<T>::InputPortIdentifier identifier;
identifier.first = GetSystemIndexOrAbort(locator.first);
identifier.second = locator.second;
return identifier;
}
template <typename T>
typename DiagramContext<T>::OutputPortIdentifier
Diagram<T>::ConvertToContextPortIdentifier(const OutputPortLocator& locator)
const {
typename DiagramContext<T>::OutputPortIdentifier identifier;
identifier.first = GetSystemIndexOrAbort(locator.first);
identifier.second = locator.second;
return identifier;
}
template <typename T>
bool Diagram<T>::PortsAreValid() const {
for (const auto& entry : connection_map_) {
const InputPortLocator& dest = entry.first;
const OutputPortLocator& src = entry.second;
if (dest.second < 0 || dest.second >= dest.first->num_input_ports()) {
return false;
}
if (src.second < 0 || src.second >= src.first->num_output_ports()) {
return false;
}
}
return true;
}
template <typename T>
bool Diagram<T>::NamesAreUniqueAndNonEmpty() const {
string_unordered_set names;
for (const auto& system : registered_systems_) {
const std::string& name = system->get_name();
if (name.empty()) {
// This can only happen if someone blanks out the name *after* adding
// it to DiagramBuilder; if an empty name is given to DiagramBuilder,
// a default non-empty name is automatically assigned.
log()->error("Subsystem of type {} has no name",
NiceTypeName::Get(*system));
// We skip names.insert here, so that the return value will be false.
continue;
}
if (names.find(name) != names.end()) {
log()->error("Non-unique name \"{}\" for subsystem of type {}", name,
NiceTypeName::Get(*system));
}
names.insert(name);
}
return names.size() == registered_systems_.size();
}
template <typename T>
int Diagram<T>::num_subsystems() const {
return static_cast<int>(registered_systems_.size());
}
} // namespace systems
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::Diagram)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/value_producer.cc | #include "drake/systems/framework/value_producer.h"
#include <stdexcept>
#include <fmt/format.h>
#include "drake/common/nice_type_name.h"
namespace drake {
namespace systems {
ValueProducer::ValueProducer() = default;
ValueProducer::ValueProducer(
AllocateCallback allocate, CalcCallback calc)
: allocate_(std::move(allocate)), calc_(std::move(calc)) {
if (allocate_ == nullptr) {
throw std::logic_error(
"Cannot create a ValueProducer with a null AllocateCallback");
}
if (calc_ == nullptr) {
throw std::logic_error(
"Cannot create a ValueProducer with a null Calc");
}
}
ValueProducer::~ValueProducer() = default;
bool ValueProducer::is_valid() const {
return (allocate_ != nullptr) && (calc_ != nullptr);
}
void ValueProducer::NoopCalc(const ContextBase&, AbstractValue*) {}
std::unique_ptr<AbstractValue> ValueProducer::Allocate() const {
if (allocate_ == nullptr) {
throw std::logic_error(
"ValueProducer cannot invoke a null AllocateCallback");
}
return allocate_();
}
void ValueProducer::Calc(const ContextBase& context,
AbstractValue* output) const {
if (output == nullptr) {
throw std::logic_error(
"ValueProducer output was nullptr");
}
if (calc_ == nullptr) {
throw std::logic_error(
"ValueProducer cannot invoke a null CalcCallback");
}
return calc_(context, output);
}
void ValueProducer::ThrowBadNull() {
throw std::logic_error("ValueProducer was given a null callback pointer");
}
void ValueProducer::ThrowBadCast(const std::type_info& actual_type,
const std::type_info& desired_type) {
throw std::logic_error(fmt::format(
"ValueProducer cannot cast a {} to a {}",
NiceTypeName::Get(actual_type), NiceTypeName::Get(desired_type)));
}
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/state.h | #pragma once
#include <memory>
#include <utility>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_copyable.h"
#include "drake/systems/framework/abstract_values.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/continuous_state.h"
#include "drake/systems/framework/discrete_values.h"
namespace drake {
namespace systems {
/// %State is a container for all the data comprising the
/// complete state of a particular System at a particular moment. Any field in
/// %State may be empty if it is not applicable to the System in question.
/// A System may not maintain state in any place other than a %State object.
///
/// A %State `x` contains three types of state variables:
///
/// - Continuous state `xc`
/// - Discrete state `xd`
/// - Abstract state `xa`
///
/// @tparam_default_scalar
template <typename T>
class State {
public:
// State is not copyable or moveable.
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(State)
State();
virtual ~State();
// TODO(sherm1) Consider making set_{continuous,discrete,abstract}_state()
// functions private with attorney access only to make it impossible for
// users to attempt resizing State within an existing Context.
/// (Advanced) Defines the continuous state variables for this %State.
/// @warning Do not use this function to resize continuous state in a
/// %State that is owned by an existing Context.
void set_continuous_state(std::unique_ptr<ContinuousState<T>> xc) {
DRAKE_DEMAND(xc != nullptr);
continuous_state_ = std::move(xc);
}
const ContinuousState<T>& get_continuous_state() const {
DRAKE_ASSERT(continuous_state_ != nullptr);
return *continuous_state_.get();
}
ContinuousState<T>& get_mutable_continuous_state() {
DRAKE_ASSERT(continuous_state_ != nullptr);
return *continuous_state_.get();
}
/// (Advanced) Defines the discrete state variables for this %State.
/// @warning Do not use this function to resize discrete state in a
/// %State that is owned by an existing Context.
void set_discrete_state(std::unique_ptr<DiscreteValues<T>> xd) {
DRAKE_DEMAND(xd != nullptr);
discrete_state_ = std::move(xd);
}
const DiscreteValues<T>& get_discrete_state() const {
DRAKE_ASSERT(discrete_state_ != nullptr);
return *discrete_state_.get();
}
DiscreteValues<T>& get_mutable_discrete_state() {
DRAKE_ASSERT(discrete_state_ != nullptr);
return *discrete_state_.get();
}
const BasicVector<T>& get_discrete_state(int index) const {
const DiscreteValues<T>& xd = get_discrete_state();
return xd.get_vector(index);
}
BasicVector<T>& get_mutable_discrete_state(int index) {
DiscreteValues<T>& xd = get_mutable_discrete_state();
return xd.get_mutable_vector(index);
}
/// (Advanced) Defines the abstract state variables for this %State.
/// @warning Do not use this function to resize or change types of abstract
/// state variables in a %State that is owned by an existing Context.
void set_abstract_state(std::unique_ptr<AbstractValues> xa) {
DRAKE_DEMAND(xa != nullptr);
abstract_state_ = std::move(xa);
}
const AbstractValues& get_abstract_state() const {
DRAKE_ASSERT(abstract_state_ != nullptr);
return *abstract_state_.get();
}
/// Returns a mutable reference to the abstract component of the state,
/// which may be of size zero.
AbstractValues& get_mutable_abstract_state() {
DRAKE_ASSERT(abstract_state_ != nullptr);
return *abstract_state_.get();
}
/// Returns a const pointer to the abstract component of the
/// state at @p index. Asserts if @p index doesn't exist.
template <typename U>
const U& get_abstract_state(int index) const {
const AbstractValues& xa = get_abstract_state();
return xa.get_value(index).get_value<U>();
}
/// Returns a mutable pointer to element @p index of the abstract state.
/// Asserts if @p index doesn't exist.
template <typename U>
U& get_mutable_abstract_state(int index) {
AbstractValues& xa = get_mutable_abstract_state();
return xa.get_mutable_value(index).get_mutable_value<U>();
}
/// Initializes this state from a State<U>.
template <typename U>
void SetFrom(const State<U>& other) {
continuous_state_->SetFrom(other.get_continuous_state());
discrete_state_->SetFrom(other.get_discrete_state());
abstract_state_->SetFrom(other.get_abstract_state());
}
/// @name System compatibility
/// See @ref system_compatibility.
//@{
/// (Internal use only) Gets the id of the subsystem that created this state.
internal::SystemId get_system_id() const { return system_id_; }
/// (Internal use only) Records the id of the subsystem that created this
/// state.
void set_system_id(internal::SystemId id) {
system_id_ = id;
get_mutable_continuous_state().set_system_id(this->get_system_id());
get_mutable_discrete_state().set_system_id(this->get_system_id());
}
//@}
private:
std::unique_ptr<AbstractValues> abstract_state_;
std::unique_ptr<ContinuousState<T>> continuous_state_;
std::unique_ptr<DiscreteValues<T>> discrete_state_;
// Unique id of the subsystem that created this state.
internal::SystemId system_id_;
};
} // namespace systems
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::State)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/system_output.h | #pragma once
#include <memory>
#include <utility>
#include <vector>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/value.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/framework_common.h"
namespace drake {
namespace systems {
// Forward declare for friendship below. Only System<T> may ever create
// a SystemOutput<T>.
template <typename T> class System;
/** Conveniently stores a snapshot of the values of every output port of
a System. There is framework support for allocating the right types and filling
them in but otherwise this is not used internally. Note that there is never any
live connection between a SystemOutput object and the System whose output values
it has captured.
A `SystemOutput<T>` object can only be obtained using
`System<T>::AllocateOutput()` or by copying an existing %SystemOutput object.
@tparam_default_scalar
*/
template <typename T>
class SystemOutput {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(SystemOutput);
~SystemOutput() = default;
/** Returns the number of output ports specified for this %SystemOutput
during allocation. */
int num_ports() const { return static_cast<int>(port_values_.size()); }
// TODO(sherm1) All of these should return references. We don't need to
// support missing entries.
/** Returns the last-saved value of output port `index` as an AbstractValue.
This works for any output port regardless of it actual type. */
const AbstractValue* get_data(int index) const {
DRAKE_ASSERT(0 <= index && index < num_ports());
return port_values_[index].get();
}
/** Returns the last-saved value of output port `index` as a `BasicVector<T>`,
although the actual concrete type is preserved from the actual output port.
@throws std::exception if the port is not vector-valued. */
const BasicVector<T>* get_vector_data(int index) const {
DRAKE_ASSERT(0 <= index && index < num_ports());
return &port_values_[index]->template get_value<BasicVector<T>>();
}
/** (Advanced) Returns mutable access to an AbstractValue object that is
suitable for holding the value of output port `index` of the allocating
System. This works for any output port regardless of it actual type. Most
users should just call `System<T>::CalcOutputs()` to get all the output
port values at once. */
AbstractValue* GetMutableData(int index) {
DRAKE_ASSERT(0 <= index && index < num_ports());
return port_values_[index].get_mutable();
}
/** (Advanced) Returns mutable access to a `BasicVector<T>` object that is
suitable for holding the value of output port `index` of the allocating
System. The object's concrete type is preserved from the output port. Most
users should just call `System<T>::CalcOutputs()` to get all the output
port values at once.
@throws std::exception if the port is not vector-valued. */
BasicVector<T>* GetMutableVectorData(int index) {
DRAKE_ASSERT(0 <= index && index < num_ports());
return &port_values_[index]->template get_mutable_value<BasicVector<T>>();
}
/** (Internal) Gets the id of the System that created this output.
See @ref system_compatibility. */
internal::SystemId get_system_id() const { return system_id_; }
private:
friend class System<T>;
friend class SystemOutputTest;
SystemOutput() = default;
// Add a suitable object to hold values for the next output port.
void add_port(std::unique_ptr<AbstractValue> model_value) {
port_values_.emplace_back(std::move(model_value));
}
// Records the id of the subsystem that created this output.
// See @ref system_compatibility.
void set_system_id(internal::SystemId id) { system_id_ = id; }
std::vector<copyable_unique_ptr<AbstractValue>> port_values_;
// Unique id of the subsystem that created this output.
internal::SystemId system_id_;
};
} // namespace systems
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::SystemOutput)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/output_port.cc | #include "drake/systems/framework/output_port.h"
namespace drake::systems {
template<typename T>
void OutputPort<T>::CheckValidAllocation(const AbstractValue& proposed) const {
if (this->get_data_type() != kVectorValued)
return; // Nothing we can check for an abstract port.
const auto* const proposed_vec = proposed.maybe_get_value<BasicVector<T>>();
if (proposed_vec == nullptr) {
throw std::logic_error(
fmt::format("OutputPort::Allocate(): expected BasicVector output type "
"but got {} for {}.",
proposed.GetNiceTypeName(), GetFullDescription()));
}
const int proposed_size = proposed_vec->get_value().size();
if (proposed_size != this->size()) {
throw std::logic_error(
fmt::format("OutputPort::Allocate(): expected vector output type of "
"size {} but got a vector of size {} for {}.",
this->size(), proposed_size, GetFullDescription()));
}
}
} // namespace drake::systems
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::OutputPort)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/system_symbolic_inspector.cc | #include "drake/systems/framework/system_symbolic_inspector.h"
#include <sstream>
#include "drake/common/drake_assert.h"
#include "drake/common/symbolic/decompose.h"
namespace drake {
namespace systems {
using symbolic::Expression;
using symbolic::Formula;
SystemSymbolicInspector::SystemSymbolicInspector(
const System<symbolic::Expression>& system)
: context_(system.CreateDefaultContext()),
input_variables_(system.num_input_ports()),
continuous_state_variables_(context_->num_continuous_states()),
discrete_state_variables_(context_->num_discrete_state_groups()),
numeric_parameters_(context_->num_numeric_parameter_groups()),
output_(system.AllocateOutput()),
derivatives_(system.AllocateTimeDerivatives()),
discrete_updates_(system.AllocateDiscreteVariables()),
output_port_types_(system.num_output_ports()),
context_is_abstract_(IsAbstract(system, *context_)) {
// Stop analysis if the Context is in any way abstract, because we have no way
// to initialize the abstract elements.
if (context_is_abstract_) return;
// Time.
time_ = symbolic::Variable("t");
context_->SetTime(time_);
// Input.
InitializeVectorInputs(system);
// State.
InitializeContinuousState();
InitializeDiscreteState();
// Parameters.
InitializeParameters();
// Outputs.
for (int i = 0; i < system.num_output_ports(); ++i) {
const OutputPort<symbolic::Expression>& port = system.get_output_port(i);
output_port_types_[i] = port.get_data_type();
port.Calc(*context_, output_->GetMutableData(i));
}
// Time derivatives.
if (context_->num_continuous_states() > 0) {
system.CalcTimeDerivatives(*context_, derivatives_.get());
}
// Discrete updates.
if (context_->num_discrete_state_groups() > 0) {
system.CalcForcedDiscreteVariableUpdate(*context_, discrete_updates_.get());
}
// Constraints.
// TODO(russt): Maintain constraint descriptions.
for (int i = 0; i < system.num_constraints(); i++) {
const SystemConstraint<Expression>& constraint =
system.get_constraint(SystemConstraintIndex(i));
const double tol = 0.0;
constraints_.emplace(constraint.CheckSatisfied(*context_, tol));
}
}
void SystemSymbolicInspector::InitializeVectorInputs(
const System<symbolic::Expression>& system) {
// For each input vector i, set each element j to a symbolic expression whose
// value is the variable "ui_j".
for (int i = 0; i < system.num_input_ports(); ++i) {
DRAKE_ASSERT(system.get_input_port(i).get_data_type() == kVectorValued);
const int n = system.get_input_port(i).size();
input_variables_[i].resize(n);
auto value = system.AllocateInputVector(system.get_input_port(i));
for (int j = 0; j < n; ++j) {
std::ostringstream name;
name << "u" << i << "_" << j;
input_variables_[i][j] = symbolic::Variable(name.str());
value->SetAtIndex(j, input_variables_[i][j]);
}
system.get_input_port(i).FixValue(context_.get(), *value);
}
}
void SystemSymbolicInspector::InitializeContinuousState() {
// Set each element i in the continuous state to a symbolic expression whose
// value is the variable "xci".
VectorBase<symbolic::Expression>& xc =
context_->get_mutable_continuous_state_vector();
for (int i = 0; i < xc.size(); ++i) {
std::ostringstream name;
name << "xc" << i;
continuous_state_variables_[i] = symbolic::Variable(name.str());
xc[i] = continuous_state_variables_[i];
}
}
void SystemSymbolicInspector::InitializeDiscreteState() {
// For each discrete state vector i, set each element j to a symbolic
// expression whose value is the variable "xdi_j".
auto& xd = context_->get_mutable_discrete_state();
for (int i = 0; i < context_->num_discrete_state_groups(); ++i) {
auto& xdi = xd.get_mutable_vector(i);
discrete_state_variables_[i].resize(xdi.size());
for (int j = 0; j < xdi.size(); ++j) {
std::ostringstream name;
name << "xd" << i << "_" << j;
discrete_state_variables_[i][j] = symbolic::Variable(name.str());
xdi[j] = discrete_state_variables_[i][j];
}
}
}
void SystemSymbolicInspector::InitializeParameters() {
// For each numeric parameter vector i, set each element j to a symbolic
// expression whose value is the variable "pi_j".
for (int i = 0; i < context_->num_numeric_parameter_groups(); ++i) {
auto& pi = context_->get_mutable_numeric_parameter(i);
numeric_parameters_[i].resize(pi.size());
for (int j = 0; j < pi.size(); ++j) {
std::ostringstream name;
name << "p" << i << "_" << j;
numeric_parameters_[i][j] = symbolic::Variable(name.str());
pi[j] = numeric_parameters_[i][j];
}
}
}
bool SystemSymbolicInspector::IsAbstract(
const System<symbolic::Expression>& system,
const Context<symbolic::Expression>& context) {
// If any of the input ports are abstract, we cannot do sparsity analysis of
// this Context.
for (int i = 0; i < system.num_input_ports(); ++i) {
if (system.get_input_port(i).get_data_type() == kAbstractValued) {
return true;
}
}
// If there is any abstract state or parameters, we cannot do sparsity
// analysis of this Context.
if (context.num_abstract_states() > 0) {
return true;
}
if (context.num_abstract_parameters() > 0) {
return true;
}
return false;
}
bool SystemSymbolicInspector::IsConnectedInputToOutput(
int input_port_index, int output_port_index) const {
DRAKE_ASSERT(input_port_index >= 0 &&
input_port_index < static_cast<int>(input_variables_.size()));
DRAKE_ASSERT(output_port_index >= 0 &&
output_port_index < static_cast<int>(output_port_types_.size()));
// If the Context contains any abstract values, any input might be connected
// to any output.
if (context_is_abstract_) {
return true;
}
// If the given output port is abstract, we can't determine which inputs
// influenced it.
if (output_port_types_[output_port_index] == kAbstractValued) {
return true;
}
// Extract all the variables that appear in any element of the given
// output_port_index.
symbolic::Variables output_variables;
const BasicVector<symbolic::Expression>* output_exprs =
output_->get_vector_data(output_port_index);
for (int j = 0; j < output_exprs->size(); ++j) {
output_variables.insert(output_exprs->GetAtIndex(j).GetVariables());
}
// Check whether any of the variables in any of the input_variables_ are
// among the output_variables.
for (int j = 0; j < input_variables_[input_port_index].size(); ++j) {
if (output_variables.include((input_variables_[input_port_index])(j))) {
return true;
}
}
return false;
}
namespace {
// helper method for IsTimeInvariant.
bool is_time_invariant(const VectorX<symbolic::Expression>& expressions,
const symbolic::Variable& t) {
for (int i = 0; i < expressions.size(); ++i) {
const Expression& e{expressions(i)};
if (e.GetVariables().include(t)) {
return false;
}
}
return true;
}
} // namespace
bool SystemSymbolicInspector::IsTimeInvariant() const {
// Do not trust the parsing, so return the conservative answer.
if (context_is_abstract_) {
return false;
}
if (!is_time_invariant(derivatives_->CopyToVector(), time_)) {
return false;
}
for (int i = 0; i < discrete_updates_->num_groups(); ++i) {
if (!is_time_invariant(discrete_updates_->get_vector(i).get_value(),
time_)) {
return false;
}
}
for (int i = 0; i < output_->num_ports(); ++i) {
if (output_port_types_[i] == kAbstractValued) {
// Then I can't be sure. Return the conservative answer.
return false;
}
if (!is_time_invariant(output_->get_vector_data(i)->get_value(), time_)) {
return false;
}
}
return true;
}
bool SystemSymbolicInspector::HasAffineDynamics() const {
// If the Context contains any abstract values, then I can't trust my parsing.
if (context_is_abstract_) {
return false;
}
symbolic::Variables vars(continuous_state_variables_);
for (const auto& v : discrete_state_variables_) {
vars.insert(symbolic::Variables(v));
}
for (const auto& v : input_variables_) {
vars.insert(symbolic::Variables(v));
}
if (!IsAffine(derivatives_->CopyToVector(), vars)) {
return false;
}
for (int i = 0; i < discrete_updates_->num_groups(); ++i) {
if (!IsAffine(discrete_updates_->get_vector(i).get_value(), vars)) {
return false;
}
}
return true;
}
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/system_visitor.cc | #include "drake/systems/framework/system_visitor.h"
// This is an empty file to confirm that our header parses on its own.
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/system_base.h | #pragma once
#include <functional>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <typeinfo>
#include <utility>
#include <variant>
#include <vector>
#include "drake/common/drake_throw.h"
#include "drake/common/ssize.h"
#include "drake/common/unused.h"
#include "drake/systems/framework/abstract_value_cloner.h"
#include "drake/systems/framework/cache_entry.h"
#include "drake/systems/framework/framework_common.h"
#include "drake/systems/framework/input_port_base.h"
#include "drake/systems/framework/output_port_base.h"
#include "drake/systems/framework/value_producer.h"
namespace drake {
namespace systems {
#ifndef DRAKE_DOXYGEN_CXX
namespace internal {
// This class is defined later in this header file, below.
class DiagramSystemBaseAttorney;
} // namespace internal
#endif
/** Provides non-templatized functionality shared by the templatized System
classes.
Terminology: in general a Drake System is a tree structure composed of
"subsystems", which are themselves System objects. The corresponding Context is
a parallel tree structure composed of "subcontexts", which are themselves
Context objects. There is a one-to-one correspondence between subsystems and
subcontexts. Within a given System (Context), its child subsystems (subcontexts)
are indexed using a SubsystemIndex; there is no separate SubcontextIndex since
the numbering must be identical. */
class SystemBase : public internal::SystemMessageInterface {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SystemBase)
~SystemBase() override;
/** Sets the name of the system. Do not use the path delimiter character ':'
in the name. When creating a Diagram, names of sibling subsystems should be
unique. DiagramBuilder uses this method to assign a unique default name if
none is provided. */
// TODO(sherm1) Enforce reasonable naming policies.
void set_name(const std::string& name) { name_ = name; }
/** Returns the name last supplied to set_name(), if any. Diagrams built with
DiagramBuilder will always have a default name for every contained subsystem
for which no user-provided name is available. Systems created by copying with
a scalar type change have the same name as the source system. An empty string
is returned if no name has been set. */
// TODO(sherm1) This needs to be better distinguished from the human-readable
// name. Consider an api change like get_label() for this one, with the
// intent that the label could be used programmatically.
const std::string& get_name() const { return name_; }
/** Returns a name for this %System based on a stringification of its type
name and memory address. This is intended for use in diagnostic output
and should not be used for behavioral logic, because the stringification
of the type name may produce differing results across platforms and
because the address can vary from run to run. */
std::string GetMemoryObjectName() const;
/** Returns a human-readable name for this system, for use in messages and
logging. This will be the same as returned by get_name(), unless that would
be an empty string. In that case we return a non-unique placeholder name,
currently just "_" (a lone underscore). */
const std::string& GetSystemName() const final {
return name_.empty() ? internal::SystemMessageInterface::no_name() : name_;
}
/** Generates and returns a human-readable full path name of this subsystem,
for use in messages and logging. The name starts from the root System, with
"::" delimiters between parent and child subsystems, with the individual
subsystems represented by their names as returned by GetSystemName(). */
std::string GetSystemPathname() const final;
/** Returns the most-derived type of this concrete System object as a
human-readable string suitable for use in error messages. The format is as
generated by NiceTypeName and will include namespace qualification if
present.
@see NiceTypeName for more specifics. */
std::string GetSystemType() const final { return NiceTypeName::Get(*this); }
/** Returns a Context suitable for use with this System. Context resources
are allocated based on resource requests that were made during System
construction. */
std::unique_ptr<ContextBase> AllocateContext() const {
// Get a concrete Context of the right type, allocate internal resources
// like parameters, state, and cache entries, and set up intra- and
// inter-subcontext dependencies.
std::unique_ptr<ContextBase> context = DoAllocateContext();
// We depend on derived classes to call our InitializeContextBase() method
// after allocating the appropriate concrete Context.
DRAKE_DEMAND(
internal::SystemBaseContextBaseAttorney::is_context_base_initialized(
*context));
return context;
}
//----------------------------------------------------------------------------
/** @name Graphviz methods */
//@{
/** Returns a Graphviz string describing this %System. To render the string,
use the <a href="http://www.graphviz.org/">Graphviz</a> tool, ``dot``.
Notes about the display conventions:
- The nodes of the graph are systems, and the solid edges are connections
between system input and output ports.
- The class name of a %System is shown in <b>Bold</b> atop the node.
- Under the class name, if a %System has been given a name via set_name(),
it will be displayed as `name=...`.
- Systems can elect to display additional properties besides their name;
see GraphvizFragmentParams::header_lines for implementation details.
- A Diagram's input ports are shown with a
<span style="border:2px solid blue;border-radius:4px">blue border</span>
and output ports are shown with a
<span style="border:2px solid green;border-radius:4px">green border</span>.
- Zero-sized ports are <span style="color:grey">greyed out</span>.
- Deprecated ports are <strike>struck through</strike> and flagged with a
headstone emoji (🪦) after their name.
<!-- TODO(jwnimmer-tri) Add rendering of network connections.
- Connections other than input-output ports (e.g., network message passing)
are shown with dashed lines.
-->
@param max_depth Sets a limit to the depth of nested diagrams to visualize.
Use zero to render a diagram as a single system block.
@param options Arbitrary strings to request alterations to the output. Options
that are unknown will be silently skipped. These options are often bespoke
flags that are only understood by particular systems, but Drake has one
built-in flag that is generally applicable: `"split"`. When set to `"I/O"`,
the system will be added as two nodes with all inputs on one node and all
outputs on the other; this is useful for systems that might otherwise cause
problematic visual cycles.
Options are applied only to this immediate system; they are not inherited by
the subsystems of a %Diagram. To specify an option for a %Diagram's subsystem,
prefix the option name with the subsystem's path, e.g., use
`"plant/split"="I/O"` to set the `"split"` option on the subsystem named
`"plant"`. */
std::string GetGraphvizString(
std::optional<int> max_depth = {},
const std::map<std::string, std::string>& options = {}) const;
/** (Advanced) The return type of GetGraphvizFragment(). */
struct GraphvizFragment {
/** The Graphviz IDs for this %System's input ports, to be used for adding
Graphviz edges. The i'th element is the ID for `get_input_port(i)`. For a
typical LeafSystem these will look like "s123:u0", "s123:u1", … but for
diagrams and other special cases they might vary. */
std::vector<std::string> input_ports;
/** The Graphviz IDs for this %System's output ports, to be used for adding
Graphviz edges. The i'th element is the ID for `get_output_port(i)`. For a
typical LeafSystem these will look like "s123:y0", "s123:y1", … but for
diagrams and other special cases they might vary. */
std::vector<std::string> output_ports;
/** The Graphviz content for this %System. The fragments must be a valid
Graphviz figure when concatenated and then wrapped in a `digraph { … }` or
`subgraph { … }` stanza. During concatenation, no extra newlines or any
other kind of whitespace should be inserted. (This is a list of strings,
rather than a single string, to avoid redundant string concatenation until
the last moment when we return the final GetGraphvizString().) */
std::vector<std::string> fragments;
};
/** (Advanced) Like GetGraphvizString() but does not wrap the string in a
`digraph { … }`. This is useful when merging the fragment into another
graph, and is how %Diagram obtains the Graphviz content for its subsystems.
The parameters are identical to GetGraphvizString(). The return value contains
additional metadata beyond the Graphviz content, to better support merging. */
GraphvizFragment GetGraphvizFragment(
std::optional<int> max_depth = {},
const std::map<std::string, std::string>& options = {}) const;
//@}
/** (Advanced) The arguments to the protected method DoGetGraphvizFragment().
This struct typically is only used by subclasses of LeafSystem that need to
customize their Graphviz representation. These parameters constitute a polite
request; a user's %System's implementation of DoGetGraphvizFragment() is not
strictly required to honor any of these parameters, but generally should
attempt to honor as many as possible. */
struct GraphvizFragmentParams {
/** As per GetGraphvizString(). */
int max_depth{};
/** As per GetGraphvizString(). */
std::map<std::string, std::string> options;
/** The Graphviz ID to use for this node. */
std::string node_id;
/** The header line(s) to use for this Graphviz node's table. The strings in
`header_lines` should not contain newlines; those are added automatically,
along with `<BR/>` breaks between lines. */
std::vector<std::string> header_lines;
};
//----------------------------------------------------------------------------
/** @name Input port evaluation (deprecated)
These _deprecated_ methods provide scalar type-independent evaluation of a
System input port in a particular Context. Instead of these, prefer to use
InputPort::Eval(), acquiring the port with `get_input_port(port_index)`.
If necessary, the methods here first cause the port's value
to become up to date, then they return a reference to the now-up-to-date value
in the given Context.
Specified preconditions for these methods operate as follows: The
preconditions will be checked in Debug builds but some or all might not be
checked in Release builds for performance reasons. If we do check, and a
precondition is violated, an std::exception will be thrown with a helpful
message.
@see System::get_input_port(), InputPort::Eval() for scalar type-specific
input port access. */
//@{
// TODO(jwnimmer-tri) Deprecate me.
/** Returns the value of the input port with the given `port_index` as an
AbstractValue, which is permitted for ports of any type. Causes the value to
become up to date first if necessary, delegating to our parent Diagram.
Returns a pointer to the port's value, or nullptr if the port is not
connected. If you know the actual type, use one of the more-specific
signatures.
@pre `port_index` selects an existing input port of this System.
@see InputPort::Eval() (preferred) */
const AbstractValue* EvalAbstractInput(const ContextBase& context,
int port_index) const {
ValidateContext(context);
if (port_index < 0)
ThrowNegativePortIndex(__func__, port_index);
const InputPortIndex port(port_index);
return EvalAbstractInputImpl(__func__, context, port);
}
// TODO(jwnimmer-tri) Deprecate me.
/** Returns the value of an abstract-valued input port with the given
`port_index` as a value of known type `V`. Causes the value to become
up to date first if necessary. See EvalAbstractInput() for
more information.
The result is returned as a pointer to the input port's value of type `V`,
or nullptr if the port is not connected.
@pre `port_index` selects an existing input port of this System.
@pre the port's value must be retrievable from the stored abstract value
using `AbstractValue::get_value<V>`.
@see InputPort::Eval() (preferred)
@tparam V The type of data expected. */
template <typename V>
const V* EvalInputValue(const ContextBase& context, int port_index) const {
ValidateContext(context);
if (port_index < 0)
ThrowNegativePortIndex(__func__, port_index);
const InputPortIndex port(port_index);
const AbstractValue* const abstract_value =
EvalAbstractInputImpl(__func__, context, port);
if (abstract_value == nullptr)
return nullptr; // An unconnected port.
// We have a value, is it a V?
const V* const value = abstract_value->maybe_get_value<V>();
if (value == nullptr) {
ThrowInputPortHasWrongType(__func__, port, NiceTypeName::Get<V>(),
abstract_value->GetNiceTypeName());
}
return value;
}
//@}
/** Returns the number of input ports currently allocated in this System.
These are indexed from 0 to %num_input_ports()-1. */
int num_input_ports() const {
return ssize(input_ports_);
}
/** Returns the number of output ports currently allocated in this System.
These are indexed from 0 to %num_output_ports()-1. */
int num_output_ports() const {
return ssize(output_ports_);
}
/** Returns a reference to an InputPort given its `port_index`.
@pre `port_index` selects an existing input port of this System. */
const InputPortBase& get_input_port_base(InputPortIndex port_index) const {
return GetInputPortBaseOrThrow(__func__, port_index,
/* warn_deprecated = */ true);
}
/** Returns a reference to an OutputPort given its `port_index`.
@pre `port_index` selects an existing output port of this System. */
const OutputPortBase& get_output_port_base(OutputPortIndex port_index) const {
return GetOutputPortBaseOrThrow(__func__, port_index,
/* warn_deprecated = */ true);
}
/** Returns the total dimension of all of the vector-valued input ports (as if
they were muxed). */
int num_total_inputs() const {
int count = 0;
for (const auto& in : input_ports_) count += in->size();
return count;
}
/** Returns the total dimension of all of the vector-valued output ports (as
if they were muxed). */
int num_total_outputs() const {
int count = 0;
for (const auto& out : output_ports_) count += out->size();
return count;
}
/** Reports all direct feedthroughs from input ports to output ports. For
a system with m input ports: `I = i₀, i₁, ..., iₘ₋₁`, and n output ports,
`O = o₀, o₁, ..., oₙ₋₁`, the return map will contain pairs (u, v) such that
- 0 ≤ u < m,
- 0 ≤ v < n,
- and there _might_ be a direct feedthrough from input iᵤ to each output oᵥ.
See @ref DeclareLeafOutputPort_feedthrough "DeclareLeafOutputPort"
documentation for how leaf systems can report their feedthrough.
*/
virtual std::multimap<int, int> GetDirectFeedthroughs() const = 0;
/** Returns the number nc of cache entries currently allocated in this System.
These are indexed from 0 to nc-1. */
int num_cache_entries() const {
return ssize(cache_entries_);
}
/** Returns a reference to a CacheEntry given its `index`. */
const CacheEntry& get_cache_entry(CacheIndex index) const {
DRAKE_ASSERT(0 <= index && index < num_cache_entries());
return *cache_entries_[index];
}
/** (Advanced) Returns a mutable reference to a CacheEntry given its `index`.
Note that you do not need mutable access to a CacheEntry to modify its value
in a Context, so most users should not use this method. */
CacheEntry& get_mutable_cache_entry(CacheIndex index) {
DRAKE_ASSERT(0 <= index && index < num_cache_entries());
return *cache_entries_[index];
}
//============================================================================
/** @name Dependency tickets
@anchor DependencyTicket_documentation
Use these tickets to declare well-known sources as prerequisites of a
downstream computation such as an output port, derivative, update, or cache
entry. The ticket numbers for the built-in sources are the same for all
systems. For time and accuracy they refer to the same global resource;
otherwise they refer to the specified sources within the referencing system.
A dependency ticket for a more specific resource (a particular input or
output port, a discrete variable group, abstract state variable, a parameter,
or a cache entry) is allocated and stored with the resource when it is
declared. Usually the tickets are obtained directly from the resource but
you can recover them with methods here knowing only the resource index. */
//@{
// The DependencyTrackers associated with these tickets are allocated
// in ContextBase::CreateBuiltInTrackers() and the implementation there must
// be kept up to date with the API contracts here.
// The ticket methods are promoted in the System<T> class so that users can
// invoke them in their constructors without prefixing with this->. If you
// add, remove, rename, or reorder any of these be sure to update the
// promotions in system.h.
// Keep the order here the same as they are defined in the internal enum
// BuiltInTicketNumbers, with the "particular resource" indexed methods
// inserted prior to the corresponding built-in "all such resources" ticket.
/** Returns a ticket indicating that a computation does not depend on *any*
source value; that is, it is a constant. If this appears in a prerequisite
list, it must be the only entry. */
static DependencyTicket nothing_ticket() {
return DependencyTicket(internal::kNothingTicket);
}
/** Returns a ticket indicating dependence on time. This is the same ticket
for all systems and refers to the same time value. */
static DependencyTicket time_ticket() {
return DependencyTicket(internal::kTimeTicket);
}
/** Returns a ticket indicating dependence on the accuracy setting in the
Context. This is the same ticket for all systems and refers to the same
accuracy value. */
static DependencyTicket accuracy_ticket() {
return DependencyTicket(internal::kAccuracyTicket);
}
/** Returns a ticket indicating that a computation depends on configuration
state variables q. There is no ticket representing just one of the state
variables qᵢ. */
static DependencyTicket q_ticket() {
return DependencyTicket(internal::kQTicket);
}
/** Returns a ticket indicating dependence on velocity state variables v. This
does _not_ also indicate a dependence on configuration variables q -- you must
list that explicitly or use kinematics_ticket() instead. There is no ticket
representing just one of the state variables vᵢ. */
static DependencyTicket v_ticket() {
return DependencyTicket(internal::kVTicket);
}
/** Returns a ticket indicating dependence on any or all of the miscellaneous
continuous state variables z. There is no ticket representing just one of
the state variables zᵢ. */
static DependencyTicket z_ticket() {
return DependencyTicket(internal::kZTicket);
}
/** Returns a ticket indicating dependence on _all_ of the continuous
state variables q, v, or z. */
static DependencyTicket xc_ticket() {
return DependencyTicket(internal::kXcTicket);
}
/** Returns a ticket indicating dependence on a particular discrete state
variable xdᵢ (may be a vector). (We sometimes refer to this as a "discrete
variable group".)
@see xd_ticket() to obtain a ticket for _all_ discrete variables. */
DependencyTicket discrete_state_ticket(DiscreteStateIndex index) const {
return discrete_state_tracker_info(index).ticket;
}
/** Returns a ticket indicating dependence on all of the numerical
discrete state variables, in any discrete variable group.
@see discrete_state_ticket() to obtain a ticket for just one discrete
state variable. */
static DependencyTicket xd_ticket() {
return DependencyTicket(internal::kXdTicket);
}
/** Returns a ticket indicating dependence on a particular abstract state
variable xaᵢ.
@see xa_ticket() to obtain a ticket for _all_ abstract variables. */
DependencyTicket abstract_state_ticket(AbstractStateIndex index) const {
return abstract_state_tracker_info(index).ticket;
}
/** Returns a ticket indicating dependence on all of the abstract
state variables in the current Context.
@see abstract_state_ticket() to obtain a ticket for just one abstract
state variable. */
static DependencyTicket xa_ticket() {
return DependencyTicket(internal::kXaTicket);
}
/** Returns a ticket indicating dependence on _all_ state variables x in this
system, including continuous variables xc, discrete (numeric) variables xd,
and abstract state variables xa. This does not imply dependence on time,
accuracy, parameters, or inputs; those must be specified separately. If you
mean to express dependence on all possible value sources, use
all_sources_ticket() instead. */
static DependencyTicket all_state_ticket() {
return DependencyTicket(internal::kXTicket);
}
/** Returns a ticket indicating dependence on a particular numeric parameter
pnᵢ (may be a vector).
@see pn_ticket() to obtain a ticket for _all_ numeric parameters. */
DependencyTicket numeric_parameter_ticket(NumericParameterIndex index) const {
return numeric_parameter_tracker_info(index).ticket;
}
/** Returns a ticket indicating dependence on all of the numerical
parameters in the current Context.
@see numeric_parameter_ticket() to obtain a ticket for just one numeric
parameter. */
static DependencyTicket pn_ticket() {
return DependencyTicket(internal::kPnTicket);
}
/** Returns a ticket indicating dependence on a particular abstract
parameter paᵢ.
@see pa_ticket() to obtain a ticket for _all_ abstract parameters. */
DependencyTicket abstract_parameter_ticket(
AbstractParameterIndex index) const {
return abstract_parameter_tracker_info(index).ticket;
}
/** Returns a ticket indicating dependence on all of the abstract
parameters pa in the current Context.
@see abstract_parameter_ticket() to obtain a ticket for just one abstract
parameter. */
static DependencyTicket pa_ticket() {
return DependencyTicket(internal::kPaTicket);
}
/** Returns a ticket indicating dependence on _all_ parameters p in this
system, including numeric parameters pn, and abstract parameters pa. */
static DependencyTicket all_parameters_ticket() {
return DependencyTicket(internal::kAllParametersTicket);
}
/** Returns a ticket indicating dependence on input port uᵢ indicated
by `index`.
@pre `index` selects an existing input port of this System. */
DependencyTicket input_port_ticket(InputPortIndex index) const {
DRAKE_DEMAND(0 <= index && index < num_input_ports());
if (input_ports_[index]->get_deprecation().has_value())
WarnPortDeprecation(/* is_input = */ true, index);
return input_ports_[index]->ticket();
}
/** Returns a ticket indicating dependence on _all_ input ports u of this
system.
@see input_port_ticket() to obtain a ticket for just one input port. */
static DependencyTicket all_input_ports_ticket() {
return DependencyTicket(internal::kAllInputPortsTicket);
}
/** Returns a ticket indicating dependence on every possible independent
source value _except_ input ports. This can be helpful in avoiding the
incorrect appearance of algebraic loops in a Diagram (those always involve
apparent input port dependencies). For an output port, use this ticket plus
tickets for just the input ports on which the output computation _actually_
depends. The sources included in this ticket are: time, accuracy, state,
and parameters. Note that dependencies on cache entries are _not_ included
here. Usually that won't matter since cache entries typically depend on at
least one of time, accuracy, state, or parameters so will be invalidated for
the same reason the current computation is. However, for a computation that
depends on a cache entry that depends only on input ports, be sure that
you have included those input ports in the dependency list, or include a
direct dependency on the cache entry.
@see input_port_ticket() to obtain a ticket for an input port.
@see cache_entry_ticket() to obtain a ticket for a cache entry.
@see all_sources_ticket() to also include all input ports as dependencies. */
static DependencyTicket all_sources_except_input_ports_ticket() {
return DependencyTicket(internal::kAllSourcesExceptInputPortsTicket);
}
/** Returns a ticket indicating dependence on every possible independent
source value, including time, accuracy, state, input ports, and parameters
(but not cache entries). This is the default dependency for computations that
have not specified anything more refined. It is equivalent to the set
`{all_sources_except_input_ports_ticket(), all_input_ports_ticket()}`.
@see cache_entry_ticket() to obtain a ticket for a cache entry. */
static DependencyTicket all_sources_ticket() {
return DependencyTicket(internal::kAllSourcesTicket);
}
/** Returns a ticket indicating dependence on the cache entry indicated
by `index`. Note that cache entries are _not_ included in the `all_sources`
ticket so must be listed separately.
@pre `index` selects an existing cache entry in this System. */
DependencyTicket cache_entry_ticket(CacheIndex index) const {
DRAKE_DEMAND(0 <= index && index < num_cache_entries());
return cache_entries_[index]->ticket();
}
/** Returns a ticket indicating dependence on all source values that may
affect configuration-dependent computations. In particular, this category
_does not_ include time, generalized velocities v, miscellaneous continuous
state variables z, or input ports. Generalized coordinates q are included, as
well as any discrete state variables that have been declared as configuration
variables, and configuration-affecting parameters. Finally we assume that
the accuracy setting may affect some configuration-dependent computations.
Examples: a parameter that affects length may change the computation of an
end-effector location. A change in accuracy requirement may require
recomputation of an iterative approximation of contact forces.
@see kinematics_ticket()
@note Currently there is no way to declare specific variables and parameters
to be configuration-affecting so we include all state variables and
parameters except for state variables v and z. */
// TODO(sherm1) Remove the above note once #9171 is resolved.
// The configuration_tracker implementation in ContextBase must be kept
// up to date with the above API contract.
static DependencyTicket configuration_ticket() {
return DependencyTicket(internal::kConfigurationTicket);
}
/** Returns a ticket indicating dependence on all source values that may
affect configuration- or velocity-dependent computations. This ticket depends
on the configuration_ticket defined above, and adds in velocity-affecting
source values. This _does not_ include time or input ports.
@see configuration_ticket()
@note Currently there is no way to declare specific variables and parameters
to be configuration- or velocity-affecting so we include all state variables
and parameters except for state variables z. */
// TODO(sherm1) Remove the above note once #9171 is resolved.
static DependencyTicket kinematics_ticket() {
return DependencyTicket(internal::kKinematicsTicket);
}
/** Returns a ticket for the cache entry that holds time derivatives of
the continuous variables.
@see EvalTimeDerivatives() */
static DependencyTicket xcdot_ticket() {
return DependencyTicket(internal::kXcdotTicket);
}
/** Returns a ticket for the cache entry that holds the potential energy
calculation.
@see System::EvalPotentialEnergy() */
static DependencyTicket pe_ticket() {
return DependencyTicket(internal::kPeTicket);
}
/** Returns a ticket for the cache entry that holds the kinetic energy
calculation.
@see System::EvalKineticEnergy() */
static DependencyTicket ke_ticket() {
return DependencyTicket(internal::kKeTicket);
}
/** Returns a ticket for the cache entry that holds the conservative power
calculation.
@see System::EvalConservativePower() */
static DependencyTicket pc_ticket() {
return DependencyTicket(internal::kPcTicket);
}
/** Returns a ticket for the cache entry that holds the non-conservative
power calculation.
@see System::EvalNonConservativePower() */
static DependencyTicket pnc_ticket() {
return DependencyTicket(internal::kPncTicket);
}
/** (Internal use only) Returns a ticket for the cache entry that holds the
unique periodic discrete update computation.
@see System::EvalUniquePeriodicDiscreteUpdate() */
static DependencyTicket xd_unique_periodic_update_ticket() {
return DependencyTicket(internal::kXdUniquePeriodicUpdateTicket);
}
/** (Internal use only) Returns a ticket indicating dependence on the output
port indicated by `index`. No user-definable quantities in a system can
meaningfully depend on that system's own output ports.
@pre `index` selects an existing output port of this System. */
DependencyTicket output_port_ticket(OutputPortIndex index) const {
DRAKE_DEMAND(0 <= index && index < num_output_ports());
return output_ports_[index]->ticket();
}
//@}
/** Returns the number of declared continuous state variables. */
int num_continuous_states() const {
return context_sizes_.num_generalized_positions +
context_sizes_.num_generalized_velocities +
context_sizes_.num_misc_continuous_states;
}
/** Returns the number of declared discrete state groups (each group is
a vector-valued discrete state variable). */
int num_discrete_state_groups() const {
return context_sizes_.num_discrete_state_groups;
}
/** Returns the number of declared abstract state variables. */
int num_abstract_states() const {
return context_sizes_.num_abstract_states;
}
/** Returns the number of declared numeric parameters (each of these is
a vector-valued parameter). */
int num_numeric_parameter_groups() const {
return context_sizes_.num_numeric_parameter_groups;
}
/** Returns the number of declared abstract parameters. */
int num_abstract_parameters() const {
return context_sizes_.num_abstract_parameters;
}
/** Returns the size of the implicit time derivatives residual vector.
By default this is the same as num_continuous_states() but a LeafSystem
can change it during construction via
LeafSystem::DeclareImplicitTimeDerivativesResidualSize(). */
int implicit_time_derivatives_residual_size() const {
return implicit_time_derivatives_residual_size_.has_value()
? *implicit_time_derivatives_residual_size_
: num_continuous_states();
}
// Note that it is extremely unlikely that a Context will have an invalid
// system id because it is near impossible for a user to create one. We'll
// just assume it's valid as a precondition on the ValidateContext() methods.
// In Debug builds this will be reported as an error but otherwise a
// readable but imperfect "Not created for this System" message will issue
// if there is no id.
// @pre both `context` and `this` have valid System Ids.
/** Checks whether the given context was created for this system.
@note This method is sufficiently fast for performance sensitive code.
@throws std::exception if the System Ids don't match. */
void ValidateContext(const ContextBase& context) const final {
if (context.get_system_id() != system_id_) {
ThrowValidateContextMismatch(context);
}
}
// @pre if `context` is non-null, then both `context` and `this` have valid
// System Ids.
/** Checks whether the given context was created for this system.
@note This method is sufficiently fast for performance sensitive code.
@throws std::exception if the System Ids don't match.
@throws std::exception if `context` is null.
@exclude_from_pydrake_mkdoc{This overload is not bound.} */
void ValidateContext(const ContextBase* context) const {
DRAKE_THROW_UNLESS(context != nullptr);
ValidateContext(*context);
}
// In contrast to Contexts it is easier to create some System-related objects
// without assigning them a valid system id. So for checking arbitrary object
// types we'll permit the object to have an invalid system id. (We still
// require that this SystemBase has a valid system id.)
// @pre `this` System has a valid system id.
/** Checks whether the given object was created for this system.
@note This method is sufficiently fast for performance sensitive code.
@throws std::exception if the System Ids don't match or if `object` doesn't
have an associated System Id.
@throws std::exception if the argument type is a pointer and it is null. */
template <class Clazz>
void ValidateCreatedForThisSystem(const Clazz& object) const {
const internal::SystemId id = [&]() {
if constexpr (std::is_pointer_v<Clazz>) {
DRAKE_THROW_UNLESS(object != nullptr);
return object->get_system_id();
} else {
return object.get_system_id();
}
}();
if (!id.is_same_as_valid_id(system_id_))
ThrowNotCreatedForThisSystem(object, id);
}
protected:
friend class internal::DiagramSystemBaseAttorney;
/** (Internal use only). */
SystemBase() = default;
//============================================================================
/** @name Declare cache entries
@anchor DeclareCacheEntry_documentation
Methods in this section are used by derived classes to declare cache entries
for their own internal computations. (Other cache entries are provided
automatically for well-known computations such as output ports and time
derivatives.) Cache entries may contain values of any type, however the type
for any particular cache entry is fixed after first allocation. Every cache
entry must have an _allocator_ function `Allocate()` and a _calculator_
function `Calc()`. `Allocate()` returns an object suitable for holding a value
of the cache entry. `Calc()` uses the contents of a given Context to produce
the cache entry's value, which is placed in an object of the type returned by
`Allocate()`.
<h4>Prerequisites</h4>
Correct runtime caching behavior depends critically on understanding the
dependencies of the cache entry's `Calc()` function (we call those
"prerequisites"). If none of the prerequisites has changed since the last
time `Calc()` was invoked to set the cache entry's value, then we don't need
to perform a potentially expensive recalculation. On the other hand, if any
of the prerequisites has changed then the current value is invalid and must
not be used without first recomputing.
Currently it is not possible for Drake to infer prerequisites accurately and
automatically from inspection of the `Calc()` implementation. Therefore,
if you don't say otherwise, Drake will assume `Calc()` is dependent
on all value sources in the Context, including time, state, input ports,
parameters, and accuracy. That means the cache entry's value will be
considered invalid if _any_ of those sources has changed since the last time
the value was calculated. That is safe, but can result in more computation
than necessary. If you know that your `Calc()` method has fewer prerequisites,
you may say so by providing an explicit list in the `prerequisites_of_calc`
parameter. Every possible prerequisite has a DependencyTicket ("ticket"), and
the list should consist of tickets. For example, if your calculator depends
only on time (e.g. `Calc(context)` is `sin(context.get_time())`) then you
would specify `prerequisites_of_calc={time_ticket()}` here. See
@ref DependencyTicket_documentation "Dependency tickets" for a list of the
possible tickets and what they mean.
@warning It is critical that the prerequisite list you supply be accurate, or
at least conservative, for correct functioning of the caching system. Drake
cannot currently detect that a `Calc()` function accesses an undeclared
prerequisite. Even assuming you have correctly listed the prerequisites, you
should include a prominent comment in every `Calc()` implementation noting
that if the implementation is changed then the prerequisite list must be
updated correspondingly.
A technique you can use to ensure that prerequisites have been properly
specified is to make use of the Context's
@ref drake::systems::ContextBase::DisableCaching "DisableCaching()"
method, which causes cache values to be recalculated unconditionally. You
should get identical results with caching enabled or disabled, with speed
being the only difference. You can also disable caching for individual
cache entries in a Context, or specify that individual cache entries should
be disabled by default when they are first allocated.
@see ContextBase::DisableCaching()
@see CacheEntry::disable_caching()
@see CacheEntry::disable_caching_by_default()
@see LeafOutputPort::disable_caching_by_default()
<h4>Which signature to use?</h4>
Although the allocator and calculator functions ultimately satisfy generic
function signatures defined by a ValueProducer, we provide a variety
of `DeclareCacheEntry()` signatures here for convenient specification,
with mapping to the generic form handled invisibly. In particular,
allocators are most easily defined by providing a model value that can be
used to construct an allocator that copies the model when a new value
object is needed. Alternatively a method can be provided that constructs
a value object when invoked (those methods are conventionally, but not
necessarily, named `MakeSomething()` where `Something` is replaced by the
cache entry value type).
Because cache entry values are ultimately stored in AbstractValue objects,
the underlying types must be suitable. That means the type must be copy
constructible or cloneable. For methods below that are not given an explicit
model value or construction ("make") method, the underlying type must also be
default constructible.
@see drake::Value for more about abstract values. */
//@{
/// @anchor DeclareCacheEntry_primary
/** Declares a new %CacheEntry in this System using the most generic form
of the calculation function. Prefer one of the more convenient signatures
below if you can. The new cache entry is assigned a unique CacheIndex and
DependencyTicket, which can be obtained from the returned %CacheEntry.
@param[in] description
A human-readable description of this cache entry, most useful for debugging
and documentation. Not interpreted in any way by Drake; it is retained
by the cache entry and used to generate the description for the
corresponding CacheEntryValue in the Context.
@param[in] value_producer
Provides the computation that maps from a given Context to the current
value that this cache entry should have, as well as a way to allocate
storage prior to the computation.
@param[in] prerequisites_of_calc
Provides the DependencyTicket list containing a ticket for _every_ Context
value on which `calc_function` may depend when it computes its result.
Defaults to `{all_sources_ticket()}` if unspecified. If the cache value
is truly independent of the Context (rare!) say so explicitly by providing
the list `{nothing_ticket()}`; an explicitly empty list `{}` is forbidden.
@returns a reference to the newly-created %CacheEntry.
@throws std::exception if given an explicitly empty prerequisite list. */
CacheEntry& DeclareCacheEntry(
std::string description, ValueProducer value_producer,
std::set<DependencyTicket> prerequisites_of_calc = {
all_sources_ticket()});
/// @anchor DeclareCacheEntry_model_and_calc
/** Declares a cache entry by specifying a model value of concrete type
`ValueType` and a calculator function that is a class member function (method)
with signature: @code
void MySystem::CalcCacheValue(const MyContext&, ValueType*) const;
@endcode
where `MySystem` is a class derived from `SystemBase`, `MyContext` is a class
derived from `ContextBase`, and `ValueType` is any concrete type such that
`Value<ValueType>` is permitted. (The method names are arbitrary.) Template
arguments will be deduced and do not need to be specified. See the
@ref DeclareCacheEntry_primary "primary DeclareCacheEntry() signature"
above for more information about the parameters and behavior.
@see drake::Value */
template <class MySystem, class MyContext, typename ValueType>
CacheEntry& DeclareCacheEntry(
std::string description, const ValueType& model_value,
void (MySystem::*calc)(const MyContext&, ValueType*) const,
std::set<DependencyTicket> prerequisites_of_calc = {
all_sources_ticket()});
/// @anchor DeclareCacheEntry_calc_only
/** Declares a cache entry by specifying only a calculator function that is a
class member function (method) with signature:
@code
void MySystem::CalcCacheValue(const MyContext&, ValueType*) const;
@endcode
where `MySystem` is a class derived from `SystemBase` and `MyContext` is a
class derived from `ContextBase`. `ValueType` is a concrete type such that
(a) `Value<ValueType>` is permitted, and (b) `ValueType` is default
constructible. That allows us to create a model value using
`Value<ValueType>{}` (value initialized so numerical types will be zeroed in
the model). (The method name is arbitrary.) Template arguments will be
deduced and do not need to be specified. See the first DeclareCacheEntry()
signature above for more information about the parameters and behavior.
@note The default constructor will be called once immediately to create a
model value, and subsequent allocations will just copy the model value without
invoking the constructor again. If you want the constructor invoked again at
each allocation (not common), use one of the other signatures to explicitly
provide a method for the allocator to call; that method can then invoke
the `ValueType` default constructor each time it is called.
@see drake::Value */
template <class MySystem, class MyContext, typename ValueType>
CacheEntry& DeclareCacheEntry(
std::string description,
void (MySystem::*calc)(const MyContext&, ValueType*) const,
std::set<DependencyTicket> prerequisites_of_calc = {
all_sources_ticket()});
//@}
// TODO(jwnimmer-tri) This function does not meet the criteria for inline.
/** (Internal use only) Adds an already-constructed input port to this System.
Insists that the port already contains a reference to this System, and that
the port's index is already set to the next available input port index for
this System, that the port name is unique (just within this System), and that
the port name is non-empty. */
// TODO(sherm1) Add check on suitability of `size` parameter for the port's
// data type.
void AddInputPort(std::unique_ptr<InputPortBase> port) {
using internal::PortBaseAttorney;
DRAKE_DEMAND(port != nullptr);
DRAKE_DEMAND(&PortBaseAttorney::get_system_interface(*port) == this);
DRAKE_DEMAND(port->get_index() == num_input_ports());
DRAKE_DEMAND(!port->get_name().empty());
// Check that name is unique.
for (InputPortIndex i{0}; i < num_input_ports(); i++) {
if (port->get_name() == input_ports_[i]->get_name()) {
throw std::logic_error("System " + GetSystemName() +
" already has an input port named " +
port->get_name());
}
}
input_ports_.push_back(std::move(port));
}
// TODO(jwnimmer-tri) This function does not meet the criteria for inline.
/** (Internal use only) Adds an already-constructed output port to this
System. Insists that the port already contains a reference to this System, and
that the port's index is already set to the next available output port index
for this System, and that the name of the port is unique.
@throws std::exception if the name of the output port is not unique. */
// TODO(sherm1) Add check on suitability of `size` parameter for the port's
// data type.
void AddOutputPort(std::unique_ptr<OutputPortBase> port) {
using internal::PortBaseAttorney;
DRAKE_DEMAND(port != nullptr);
DRAKE_DEMAND(&PortBaseAttorney::get_system_interface(*port) == this);
DRAKE_DEMAND(port->get_index() == num_output_ports());
DRAKE_DEMAND(!port->get_name().empty());
// Check that name is unique.
for (OutputPortIndex i{0}; i < num_output_ports(); i++) {
if (port->get_name() == output_ports_[i]->get_name()) {
throw std::logic_error("System " + GetSystemName() +
" already has an output port named " +
port->get_name());
}
}
output_ports_.push_back(std::move(port));
}
/** (Internal use only) Returns a name for the next input port, using the
given name if it isn't kUseDefaultName, otherwise making up a name like "u3"
from the next available input port index.
@pre `given_name` must not be empty. */
std::string NextInputPortName(
std::variant<std::string, UseDefaultName> given_name) const {
const std::string result =
given_name == kUseDefaultName
? std::string("u") + std::to_string(num_input_ports())
: std::get<std::string>(std::move(given_name));
DRAKE_DEMAND(!result.empty());
return result;
}
/** (Internal use only) Returns a name for the next output port, using the
given name if it isn't kUseDefaultName, otherwise making up a name like "y3"
from the next available output port index.
@pre `given_name` must not be empty. */
std::string NextOutputPortName(
std::variant<std::string, UseDefaultName> given_name) const {
const std::string result =
given_name == kUseDefaultName
? std::string("y") + std::to_string(num_output_ports())
: std::get<std::string>(std::move(given_name));
DRAKE_DEMAND(!result.empty());
return result;
}
/** (Internal use only) Assigns a ticket to a new discrete variable group
with the given `index`.
@pre The supplied index must be the next available one; that is, indexes
must be assigned sequentially. */
void AddDiscreteStateGroup(DiscreteStateIndex index) {
DRAKE_DEMAND(index == discrete_state_tickets_.size());
DRAKE_DEMAND(index == context_sizes_.num_discrete_state_groups);
const DependencyTicket ticket(assign_next_dependency_ticket());
discrete_state_tickets_.push_back(
{ticket, "discrete state group " + std::to_string(index)});
++context_sizes_.num_discrete_state_groups;
}
/** (Internal use only) Assigns a ticket to a new abstract state variable with
the given `index`.
@pre The supplied index must be the next available one; that is, indexes
must be assigned sequentially. */
void AddAbstractState(AbstractStateIndex index) {
const DependencyTicket ticket(assign_next_dependency_ticket());
DRAKE_DEMAND(index == abstract_state_tickets_.size());
DRAKE_DEMAND(index == context_sizes_.num_abstract_states);
abstract_state_tickets_.push_back(
{ticket, "abstract state " + std::to_string(index)});
++context_sizes_.num_abstract_states;
}
/** (Internal use only) Assigns a ticket to a new numeric parameter with
the given `index`.
@pre The supplied index must be the next available one; that is, indexes
must be assigned sequentially. */
void AddNumericParameter(NumericParameterIndex index) {
DRAKE_DEMAND(index == numeric_parameter_tickets_.size());
DRAKE_DEMAND(index == context_sizes_.num_numeric_parameter_groups);
const DependencyTicket ticket(assign_next_dependency_ticket());
numeric_parameter_tickets_.push_back(
{ticket, "numeric parameter " + std::to_string(index)});
++context_sizes_.num_numeric_parameter_groups;
}
/** (Internal use only) Assigns a ticket to a new abstract parameter with
the given `index`.
@pre The supplied index must be the next available one; that is, indexes
must be assigned sequentially. */
void AddAbstractParameter(AbstractParameterIndex index) {
const DependencyTicket ticket(assign_next_dependency_ticket());
DRAKE_DEMAND(index == abstract_parameter_tickets_.size());
DRAKE_DEMAND(index == context_sizes_.num_abstract_parameters);
abstract_parameter_tickets_.push_back(
{ticket, "abstract parameter " + std::to_string(index)});
++context_sizes_.num_abstract_parameters;
}
/** (Internal use only) This is for cache entries associated with pre-defined
tickets, for example the cache entry for time derivatives. See the public API
for the most-general DeclareCacheEntry() signature for the meanings of the
other parameters here. */
CacheEntry& DeclareCacheEntryWithKnownTicket(
DependencyTicket known_ticket, std::string description,
ValueProducer value_producer,
std::set<DependencyTicket> prerequisites_of_calc = {
all_sources_ticket()});
/** Returns a pointer to the service interface of the immediately enclosing
Diagram if one has been set, otherwise nullptr. */
const internal::SystemParentServiceInterface* get_parent_service() const {
return parent_service_;
}
/** (Internal use only) Assigns the next unused dependency ticket number,
unique only within a particular system. Each call to this method increments
the ticket number. */
DependencyTicket assign_next_dependency_ticket() {
return next_available_ticket_++;
}
/** (Internal use only) Declares that `parent_service` is the service
interface of the Diagram that owns this subsystem. Aborts if the parent
service has already been set to something else. */
// Use static method so Diagram can invoke this on behalf of a child.
// Output argument is listed first because it is serving as the 'this'
// pointer here.
static void set_parent_service(
SystemBase* child,
const internal::SystemParentServiceInterface* parent_service) {
DRAKE_DEMAND(child != nullptr && parent_service != nullptr);
DRAKE_DEMAND(child->parent_service_ == nullptr ||
child->parent_service_ == parent_service);
child->parent_service_ = parent_service;
}
/** (Internal use only) Given a `port_index`, returns a function to be called
when validating Context::FixInputPort requests. The function should attempt
to throw an exception if the input AbstractValue is invalid, so that errors
can be reported at Fix-time instead of EvalInput-time.*/
virtual std::function<void(const AbstractValue&)> MakeFixInputPortTypeChecker(
InputPortIndex port_index) const = 0;
/** (Internal use only) Shared code for updating an input port and returning a
pointer to its abstract value, or nullptr if the port is not connected. `func`
should be the user-visible API function name obtained with __func__. */
const AbstractValue* EvalAbstractInputImpl(const char* func,
const ContextBase& context,
InputPortIndex port_index) const;
/** Throws std::exception to report a negative `port_index` that was
passed to API method `func`. Caller must ensure that the function name
makes it clear what kind of port we're complaining about. */
// We're taking an int here for the index; InputPortIndex and OutputPortIndex
// can't be negative.
[[noreturn]] void ThrowNegativePortIndex(const char* func,
int port_index) const;
/** Throws std::exception to report bad input `port_index` that was passed
to API method `func`. */
[[noreturn]] void ThrowInputPortIndexOutOfRange(
const char* func, InputPortIndex port_index) const;
/** Throws std::exception to report bad output `port_index` that was passed
to API method `func`. */
[[noreturn]] void ThrowOutputPortIndexOutOfRange(
const char* func, OutputPortIndex port_index) const;
/** Throws std::exception because someone misused API method `func`, that is
only allowed for declared-vector input ports, on an abstract port whose
index is given here. */
[[noreturn]] void ThrowNotAVectorInputPort(const char* func,
InputPortIndex port_index) const;
/** Throws std::exception because someone called API method `func` claiming
the input port had some value type that was wrong. */
[[noreturn]] void ThrowInputPortHasWrongType(
const char* func, InputPortIndex port_index,
const std::string& expected_type, const std::string& actual_type) const;
// This method is static for use from outside the System hierarchy but where
// the problematic System is clear.
/** Throws std::exception because someone called API method `func` claiming
the input port had some value type that was wrong. */
[[noreturn]] static void ThrowInputPortHasWrongType(
const char* func, const std::string& system_pathname, InputPortIndex,
const std::string& port_name, const std::string& expected_type,
const std::string& actual_type);
/** Throws std::exception because someone called API method `func`, that
requires this input port to be evaluatable, but the port was neither
fixed nor connected. */
[[noreturn]] void ThrowCantEvaluateInputPort(const char* func,
InputPortIndex port_index) const;
/** (Internal use only) Returns the InputPortBase at index `port_index`,
throwing std::exception we don't like the port index. The name of the
public API method that received the bad index is provided in `func` and is
included in the error message. The `warn_deprecated` governs whether or not
a deprecation warning should occur when the `port_index` is deprecated; calls
made on behalf of the user should pass `true`; calls made on behalf or the
framework internals should pass `false`. */
const InputPortBase& GetInputPortBaseOrThrow(const char* func,
int port_index,
bool warn_deprecated) const {
if (port_index < 0)
ThrowNegativePortIndex(func, port_index);
const InputPortIndex port(port_index);
if (port_index >= num_input_ports())
ThrowInputPortIndexOutOfRange(func, port);
if (warn_deprecated && input_ports_[port]->get_deprecation().has_value())
WarnPortDeprecation(/* is_input = */ true, port_index);
return *input_ports_[port];
}
/** (Internal use only) Returns the OutputPortBase at index `port_index`,
throwing std::exception if we don't like the port index. The name of the
public API method that received the bad index is provided in `func` and is
included in the error message. The `warn_deprecated` governs whether or not
a deprecation warning should occur when the `port_index` is deprecated; calls
made on behalf of the user should pass `true`; calls made on behalf or the
framework internals should pass `false`. */
const OutputPortBase& GetOutputPortBaseOrThrow(const char* func,
int port_index,
bool warn_deprecated) const {
if (port_index < 0)
ThrowNegativePortIndex(func, port_index);
const OutputPortIndex port(port_index);
if (port_index >= num_output_ports())
ThrowOutputPortIndexOutOfRange(func, port);
if (warn_deprecated && output_ports_[port]->get_deprecation().has_value())
WarnPortDeprecation(/* is_input = */ false, port_index);
return *output_ports_[port_index];
}
/** (Internal use only) Throws std::exception with a message that the sanity
check(s) given by ValidateContext have failed. */
[[noreturn]] void ThrowValidateContextMismatch(const ContextBase&) const;
/** (Internal use only) Returns the message to use for a std::exception in
the case of unsupported scalar type conversions. */
virtual std::string GetUnsupportedScalarConversionMessage(
const std::type_info& source_type,
const std::type_info& destination_type) const;
/** This method must be invoked from within derived class DoAllocateContext()
implementations right after the concrete Context object has been allocated.
It allocates cache entries, sets up all intra-Context dependencies, and marks
the ContextBase as initialized so that we can verify proper derived-class
behavior.
@pre The supplied context must not be null and must not already have been
initialized. */
void InitializeContextBase(ContextBase* context) const;
/** Derived class implementations should allocate a suitable concrete Context
type, then invoke the above InitializeContextBase() method. A Diagram must
then invoke AllocateContext() to obtain each of the subcontexts for its
DiagramContext, and must set up inter-subcontext dependencies among its
children and between itself and its children. Then context resources such as
parameters and state should be allocated. */
virtual std::unique_ptr<ContextBase> DoAllocateContext() const = 0;
/** Return type for get_context_sizes(). Initialized to zero
and equipped with a += operator for Diagram use in aggregation. */
struct ContextSizes {
int num_generalized_positions{0}; // q }
int num_generalized_velocities{0}; // v | Sum is num continuous states x.
int num_misc_continuous_states{0}; // z }
int num_discrete_state_groups{0}; // Each "group" is a vector.
int num_abstract_states{0};
int num_numeric_parameter_groups{0}; // Each "group" is a vector.
int num_abstract_parameters{0};
ContextSizes& operator+=(const ContextSizes& other) {
num_generalized_positions += other.num_generalized_positions;
num_generalized_velocities += other.num_generalized_velocities;
num_misc_continuous_states += other.num_misc_continuous_states;
num_discrete_state_groups += other.num_discrete_state_groups;
num_abstract_states += other.num_abstract_states;
num_numeric_parameter_groups += other.num_numeric_parameter_groups;
num_abstract_parameters += other.num_abstract_parameters;
return *this;
}
};
/** Obtains access to the declared Context partition sizes as accumulated
during LeafSystem or Diagram construction .*/
const ContextSizes& get_context_sizes() const { return context_sizes_; }
/** Obtains mutable access to the Context sizes struct. Should be used only
during LeafSystem or Diagram construction. */
ContextSizes& get_mutable_context_sizes() { return context_sizes_; }
/** Allows Diagram to access protected get_context_sizes() recursively on its
subsystems. */
static const ContextSizes& get_context_sizes(const SystemBase& system) {
return system.get_context_sizes();
}
/** Allows a LeafSystem to override the default size for the implicit time
derivatives residual and a Diagram to sum up the total size. If no value
is set, the default size is n=num_continuous_states().
@param[in] n The size of the residual vector output argument of
System::CalcImplicitTimeDerivativesResidual(). If n <= 0
restore to the default, num_continuous_states().
@see implicit_time_derivatives_residual_size()
@see LeafSystem::DeclareImplicitTimeDerivativesResidualSize()
@see System::CalcImplicitTimeDerivativesResidual() */
void set_implicit_time_derivatives_residual_size(int n) {
implicit_time_derivatives_residual_size_.reset();
if (n > 0)
implicit_time_derivatives_residual_size_ = n;
}
/** (Internal) Gets the id used to tag context data as being created by this
system. See @ref system_compatibility. */
internal::SystemId get_system_id() const { return system_id_; }
/** The NVI implementation of GetGraphvizFragment() for subclasses to override
if desired. The default behavior should be sufficient in most cases. */
virtual GraphvizFragment DoGetGraphvizFragment(
const GraphvizFragmentParams& params) const;
private:
void CreateSourceTrackers(ContextBase*) const;
static internal::SystemId get_next_id();
// Used to create trackers for variable-number System-allocated objects.
struct TrackerInfo {
DependencyTicket ticket;
std::string description;
};
const TrackerInfo& discrete_state_tracker_info(
DiscreteStateIndex index) const {
DRAKE_DEMAND(0 <= index && index < discrete_state_tickets_.size());
return discrete_state_tickets_[index];
}
const TrackerInfo& abstract_state_tracker_info(
AbstractStateIndex index) const {
DRAKE_DEMAND(0 <= index && index < abstract_state_tickets_.size());
return abstract_state_tickets_[index];
}
const TrackerInfo& numeric_parameter_tracker_info(
NumericParameterIndex index) const {
DRAKE_DEMAND(0 <= index && index < numeric_parameter_tickets_.size());
return numeric_parameter_tickets_[index];
}
const TrackerInfo& abstract_parameter_tracker_info(
AbstractParameterIndex index) const {
DRAKE_DEMAND(0 <= index && index < abstract_parameter_tickets_.size());
return abstract_parameter_tickets_[index];
}
template <class Clazz>
[[noreturn]] void ThrowNotCreatedForThisSystem(const Clazz& object,
internal::SystemId id) const {
unused(object);
ThrowNotCreatedForThisSystemImpl(
NiceTypeName::Get<std::remove_pointer_t<Clazz>>(), id);
}
[[noreturn]] void ThrowNotCreatedForThisSystemImpl(
const std::string& nice_type_name, internal::SystemId id) const;
// Given a deprecated input or output port (as determined by `input`), logs
// a warning (just once per process) about the deprecation.
void WarnPortDeprecation(bool is_input, int port_index) const;
// Returns the names of all input (or output) ports, styled for Graphviz using
// its subset of HTML. For example, this handles the markup for deprecated or
// size-0 ports as documented in GetGraphvizString(). The return value is in
// port-index order -- the i'th element is the i'th input (or output) port.
std::vector<std::string> GetGraphvizPortLabels(bool input) const;
// Ports and cache entries hold their own DependencyTickets. Note that the
// addresses of the elements are stable even if the std::vectors are resized.
// Indexed by InputPortIndex.
std::vector<std::unique_ptr<InputPortBase>> input_ports_;
// Indexed by OutputPortIndex.
std::vector<std::unique_ptr<OutputPortBase>> output_ports_;
// Indexed by CacheIndex.
std::vector<std::unique_ptr<CacheEntry>> cache_entries_;
// States and parameters don't hold their own tickets so we track them here.
// Indexed by DiscreteStateIndex.
std::vector<TrackerInfo> discrete_state_tickets_;
// Indexed by AbstractStateIndex.
std::vector<TrackerInfo> abstract_state_tickets_;
// Indexed by NumericParameterIndex.
std::vector<TrackerInfo> numeric_parameter_tickets_;
// Indexed by AbstractParameterIndex.
std::vector<TrackerInfo> abstract_parameter_tickets_;
// Initialize to the first ticket number available after all the well-known
// ones. This gets incremented as tickets are handed out for the optional
// entities above.
DependencyTicket next_available_ticket_{internal::kNextAvailableTicket};
// The enclosing Diagram. Null/invalid when this is the root system.
const internal::SystemParentServiceInterface* parent_service_{nullptr};
// Name of this system.
std::string name_;
// Unique id of this system.
internal::SystemId system_id_{get_next_id()};
// Records the total sizes of Context resources as they will appear
// in a Context allocated by this System. Starts at zero, counts up during
// declaration for LeafSystem construction; computed recursively during
// Diagram construction.
ContextSizes context_sizes_;
// Defaults to num_continuous_states() if no value here. Diagrams always
// fill this in by summing the value from their immediate subsystems.
std::optional<int> implicit_time_derivatives_residual_size_;
};
// Implementations of templatized DeclareCacheEntry() methods.
// Takes an initial value and calc() member function that has an output
// argument.
template <class MySystem, class MyContext, typename ValueType>
CacheEntry& SystemBase::DeclareCacheEntry(
std::string description, const ValueType& model_value,
void (MySystem::*calc)(const MyContext&, ValueType*) const,
std::set<DependencyTicket> prerequisites_of_calc) {
static_assert(std::is_base_of_v<SystemBase, MySystem>,
"Expected to be invoked from a SystemBase-derived System.");
static_assert(std::is_base_of_v<ContextBase, MyContext>,
"Expected to be invoked with a ContextBase-derived Context.");
auto& entry = DeclareCacheEntry(
std::move(description), ValueProducer(this, model_value, calc),
std::move(prerequisites_of_calc));
return entry;
}
// Takes just a calc() member function with an output argument, and
// value-initializes the entry.
template <class MySystem, class MyContext, typename ValueType>
CacheEntry& SystemBase::DeclareCacheEntry(
std::string description,
void (MySystem::*calc)(const MyContext&, ValueType*) const,
std::set<DependencyTicket> prerequisites_of_calc) {
static_assert(
std::is_default_constructible_v<ValueType>,
"SystemBase::DeclareCacheEntry(calc): the calc-only overloads of "
"this method requires that the output type has a default constructor");
// Invokes the above model-value method. Note that value initialization {}
// is required here.
return DeclareCacheEntry(std::move(description), ValueType{}, calc,
std::move(prerequisites_of_calc));
}
#ifndef DRAKE_DOXYGEN_CXX
template <typename> class Diagram;
namespace internal {
// This is an attorney-client pattern class providing Diagram with access to
// certain specific SystemBase protected member functions, and nothing else.
// Without this, Diagram couldn't call protected member functions on instances
// other than itself.
class DiagramSystemBaseAttorney {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DiagramSystemBaseAttorney)
DiagramSystemBaseAttorney() = delete;
private:
template <typename> friend class drake::systems::Diagram;
static std::string GetUnsupportedScalarConversionMessage(
const SystemBase&, const std::type_info&, const std::type_info&);
static std::vector<std::string> GetGraphvizPortLabels(const SystemBase&,
bool input);
};
} // namespace internal
#endif
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/diagram_context.cc | #include "drake/systems/framework/diagram_context.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/parameters.h"
namespace drake {
namespace systems {
template <typename T>
DiagramContext<T>::DiagramContext(int num_subcontexts)
: contexts_(num_subcontexts),
state_(std::make_unique<DiagramState<T>>(num_subcontexts)) {}
template <typename T>
void DiagramContext<T>::AddSystem(
SubsystemIndex index, std::unique_ptr<Context<T>> context) {
DRAKE_DEMAND(index >= 0 && index < num_subcontexts());
DRAKE_DEMAND(contexts_[index] == nullptr);
ContextBase::set_parent(context.get(), this);
contexts_[index] = std::move(context);
}
template <typename T>
void DiagramContext<T>::SubscribeExportedInputPortToDiagramPort(
InputPortIndex input_port_index,
const InputPortIdentifier& subsystem_input_port) {
// Identify and validate the destination input port.
const SubsystemIndex subsystem_index = subsystem_input_port.first;
const InputPortIndex subsystem_iport_index = subsystem_input_port.second;
Context<T>& subcontext = GetMutableSubsystemContext(subsystem_index);
DRAKE_DEMAND(0 <= subsystem_iport_index &&
subsystem_iport_index < subcontext.num_input_ports());
// Get this Diagram's input port that serves as the source.
const DependencyTicket iport_ticket =
this->input_port_ticket(input_port_index);
DependencyTracker& iport_tracker = this->get_mutable_tracker(iport_ticket);
const DependencyTicket subcontext_iport_ticket =
subcontext.input_port_ticket(subsystem_iport_index);
DependencyTracker& subcontext_iport_tracker =
subcontext.get_mutable_tracker(subcontext_iport_ticket);
subcontext_iport_tracker.SubscribeToPrerequisite(&iport_tracker);
}
template <typename T>
void DiagramContext<T>::SubscribeDiagramPortToExportedOutputPort(
OutputPortIndex output_port_index,
const OutputPortIdentifier& subsystem_output_port) {
// Identify and validate the source output port.
const SubsystemIndex subsystem_index = subsystem_output_port.first;
const OutputPortIndex subsystem_oport_index = subsystem_output_port.second;
Context<T>& subcontext = GetMutableSubsystemContext(subsystem_index);
DRAKE_DEMAND(0 <= subsystem_oport_index &&
subsystem_oport_index < subcontext.num_output_ports());
// Get the child subsystem's output port tracker that serves as the source.
const DependencyTicket subcontext_oport_ticket =
subcontext.output_port_ticket(subsystem_oport_index);
DependencyTracker& subcontext_oport_tracker =
subcontext.get_mutable_tracker(subcontext_oport_ticket);
// Get the diagram's output port tracker that is the destination.
const DependencyTicket oport_ticket =
this->output_port_ticket(output_port_index);
DependencyTracker& oport_tracker = this->get_mutable_tracker(oport_ticket);
oport_tracker.SubscribeToPrerequisite(&subcontext_oport_tracker);
}
template <typename T>
void DiagramContext<T>::SubscribeInputPortToOutputPort(
const OutputPortIdentifier& output_port,
const InputPortIdentifier& input_port) {
// Identify and validate the source output port.
const SubsystemIndex oport_system_index = output_port.first;
const OutputPortIndex oport_index = output_port.second;
Context<T>& oport_context = GetMutableSubsystemContext(oport_system_index);
DRAKE_DEMAND(oport_index >= 0);
DRAKE_DEMAND(oport_index < oport_context.num_output_ports());
// Identify and validate the destination input port.
const SubsystemIndex iport_system_index = input_port.first;
const InputPortIndex iport_index = input_port.second;
Context<T>& iport_context = GetMutableSubsystemContext(iport_system_index);
DRAKE_DEMAND(iport_index >= 0);
DRAKE_DEMAND(iport_index < iport_context.num_input_ports());
// Dig out the dependency trackers for both ports so we can subscribe the
// input port tracker to the output port tracker.
const DependencyTicket oport_ticket =
oport_context.output_port_ticket(oport_index);
const DependencyTicket iport_ticket =
iport_context.input_port_ticket(iport_index);
DependencyTracker& oport_tracker =
oport_context.get_mutable_tracker(oport_ticket);
DependencyTracker& iport_tracker =
iport_context.get_mutable_tracker(iport_ticket);
iport_tracker.SubscribeToPrerequisite(&oport_tracker);
}
template <typename T>
void DiagramContext<T>::SubscribeDiagramCompositeTrackersToChildrens() {
// Diagrams don't provide diagram-level tickets for individual
// discrete or abstract state or individual numerical or abstract parameters.
// That means we need only subscribe the aggregate trackers xd, xa, pn, pa
// to their children's xd, xa, pn, pa, resp.
std::vector<internal::BuiltInTicketNumbers> composites{
internal::kQTicket, // Value sources.
internal::kVTicket,
internal::kZTicket,
internal::kXdTicket,
internal::kXaTicket,
internal::kPnTicket,
internal::kPaTicket,
internal::kXcdotTicket, // Cache entries.
internal::kPeTicket,
internal::kKeTicket,
internal::kPcTicket,
internal::kPncTicket};
// Validate the claim above that Diagrams do not have tickets for individual
// variables and parameters.
DRAKE_DEMAND(!this->owns_any_variables_or_parameters());
// Collect the diagram trackers for each composite item above.
DependencyGraph& graph = this->get_mutable_dependency_graph();
std::vector<DependencyTracker*> diagram_trackers;
for (auto ticket : composites) {
diagram_trackers.push_back(
&graph.get_mutable_tracker(DependencyTicket(ticket)));
}
// Subscribe those trackers to the corresponding subcontext trackers.
for (auto& subcontext : contexts_) {
DependencyGraph& subgraph = subcontext->get_mutable_dependency_graph();
for (size_t i = 0; i < composites.size(); ++i) {
auto& sub_tracker =
subgraph.get_mutable_tracker(DependencyTicket(composites[i]));
diagram_trackers[i]->SubscribeToPrerequisite(&sub_tracker);
}
}
}
template <typename T>
void DiagramContext<T>::MakeState() {
auto state = std::make_unique<DiagramState<T>>(num_subcontexts());
for (SubsystemIndex i(0); i < num_subcontexts(); ++i) {
Context<T>& subcontext = *contexts_[i].get();
// Using `access` here to avoid sending invalidations.
state->set_substate(i, &Context<T>::access_mutable_state(&subcontext));
}
state->Finalize();
state->set_system_id(this->get_system_id());
state_ = std::move(state);
}
template <typename T>
void DiagramContext<T>::MakeParameters() {
std::vector<BasicVector<T>*> numeric_params;
std::vector<AbstractValue*> abstract_params;
for (auto& subcontext : contexts_) {
// Using `access` here to avoid sending invalidations.
Parameters<T>& subparams =
Context<T>::access_mutable_parameters(&*subcontext);
for (int i = 0; i < subparams.num_numeric_parameter_groups(); ++i) {
numeric_params.push_back(&subparams.get_mutable_numeric_parameter(i));
}
for (int i = 0; i < subparams.num_abstract_parameters(); ++i) {
abstract_params.push_back(&subparams.get_mutable_abstract_parameter(i));
}
}
auto params = std::make_unique<Parameters<T>>();
params->set_numeric_parameters(
std::make_unique<DiscreteValues<T>>(numeric_params));
params->set_abstract_parameters(
std::make_unique<AbstractValues>(abstract_params));
params->set_system_id(this->get_system_id());
this->init_parameters(std::move(params));
}
template <typename T>
DiagramContext<T>::DiagramContext(const DiagramContext& source)
: Context<T>(source),
contexts_(source.num_subcontexts()),
state_(std::make_unique<DiagramState<T>>(source.num_subcontexts())) {
// Clone all the subsystem contexts.
for (SubsystemIndex i(0); i < num_subcontexts(); ++i) {
DRAKE_DEMAND(source.contexts_[i] != nullptr);
AddSystem(i, Context<T>::CloneWithoutPointers(*source.contexts_[i]));
}
// Build a superstate over the subsystem contexts.
MakeState();
// Build superparameters over the subsystem contexts.
MakeParameters();
// Everything else was handled by the Context<T> copy constructor.
}
template <typename T>
std::unique_ptr<ContextBase> DiagramContext<T>::DoCloneWithoutPointers() const {
return std::unique_ptr<ContextBase>(new DiagramContext<T>(*this));
}
template <typename T>
std::unique_ptr<State<T>> DiagramContext<T>::DoCloneState() const {
auto clone = std::make_unique<DiagramState<T>>(num_subcontexts());
for (SubsystemIndex i(0); i < num_subcontexts(); i++) {
Context<T>* context = contexts_[i].get();
clone->set_and_own_substate(i, context->CloneState());
}
clone->Finalize();
return clone;
}
template <typename T>
std::string DiagramContext<T>::do_to_string() const {
std::ostringstream os;
os << this->GetSystemPathname() << " Context (of a Diagram)\n";
os << std::string(this->GetSystemPathname().size() + 24, '-') << "\n";
if (this->num_continuous_states())
os << this->num_continuous_states() << " total continuous states\n";
if (this->num_discrete_state_groups()) {
int num_discrete_states = 0;
for (int i = 0; i < this->num_discrete_state_groups(); i++) {
num_discrete_states += this->get_discrete_state(i).size();
}
os << num_discrete_states << " total discrete states in "
<< this->num_discrete_state_groups() << " groups\n";
}
if (this->num_abstract_states())
os << this->num_abstract_states() << " total abstract states\n";
if (this->num_numeric_parameter_groups()) {
int num_numeric_parameters = 0;
for (int i = 0; i < this->num_numeric_parameter_groups(); i++) {
num_numeric_parameters += this->get_numeric_parameter(i).size();
}
os << num_numeric_parameters << " total numeric parameters in "
<< this->num_numeric_parameter_groups() << " groups\n";
}
if (this->num_abstract_parameters())
os << this->num_abstract_parameters() << " total abstract parameters\n";
for (systems::SubsystemIndex i{0}; i < num_subcontexts(); i++) {
const Context<T>& subcontext = this->GetSubsystemContext(i);
// Only print this context if it has something useful to print.
if (subcontext.get_continuous_state_vector().size() ||
subcontext.num_discrete_state_groups() ||
subcontext.num_abstract_states() ||
subcontext.num_numeric_parameter_groups() ||
subcontext.num_abstract_parameters()) {
os << "\n" << subcontext.to_string();
}
}
return os.str();
}
template <typename T>
void DiagramContext<T>::DoPropagateTimeChange(
const T& time_sec,
const std::optional<T>& true_time,
int64_t change_event) {
for (auto& subcontext : contexts_) {
DRAKE_ASSERT(subcontext != nullptr);
Context<T>::PropagateTimeChange(&*subcontext, time_sec, true_time,
change_event);
}
}
template <typename T>
void DiagramContext<T>::DoPropagateAccuracyChange(
const std::optional<double>& accuracy,
int64_t change_event) {
for (auto& subcontext : contexts_) {
DRAKE_ASSERT(subcontext != nullptr);
Context<T>::PropagateAccuracyChange(&*subcontext, accuracy, change_event);
}
}
template <typename T>
void DiagramContext<T>::DoPropagateBulkChange(
int64_t change_event,
void (ContextBase::*note_bulk_change)(int64_t change_event)) {
for (auto& subcontext : contexts_) {
DRAKE_ASSERT(subcontext != nullptr);
ContextBase::PropagateBulkChange(&*subcontext, change_event,
note_bulk_change);
}
}
template <typename T>
void DiagramContext<T>::DoPropagateCachingChange(
void (Cache::*caching_change)()) const {
for (auto& subcontext : contexts_) {
DRAKE_ASSERT(subcontext != nullptr);
ContextBase::PropagateCachingChange(*subcontext, caching_change);
}
}
template <typename T>
void DiagramContext<T>::DoPropagateBuildTrackerPointerMap(
const ContextBase& clone,
DependencyTracker::PointerMap* tracker_map) const {
auto& clone_diagram = dynamic_cast<const DiagramContext<T>&>(clone);
DRAKE_DEMAND(clone_diagram.contexts_.size() == contexts_.size());
for (SubsystemIndex i(0); i < num_subcontexts(); ++i) {
ContextBase::BuildTrackerPointerMap(
*contexts_[i], *clone_diagram.contexts_[i], &*tracker_map);
}
}
template <typename T>
void DiagramContext<T>::DoPropagateFixContextPointers(
const ContextBase& source,
const DependencyTracker::PointerMap& tracker_map) {
auto& source_diagram = dynamic_cast<const DiagramContext<T>&>(source);
DRAKE_DEMAND(contexts_.size() == source_diagram.contexts_.size());
for (SubsystemIndex i(0); i < num_subcontexts(); ++i) {
ContextBase::FixContextPointers(*source_diagram.contexts_[i], tracker_map,
&*contexts_[i]);
}
}
} // namespace systems
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::DiagramContext)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/cache.cc | #include "drake/systems/framework/cache.h"
#include <typeindex>
#include <typeinfo>
#include "drake/systems/framework/dependency_tracker.h"
namespace drake {
namespace systems {
std::string CacheEntryValue::GetPathDescription() const {
DRAKE_DEMAND(owning_subcontext_!= nullptr);
return owning_subcontext_->GetSystemPathname() + ":" + description();
}
void CacheEntryValue::ThrowIfBadCacheEntryValue(
const internal::ContextMessageInterface* owning_subcontext) const {
if (owning_subcontext_ == nullptr) {
// Can't use FormatName() here because that depends on us having an owning
// context to talk to.
throw std::logic_error("CacheEntryValue(" + description() + ")::" +
__func__ + "(): entry has no owning subcontext.");
}
if (owning_subcontext && owning_subcontext_ != owning_subcontext) {
throw std::logic_error(FormatName(__func__) + "wrong owning subcontext.");
}
if ((flags_ & ~(kValueIsOutOfDate | kCacheEntryIsDisabled)) != 0) {
throw std::logic_error(FormatName(__func__) +
"flags value is out of range.");
}
if (serial_number() < 0) {
throw std::logic_error(FormatName(__func__) + "serial number is negative.");
}
if (!(cache_index_.is_valid() && ticket_.is_valid())) {
throw std::logic_error(FormatName(__func__) +
"cache index or dependency ticket invalid.");
}
}
void CacheEntryValue::ThrowIfBadOtherValue(
const char* api,
const std::unique_ptr<AbstractValue>* other_value_ptr) const {
if (other_value_ptr == nullptr)
throw std::logic_error(FormatName(api) + "null other_value pointer.");
auto& other_value = *other_value_ptr;
if (other_value == nullptr)
throw std::logic_error(FormatName(api) + "other_value is empty.");
DRAKE_DEMAND(value_ != nullptr); // Should have been checked already.
if (value_->type_info() != other_value->type_info()) {
throw std::logic_error(FormatName(api) +
"other_value has wrong concrete type " +
other_value->GetNiceTypeName() + ". Expected " +
value_->GetNiceTypeName() + ".");
}
}
CacheEntryValue& Cache::CreateNewCacheEntryValue(
CacheIndex index, DependencyTicket ticket,
const std::string& description,
const std::set<DependencyTicket>& prerequisites,
DependencyGraph* trackers) {
DRAKE_DEMAND(trackers != nullptr);
DRAKE_DEMAND(index.is_valid() && ticket.is_valid());
// Make sure there is a place for this cache entry in the cache.
if (index >= cache_size())
store_.resize(index + 1);
// Create the new cache entry value and install it into this Cache. Note that
// indirection here means the CacheEntryValue object's address is stable
// even when store_ is resized.
DRAKE_DEMAND(store_[index] == nullptr);
// Can't use make_unique because constructor is private.
store_[index] = std::unique_ptr<CacheEntryValue>(
new CacheEntryValue(index, ticket, description, owning_subcontext_,
nullptr /* no value yet */));
CacheEntryValue& value = *store_[index];
// Obtain a DependencyTracker for the CacheEntryValue. Normally there will be
// no tracker associated with the given ticket. However, if this cache entry
// corresponds to a well-known tracker (e.g. continuous derivatives xcdot)
// that tracker will already have been created earlier and we just need to
// point the tracker at the new cache entry value.
DependencyTracker* tracker{};
if (trackers->has_tracker(ticket)) {
// Pre-existing trackers should only be present for well-known tickets.
DRAKE_DEMAND(ticket < internal::kNextAvailableTicket);
tracker = &trackers->get_mutable_tracker(ticket);
tracker->set_cache_entry_value(&value);
} else {
// Allocate a DependencyTracker for this cache entry. Note that a pointer
// to the new CacheEntryValue is retained so must have a lifetime matching
// the tracker. That requires that the Cache and DependencyGraph are
// contained in the same Context.
tracker = &trackers->CreateNewDependencyTracker(
ticket,
"cache " + description,
&value);
}
// Subscribe to prerequisites (trackers must already exist).
for (auto prereq : prerequisites) {
auto& prereq_tracker = trackers->get_mutable_tracker(prereq);
tracker->SubscribeToPrerequisite(&prereq_tracker);
}
return value;
}
void Cache::DisableCaching() {
for (auto& entry : store_)
if (entry) entry->disable_caching();
}
void Cache::EnableCaching() {
for (auto& entry : store_)
if (entry) entry->enable_caching();
}
void Cache::SetAllEntriesOutOfDate() {
for (auto& entry : store_)
if (entry) entry->mark_out_of_date();
}
void Cache::RepairCachePointers(
const internal::ContextMessageInterface* owning_subcontext) {
DRAKE_DEMAND(owning_subcontext != nullptr);
DRAKE_DEMAND(owning_subcontext_ == nullptr);
owning_subcontext_ = owning_subcontext;
for (auto& entry : store_)
if (entry) entry->set_owning_subcontext(owning_subcontext);
}
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/cache_entry.cc | #include "drake/systems/framework/cache_entry.h"
#include <exception>
#include <memory>
#include <typeinfo>
#include "drake/common/drake_assert.h"
#include "drake/common/nice_type_name.h"
namespace drake {
namespace systems {
CacheEntry::CacheEntry(
const internal::SystemMessageInterface* owning_system, CacheIndex index,
DependencyTicket ticket, std::string description,
ValueProducer value_producer,
std::set<DependencyTicket> prerequisites_of_calc)
: owning_system_(owning_system),
cache_index_(index),
ticket_(ticket),
description_(std::move(description)),
value_producer_(std::move(value_producer)),
prerequisites_of_calc_(std::move(prerequisites_of_calc)) {
DRAKE_DEMAND(owning_system != nullptr);
DRAKE_DEMAND(index.is_valid() && ticket.is_valid());
DRAKE_DEMAND(value_producer_.is_valid());
if (prerequisites_of_calc_.empty()) {
throw std::logic_error(FormatName("CacheEntry") +
"Cannot create a CacheEntry with an empty prerequisites list. If the "
"Calc() function really has no dependencies, list 'nothing_ticket()' "
"as its sole prerequisite.");
}
}
std::unique_ptr<AbstractValue> CacheEntry::Allocate() const {
std::unique_ptr<AbstractValue> value = value_producer_.Allocate();
if (value == nullptr) {
throw std::logic_error(FormatName("Allocate") +
"allocator returned a nullptr.");
}
return value;
}
void CacheEntry::Calc(const ContextBase& context,
AbstractValue* value) const {
DRAKE_DEMAND(value != nullptr);
DRAKE_ASSERT_VOID(owning_system_->ValidateContext(context));
DRAKE_ASSERT_VOID(CheckValidAbstractValue(context, *value));
value_producer_.Calc(context, value);
}
void CacheEntry::CheckValidAbstractValue(const ContextBase& context,
const AbstractValue& proposed) const {
const CacheEntryValue& cache_value = get_cache_entry_value(context);
const AbstractValue& value = cache_value.PeekAbstractValueOrThrow();
if (proposed.type_info() != value.type_info()) {
throw std::logic_error(FormatName("Calc") +
"expected AbstractValue output type " +
value.GetNiceTypeName() + " but got " +
proposed.GetNiceTypeName() + ".");
}
}
std::string CacheEntry::FormatName(const char* api) const {
return "System '" + owning_system_->GetSystemPathname() + "' (" +
NiceTypeName::RemoveNamespaces(owning_system_->GetSystemType()) +
"): CacheEntry[" + std::to_string(cache_index_) + "](" +
description() + ")::" + api + "(): ";
}
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/state.cc | #include "drake/systems/framework/state.h"
namespace drake {
namespace systems {
template <typename T>
State<T>::State()
: abstract_state_(std::make_unique<AbstractValues>()),
continuous_state_(std::make_unique<ContinuousState<T>>()),
discrete_state_(std::make_unique<DiscreteValues<T>>()) {}
template <typename T>
State<T>::~State() {}
} // namespace systems
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::State)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/basic_vector.h | #pragma once
#include <initializer_list>
#include <memory>
#include <utility>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_throw.h"
#include "drake/common/dummy_value.h"
#include "drake/common/eigen_types.h"
#include "drake/systems/framework/vector_base.h"
namespace drake {
namespace systems {
/// BasicVector is a semantics-free wrapper around an Eigen vector that
/// satisfies VectorBase. Once constructed, its size is fixed.
///
/// @tparam_default_scalar
template <typename T>
class BasicVector : public VectorBase<T> {
public:
// BasicVector cannot be copied or moved; use Clone instead. (We cannot
// support copy or move because of the slicing problem, and also because
// assignment of a BasicVector could change its size.)
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(BasicVector)
/// Constructs an empty BasicVector.
BasicVector() = default;
/// Initializes with the given @p size using the drake::dummy_value<T>, which
/// is NaN when T = double.
explicit BasicVector(int size)
: values_(VectorX<T>::Constant(size, dummy_value<T>::get())) {}
/// Constructs a BasicVector with the specified @p vec data.
explicit BasicVector(VectorX<T> vec) : values_(std::move(vec)) {}
/// Constructs a BasicVector whose elements are the elements of @p init.
BasicVector(const std::initializer_list<T>& init)
: BasicVector<T>(init.size()) {
int i = 0;
for (const T& datum : init) {
(*this)[i++] = datum;
}
}
/// Constructs a BasicVector whose elements are the elements of @p init.
static std::unique_ptr<BasicVector<T>> Make(
const std::initializer_list<T>& init) {
return std::make_unique<BasicVector<T>>(init);
}
/// Constructs a BasicVector where each element is constructed using the
/// placewise-corresponding member of @p args as the sole constructor
/// argument. For instance:
/// BasicVector<symbolic::Expression>::Make("x", "y", "z");
template<typename... Fargs>
static std::unique_ptr<BasicVector<T>> Make(Fargs&&... args) {
auto data = std::make_unique<BasicVector<T>>(sizeof...(args));
BasicVector<T>::MakeRecursive(data.get(), 0, args...);
return data;
}
int size() const final { return static_cast<int>(values_.rows()); }
/// Sets the vector to the given value. After a.set_value(b.get_value()), a
/// must be identical to b.
/// @throws std::exception if the new value has different dimensions.
void set_value(const Eigen::Ref<const VectorX<T>>& value) {
const int n = value.rows();
if (n != size()) { this->ThrowMismatchedSize(n); }
values_ = value;
}
/// Returns a const reference to the contained `VectorX<T>`. This is the
/// preferred method for examining a BasicVector's value.
const VectorX<T>& value() const { return values_; }
/// Returns the entire vector as a mutable Eigen::VectorBlock, which allows
/// mutation of the values, but does not allow `resize()` to be invoked on
/// the returned object.
Eigen::VectorBlock<VectorX<T>> get_mutable_value() {
return values_.head(values_.rows());
}
void SetFromVector(const Eigen::Ref<const VectorX<T>>& value) final {
set_value(value);
}
VectorX<T> CopyToVector() const final { return values_; }
void ScaleAndAddToVector(const T& scale,
EigenPtr<VectorX<T>> vec) const final {
DRAKE_THROW_UNLESS(vec != nullptr);
const int n = vec->rows();
if (n != size()) { this->ThrowMismatchedSize(n); }
*vec += scale * values_;
}
void SetZero() final { values_.setZero(); }
/// Copies the entire vector to a new BasicVector, with the same concrete
/// implementation type.
///
/// Uses the Non-Virtual Interface idiom because smart pointers do not have
/// type covariance.
std::unique_ptr<BasicVector<T>> Clone() const {
auto clone = std::unique_ptr<BasicVector<T>>(DoClone());
clone->set_value(this->get_value());
return clone;
}
// TODO(sherm1) Consider deprecating this.
/// (Don't use this in new code) Returns the entire vector as a const
/// Eigen::VectorBlock. Prefer `value()` which returns direct access to the
/// underlying VectorX rather than wrapping it in a VectorBlock.
Eigen::VectorBlock<const VectorX<T>> get_value() const {
return values_.head(values_.rows());
}
protected:
const T& DoGetAtIndexUnchecked(int index) const final {
DRAKE_ASSERT(index < size());
return values_[index];
}
T& DoGetAtIndexUnchecked(int index) final {
DRAKE_ASSERT(index < size());
return values_[index];
}
const T& DoGetAtIndexChecked(int index) const final {
if (index >= size()) { this->ThrowOutOfRange(index); }
return values_[index];
}
T& DoGetAtIndexChecked(int index) final {
if (index >= size()) { this->ThrowOutOfRange(index); }
return values_[index];
}
/// Returns a new BasicVector containing a copy of the entire vector.
/// Caller must take ownership, and may rely on the NVI wrapper to initialize
/// the clone elementwise.
///
/// Subclasses of BasicVector must override DoClone to return their covariant
/// type.
[[nodiscard]] virtual BasicVector<T>* DoClone() const {
return new BasicVector<T>(this->size());
}
/// Sets @p data at @p index to an object of type T, which must have a
/// single-argument constructor invoked via @p constructor_arg, and then
/// recursively invokes itself on the next index with @p recursive args.
/// Helper for BasicVector<T>::Make.
template<typename F, typename... Fargs>
static void MakeRecursive(BasicVector<T>* data, int index,
F constructor_arg, Fargs&&... recursive_args) {
(*data)[index++] = T(constructor_arg);
BasicVector<T>::MakeRecursive(data, index, recursive_args...);
}
/// Base case for the MakeRecursive template recursion.
template<typename F, typename... Fargs>
static void MakeRecursive(BasicVector<T>* data, int index,
F constructor_arg) {
(*data)[index++] = T(constructor_arg);
}
// TODO(sherm1) Deprecate this method.
/// Provides const access to the element storage. Prefer the synonymous
/// public `value()` method -- this protected method remains for backwards
/// compatibility in derived classes.
const VectorX<T>& values() const { return values_; }
/// (Advanced) Provides mutable access to the element storage. Be careful
/// not to resize the storage unless you really know what you're doing.
VectorX<T>& values() { return values_; }
private:
// Add in multiple scaled vectors to this vector. All vectors
// must be the same size. This function overrides the default DoPlusEqScaled()
// implementation toward maximizing speed. This implementation should be able
// to leverage Eigen's fast scale and add functions in the case that rhs_scal
// is also (i.e., in addition to 'this') a contiguous vector.
void DoPlusEqScaled(
const std::initializer_list<std::pair<T, const VectorBase<T>&>>& rhs_scal)
final {
for (const auto& operand : rhs_scal)
operand.second.ScaleAndAddToVector(operand.first, &values_);
}
// The column vector of T values.
VectorX<T> values_;
// N.B. Do not add more member fields without considering the effect on
// subclasses. Derived class's Clone() methods currently assume that the
// BasicVector(VectorX<T>) constructor is all that is needed.
};
} // namespace systems
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::BasicVector)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/model_values.h | #pragma once
#include <memory>
#include <utility>
#include <vector>
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/value.h"
#include "drake/systems/framework/basic_vector.h"
namespace drake {
namespace systems {
namespace internal {
/// Represents models for a sequence of AbstractValues (usually a sequence of
/// either input or output ports). The models are the "prototype" design
/// pattern (https://en.wikipedia.org/wiki/Prototype_pattern). When creating
/// elements in new Context, these models' values are cloned to establish the
/// subtype and default values of the, e.g. input port.
///
/// Conceptually, the %ModelValues form an infinite sequence. The value at a
/// given index is allowed to be absent, in which case the CloneModel method
/// will return nullptr. Adding new values must be monotonic; new values must
/// use strictly larger indices; the model value for a given index cannot be
/// reset.
class ModelValues {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ModelValues);
ModelValues() = default;
/// Returns one greater than the largest index passed to AddModel or
/// AddVectorModel.
int size() const;
/// Sets @p model_value to be the model value for @p index.
///
/// @pre index >= size()
void AddModel(int index, std::unique_ptr<AbstractValue> model_value);
/// Wraps @p model_vector in a Value and sets that to be the model value for
/// @p index.
///
/// @pre index >= size()
template <typename T>
void AddVectorModel(int index, std::unique_ptr<BasicVector<T>> model_vector);
/// Returns a clone of the model value at @p index, which may be nullptr.
std::unique_ptr<AbstractValue> CloneModel(int index) const;
/// Returns a vector of all the cloned model values. Some may be nullptr.
std::vector<std::unique_ptr<AbstractValue>> CloneAllModels() const {
std::vector<std::unique_ptr<AbstractValue>> ret(size());
for (int i = 0; i < size(); ++i) {
ret[i] = CloneModel(i);
}
return ret;
}
/// Returns a clone of the vector within the model value at @p index, which
/// may be nullptr.
///
/// @throws std::exception if the index has a model but the model's type does
/// not match the given @p T
template <typename T>
std::unique_ptr<BasicVector<T>> CloneVectorModel(int index) const;
private:
// Elements here are allowed to be nullptr.
std::vector<std::unique_ptr<const AbstractValue>> values_;
};
template <typename T>
void ModelValues::AddVectorModel(
int index, std::unique_ptr<BasicVector<T>> model_vector) {
if (model_vector.get() != nullptr) {
AddModel(index, std::make_unique<Value<BasicVector<T>>>(
std::move(model_vector)));
} else {
AddModel(index, std::unique_ptr<AbstractValue>{});
}
}
template <typename T>
std::unique_ptr<BasicVector<T>>
ModelValues::CloneVectorModel(int index) const {
std::unique_ptr<AbstractValue> abstract_result = CloneModel(index);
if (abstract_result.get() == nullptr) {
return nullptr;
}
const auto& basic_vector = abstract_result->get_value<BasicVector<T>>();
return basic_vector.Clone();
}
} // namespace internal
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/event_status.cc | #include "drake/systems/framework/event_status.h"
#include <stdexcept>
#include <fmt/format.h>
#include "drake/common/nice_type_name.h"
#include "drake/systems/framework/system_base.h"
namespace drake {
namespace systems {
void EventStatus::ThrowOnFailure(const char* function_name) const {
if (!failed()) return;
DRAKE_THROW_UNLESS(function_name != nullptr);
/* Attempt to identify the relevant subsystem in human-readable terms. If no
subsystem was provided we just call it "System". Otherwise, we obtain its
type and its name and call it "type system 'name'", e.g.
"MultibodyPlant<double> system 'my_plant'". */
const std::string system_id =
system() == nullptr
? "System"
: fmt::format("{} system '{}'", system()->GetSystemType(),
system()->GetSystemPathname());
throw std::runtime_error(
fmt::format("{}(): An event handler in {} failed with message: \"{}\".",
function_name, system_id, message()));
}
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/diagram_builder.h | #pragma once
#include <map>
#include <memory>
#include <set>
#include <string>
#include <unordered_set>
#include <utility>
#include <variant>
#include <vector>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/hash.h"
#include "drake/common/pointer_cast.h"
#include "drake/common/string_map.h"
#include "drake/systems/framework/diagram.h"
#include "drake/systems/framework/system.h"
namespace drake {
namespace systems {
/// DiagramBuilder is a factory class for Diagram.
///
/// It is single use: after calling Build or BuildInto, DiagramBuilder gives up
/// ownership of the constituent systems, and should therefore be discarded;
/// all member functions will throw an exception after this point.
///
/// When a Diagram (or DiagramBuilder) that owns systems is destroyed, the
/// systems will be destroyed in the reverse of the order they were added.
///
/// A system must be added to the DiagramBuilder with AddSystem or
/// AddNamedSystem before it can be wired up in any way. Every system must have
/// a unique, non-empty name.
///
/// @anchor DiagramBuilder_feedthrough
/// <h2>Building large Diagrams</h2>
///
/// When building large Diagrams with many added systems and input-output port
/// connections, the runtime performance of DiagramBuilder::Build() might become
/// relevant.
///
/// As part of its correctness checks, the DiagramBuilder::Build() function
/// performs a graph search of the diagram's dependencies. In the graph, the
/// nodes are the child systems that have been added to the diagram, and the
/// edges are the diagram connections from one child's output port to another
/// child's input port(s). The builder must confirm that the graph is acyclic;
/// a cycle would imply an infinite loop in an output calculation function.
/// With a large graph, this check can be computationally expensive. To speed
/// it up, ensure that your output ports do not gratuitously depend on
/// irrelevant input ports.
///
/// The dependencies are supplied via the `prerequisites_of_calc` argument to
/// DeclareOutputPort family of functions. If the default value is used (i.e.,
/// when no prerequisites are provided), the default is to assume the output
/// port value is dependent on all possible sources.
///
/// Refer to the
/// @ref DeclareLeafOutputPort_feedthrough "Direct feedthrough"
/// documentation for additional details and examples. In particular, the
/// SystemBase::all_sources_except_input_ports_ticket() is a convenient
/// shortcut for outputs that do not depend on any inputs.
template <typename T>
class DiagramBuilder {
public:
// DiagramBuilder objects are neither copyable nor moveable.
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DiagramBuilder)
/// A designator for a "system + input port" pair, to uniquely refer to
/// some input port on one of this builder's subsystems.
using InputPortLocator = typename Diagram<T>::InputPortLocator;
/// A designator for a "system + output port" pair, to uniquely refer to
/// some output port on one of this builder's subsystems.
using OutputPortLocator = typename Diagram<T>::OutputPortLocator;
DiagramBuilder();
virtual ~DiagramBuilder();
/// Takes ownership of @p system and adds it to the builder. Returns a bare
/// pointer to the System, which will remain valid for the lifetime of the
/// Diagram built by this builder.
///
/// If the system's name is unset, sets it to System::GetMemoryObjectName()
/// as a default in order to have unique names within the diagram.
///
/// @code
/// DiagramBuilder<T> builder;
/// auto foo = builder.AddSystem(std::make_unique<Foo<T>>());
/// @endcode
///
/// @tparam S The type of system to add.
template<class S>
S* AddSystem(std::unique_ptr<S> system) {
ThrowIfAlreadyBuilt();
if (system->get_name().empty()) {
system->set_name(system->GetMemoryObjectName());
}
S* raw_sys_ptr = system.get();
systems_.insert(raw_sys_ptr);
registered_systems_.push_back(std::move(system));
return raw_sys_ptr;
}
/// Constructs a new system with the given @p args, and adds it to the
/// builder, which retains ownership. Returns a bare pointer to the System,
/// which will remain valid for the lifetime of the Diagram built by this
/// builder.
///
/// @code
/// DiagramBuilder<double> builder;
/// auto foo = builder.AddSystem<Foo<double>>("name", 3.14);
/// @endcode
///
/// Note that for dependent names you must use the template keyword:
///
/// @code
/// DiagramBuilder<T> builder;
/// auto foo = builder.template AddSystem<Foo<T>>("name", 3.14);
/// @endcode
///
/// You may prefer the `unique_ptr` variant instead.
///
///
/// @tparam S The type of System to construct. Must subclass System<T>.
///
/// @exclude_from_pydrake_mkdoc{Not bound in pydrake -- emplacement while
/// specifying <T> doesn't make sense for that language.}
template<class S, typename... Args>
S* AddSystem(Args&&... args) {
ThrowIfAlreadyBuilt();
return AddSystem(std::make_unique<S>(std::forward<Args>(args)...));
}
/// Constructs a new system with the given @p args, and adds it to the
/// builder, which retains ownership. Returns a bare pointer to the System,
/// which will remain valid for the lifetime of the Diagram built by this
/// builder.
///
/// @code
/// DiagramBuilder<double> builder;
/// // Foo must be a template.
/// auto foo = builder.AddSystem<Foo>("name", 3.14);
/// @endcode
///
/// Note that for dependent names you must use the template keyword:
///
/// @code
/// DiagramBuilder<T> builder;
/// auto foo = builder.template AddSystem<Foo>("name", 3.14);
/// @endcode
///
/// You may prefer the `unique_ptr` variant instead.
///
/// @tparam S A template for the type of System to construct. The template
/// will be specialized on the scalar type T of this builder.
///
/// @exclude_from_pydrake_mkdoc{Not bound in pydrake -- emplacement while
/// specifying <T> doesn't make sense for that language.}
template<template<typename Scalar> class S, typename... Args>
S<T>* AddSystem(Args&&... args) {
ThrowIfAlreadyBuilt();
return AddSystem(std::make_unique<S<T>>(std::forward<Args>(args)...));
}
/// Takes ownership of @p system, applies @p name to it, and adds it to the
/// builder. Returns a bare pointer to the System, which will remain valid
/// for the lifetime of the Diagram built by this builder.
///
/// @code
/// DiagramBuilder<T> builder;
/// auto bar = builder.AddNamedSystem("bar", std::make_unique<Bar<T>>());
/// @endcode
///
/// @tparam S The type of system to add.
/// @post The system's name is @p name.
template<class S>
S* AddNamedSystem(const std::string& name, std::unique_ptr<S> system) {
ThrowIfAlreadyBuilt();
system->set_name(name);
return AddSystem(std::move(system));
}
/// Constructs a new system with the given @p args, applies @p name to it,
/// and adds it to the builder, which retains ownership. Returns a bare
/// pointer to the System, which will remain valid for the lifetime of the
/// Diagram built by this builder.
///
/// @code
/// DiagramBuilder<double> builder;
/// auto bar = builder.AddNamedSystem<Bar<double>>("bar", 3.14);
/// @endcode
///
/// Note that for dependent names you must use the template keyword:
///
/// @code
/// DiagramBuilder<T> builder;
/// auto bar = builder.template AddNamedSystem<Bar<T>>("bar", 3.14);
/// @endcode
///
/// You may prefer the `unique_ptr` variant instead.
///
/// @tparam S The type of System to construct. Must subclass System<T>.
/// @post The newly constructed system's name is @p name.
///
/// @exclude_from_pydrake_mkdoc{Not bound in pydrake -- emplacement while
/// specifying <T> doesn't make sense for that language.}
template<class S, typename... Args>
S* AddNamedSystem(const std::string& name, Args&&... args) {
ThrowIfAlreadyBuilt();
return AddNamedSystem(
name, std::make_unique<S>(std::forward<Args>(args)...));
}
/// Constructs a new system with the given @p args, applies @p name to it,
/// and adds it to the builder, which retains ownership. Returns a bare
/// pointer to the System, which will remain valid for the lifetime of the
/// Diagram built by this builder.
///
/// @code
/// DiagramBuilder<double> builder;
/// // Bar must be a template.
/// auto bar = builder.AddNamedSystem<Bar>("bar", 3.14);
/// @endcode
///
/// Note that for dependent names you must use the template keyword:
///
/// @code
/// DiagramBuilder<T> builder;
/// auto bar = builder.template AddNamedSystem<Bar>("bar", 3.14);
/// @endcode
///
/// You may prefer the `unique_ptr` variant instead.
///
/// @tparam S A template for the type of System to construct. The template
/// will be specialized on the scalar type T of this builder.
/// @post The newly constructed system's name is @p name.
///
/// @exclude_from_pydrake_mkdoc{Not bound in pydrake -- emplacement while
/// specifying <T> doesn't make sense for that language.}
template<template<typename Scalar> class S, typename... Args>
S<T>* AddNamedSystem(const std::string& name, Args&&... args) {
ThrowIfAlreadyBuilt();
return AddNamedSystem(
name, std::make_unique<S<T>>(std::forward<Args>(args)...));
}
/// Removes the given system from this builder and disconnects any connections
/// or exported ports associated with it.
///
/// Note that un-exporting this system's ports might have a ripple effect on
/// other exported port index assignments. The relative order will remain
/// intact, but any "holes" created by this removal will be filled in by
/// decrementing the indices of all higher-numbered ports that remain.
///
/// @warning Because a DiagramBuilder owns the objects it contains, the system
/// will be deleted.
void RemoveSystem(const System<T>& system);
/// Returns whether any Systems have been added yet.
bool empty() const {
ThrowIfAlreadyBuilt();
return registered_systems_.empty();
}
/// Returns true iff Build() or BuildInto() has been called on this Builder,
/// in which case it's an error to call any member function other than the
/// the destructor.
bool already_built() const {
return already_built_;
}
/// Returns the list of contained Systems.
/// @see GetSubsystemByName()
/// @see GetMutableSystems()
std::vector<const System<T>*> GetSystems() const;
/// Returns the list of contained Systems.
/// @see GetMutableSubsystemByName()
/// @see GetSystems()
std::vector<System<T>*> GetMutableSystems();
/// Returns true iff this contains a subsystem with the given name.
/// @see GetSubsystemByName()
bool HasSubsystemNamed(std::string_view name) const;
/// Retrieves a const reference to the subsystem with name @p name returned
/// by get_name().
/// @throws std::exception if a unique match cannot be found.
/// @see System<T>::get_name()
/// @see GetMutableSubsystemByName()
/// @see GetDowncastSubsystemByName()
const System<T>& GetSubsystemByName(std::string_view name) const;
/// Retrieves a mutable reference to the subsystem with name @p name returned
/// by get_name().
/// @throws std::exception if a unique match cannot be found.
/// @see System<T>::get_name()
/// @see GetSubsystemByName()
/// @see GetMutableDowncastSubsystemByName()
System<T>& GetMutableSubsystemByName(std::string_view name);
/// Retrieves a const reference to the subsystem with name @p name returned
/// by get_name(), downcast to the type provided as a template argument.
/// @tparam MySystem is the downcast type, e.g., drake::systems::Adder
/// @throws std::exception if a unique match cannot be found.
/// @see GetMutableDowncastSubsystemByName()
/// @see GetSubsystemByName()
template <template <typename> class MySystem>
const MySystem<T>& GetDowncastSubsystemByName(std::string_view name) const {
return GetDowncastSubsystemByName<MySystem<T>>(name);
}
/// Retrieves a mutable reference to the subsystem with name @p name returned
/// by get_name(), downcast to the type provided as a template argument.
/// @tparam MySystem is the downcast type, e.g., drake::systems::Adder
/// @throws std::exception if a unique match cannot be found.
/// @see GetDowncastSubsystemByName()
/// @see GetMutableSubsystemByName()
template <template <typename> class MySystem>
MySystem<T>& GetMutableDowncastSubsystemByName(std::string_view name) {
return GetMutableDowncastSubsystemByName<MySystem<T>>(name);
}
#ifndef DRAKE_DOXYGEN_CXX
// We're omitting this from doxygen as the details are unhelpful.
// Variants of Get[Mutable]DowncastSubsystemByName that allow for leaf
// systems that are not templatized.
// The requested LeafSystem must still have the same underlying scalar type
// as this builder.
template <class MyUntemplatizedSystem>
const MyUntemplatizedSystem& GetDowncastSubsystemByName(
std::string_view name) const {
static_assert(std::is_same_v<typename MyUntemplatizedSystem::Scalar, T>,
"Scalar type of untemplatized System doesn't match the "
"DiagramBuilder's.");
const System<T>& subsystem = this->GetSubsystemByName(name);
return *dynamic_pointer_cast_or_throw<const MyUntemplatizedSystem>(
&subsystem);
}
template <class MyUntemplatizedSystem>
MyUntemplatizedSystem& GetMutableDowncastSubsystemByName(
std::string_view name) {
static_assert(std::is_same_v<typename MyUntemplatizedSystem::Scalar, T>,
"Scalar type of untemplatized System doesn't match the "
"DiagramBuilder's.");
System<T>& subsystem = this->GetMutableSubsystemByName(name);
return *dynamic_pointer_cast_or_throw<MyUntemplatizedSystem>(&subsystem);
}
#endif
/// (Advanced) Returns a reference to the map of connections between Systems.
/// The reference becomes invalid upon any call to Build or BuildInto.
const std::map<InputPortLocator, OutputPortLocator>& connection_map() const;
/// Declares that input port @p dest is connected to output port @p src.
/// @note The connection created between @p src and @p dest via a call to
/// this method can be effectively overridden by any subsequent call to
/// InputPort::FixValue(). That is, calling InputPort::FixValue() on an
/// already connected input port causes the resultant
/// FixedInputPortValue to override any other value present on that
/// port.
void Connect(const OutputPort<T>& src, const InputPort<T>& dest);
/// Declares that sole input port on the @p dest system is connected to sole
/// output port on the @p src system.
/// This function ignores deprecated ports, unless there is only one port in
/// which case it will use the deprecated port.
/// @note The connection created between @p src and @p dest via a call to
/// this method can be effectively overridden by any subsequent call to
/// InputPort::FixValue(). That is, calling InputPort::FixValue() on an
/// already connected input port causes the resultant
/// FixedInputPortValue to override any other value present on that
/// port.
/// @throws std::exception if the sole-port precondition is not met (i.e.,
/// if @p dest has no input ports, or @p dest has more than one input port,
/// or @p src has no output ports, or @p src has more than one output port).
///
/// @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
void Connect(const System<T>& src, const System<T>& dest);
/// Cascades @p src and @p dest. The sole input port on the @p dest system
/// is connected to sole output port on the @p src system.
/// @throws std::exception if the sole-port precondition is not met (i.e., if
/// @p dest has no input ports, or @p dest has more than one input port, or
/// @p src has no output ports, or @p src has more than one output port).
void Cascade(const System<T>& src, const System<T>& dest);
/// Declares that the given @p input port of a constituent system is
/// connected to a new input to the entire Diagram. @p name is an optional
/// name for the new input port; if it is unspecified, then a default name
/// will be provided.
/// @pre If supplied at all, @p name must not be empty.
/// @pre A port indicated by the resolution of @p name must not exist.
/// @post @p input is connected to the new exported input port.
/// @return The index of the exported input port of the entire diagram.
InputPortIndex ExportInput(
const InputPort<T>& input,
std::variant<std::string, UseDefaultName> name = kUseDefaultName);
/// Connects an input to the entire Diagram, indicated by @p
/// diagram_port_name, to the given @p input port of a constituent system.
/// @pre The Diagram input indicated by @p diagram_port_name must have been
/// previously built via ExportInput().
/// @post @p input is connected to the indicated Diagram input port.
void ConnectInput(
std::string_view diagram_port_name, const InputPort<T>& input);
/// Connects an input to the entire Diagram, indicated by @p
/// diagram_port_index, to the given @p input port of a constituent system.
/// @pre The Diagram input indicated by @p diagram_port_index must have been
/// previously built via ExportInput().
/// @post @p input is connected to the indicated Diagram input port.
void ConnectInput(
InputPortIndex diagram_port_index, const InputPort<T>& input);
/// Connects @p dest to the same source as @p exemplar is connected to.
///
/// If @p exemplar was connected to an output port, then @p dest is connected
/// to that same output. Or, if @p exemplar was exported as an input of this
/// diagram, then @p dest will be connected to that same diagram input. Or,
/// if @p exemplar was neither connected or exported, then this function is
/// a no-op.
///
/// Both @p exemplar and @p dest must be ports of constituent systems that
/// have already been added to this diagram.
///
/// @return True iff any connection or was made; or false when a no-op.
bool ConnectToSame(const InputPort<T>& exemplar, const InputPort<T>& dest);
/// Declares that the given @p output port of a constituent system is an
/// output of the entire diagram. @p name is an optional name for the output
/// port; if it is unspecified, then a default name will be provided.
/// @pre If supplied at all, @p name must not be empty.
/// @return The index of the exported output port of the entire diagram.
OutputPortIndex ExportOutput(
const OutputPort<T>& output,
std::variant<std::string, UseDefaultName> name = kUseDefaultName);
/// Builds the Diagram that has been described by the calls to Connect,
/// ExportInput, and ExportOutput.
/// @throws std::exception if the graph is not buildable.
///
/// See @ref DiagramBuilder_feedthrough "Building large Diagrams" for tips
/// on improving runtime performance of this function.
std::unique_ptr<Diagram<T>> Build();
/// Configures @p target to have the topology that has been described by
/// the calls to Connect, ExportInput, and ExportOutput.
/// @throws std::exception if the graph is not buildable.
///
/// Only Diagram subclasses should call this method. The target must not
/// already be initialized.
void BuildInto(Diagram<T>* target);
/// Returns true iff the given input @p port of a constituent system is either
/// connected to another constituent system or exported as a diagram input.
bool IsConnectedOrExported(const InputPort<T>& port) const;
/// Returns the current number of diagram input ports. The count may change
/// as more ports are exported.
int num_input_ports() const;
/// Returns the current number of diagram output outputs. The count may change
/// as more ports are exported.
int num_output_ports() const;
private:
// Declares a new input to the entire Diagram, using @p model_input to
// supply the data type. @p name is an optional name for the input port; if
// it is unspecified, then a default name will be provided.
// @pre @p model_input must be a port of a system within the diagram.
// @pre If supplied at all, @p name must not be empty.
// @pre A port indicated by the resolution of @p name must not exist.
// @post @p model_input is *not* connected to the new exported input port.
// @return The index of the exported input port of the entire diagram.
InputPortIndex DeclareInput(
const InputPort<T>& model_input,
std::variant<std::string, UseDefaultName> name = kUseDefaultName);
void ThrowIfAlreadyBuilt() const;
// Throws if the given input port (belonging to a child subsystem) has
// already been connected to an output port, or exported to be an input
// port of the whole diagram.
void ThrowIfInputAlreadyWired(const InputPortLocator& id) const;
void ThrowIfSystemNotRegistered(const System<T>* system) const;
void ThrowIfAlgebraicLoopsExist() const;
void CheckInvariants() const;
// Produces the Blueprint that has been described by the calls to
// Connect, ExportInput, and ExportOutput. Throws std::exception if the
// graph is empty or contains algebraic loops.
// The DiagramBuilder passes ownership of the registered systems to the
// blueprint.
std::unique_ptr<typename Diagram<T>::Blueprint> Compile();
// Whether or not Build() or BuildInto() has been called yet.
bool already_built_{false};
// The ordered inputs and outputs of the Diagram to be built.
std::vector<InputPortLocator> input_port_ids_;
std::vector<std::string> input_port_names_;
std::vector<OutputPortLocator> output_port_ids_;
std::vector<std::string> output_port_names_;
// For fast membership queries: has this input port already been wired?
std::unordered_set<InputPortLocator, DefaultHash> diagram_input_set_;
// A vector of data about exported input ports.
struct ExportedInputData {
// Which port to use for data type comparisons at connection time.
InputPortLocator model_input;
// The name of the port.
std::string name;
};
std::vector<ExportedInputData> diagram_input_data_;
// The InputPort fan-out API requires name lookup in some cases.
string_map<InputPortIndex> diagram_input_indices_;
// A map from the input ports of constituent systems, to the output ports of
// the systems from which they get their values.
std::map<InputPortLocator, OutputPortLocator> connection_map_;
// A mirror on the systems in the diagram. Should have the same values as
// registered_systems_. Used for fast membership queries.
std::unordered_set<const System<T>*> systems_;
// The Systems in this DiagramBuilder, in the order they were registered.
internal::OwnedSystems<T> registered_systems_;
};
} // namespace systems
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::DiagramBuilder)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/event_status.h | #pragma once
#include <string>
#include <utility>
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
namespace drake {
namespace systems {
class SystemBase;
/** Holds the return status from execution of an event handler function, or the
effective status after a series of handler executions due to dispatching of
simultaneous events. Drake API users will typically use only the four factory
methods below to return status, and optionally a human-readable message, from
their event handlers. */
class EventStatus {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(EventStatus)
/** The numerical values are ordered, with
did_nothing < success < terminate < fatal. */
enum Severity {
/** Successful, but nothing happened; no state update needed. */
kDidNothing = 0,
/** Handler executed successfully; state may have been updated. */
kSucceeded = 1,
/** Handler succeeded but detected a normal termination condition (has
message). Intended primarily for internal use by the Simulator. */
kReachedTermination = 2,
/** Handler was unable to perform its job (has message). */
kFailed = 3
};
/** Returns "did nothing" status, with no message. */
static EventStatus DidNothing() { return EventStatus(kDidNothing); }
/** Returns "succeeded" status, with no message. */
static EventStatus Succeeded() { return EventStatus(kSucceeded); }
// TODO(sherm1) Requiring user code to supply the System explicitly
// is asking for trouble. The code that invoked the event handler
// will be in a better position to fill in the correct System.
/** Returns "reached termination" status, with a message explaining why. */
static EventStatus ReachedTermination(const SystemBase* system,
std::string message) {
return EventStatus(kReachedTermination, system, std::move(message));
}
/** Returns "failed" status, with a message explaining why. */
static EventStatus Failed(const SystemBase* system, std::string message) {
return EventStatus(kFailed, system, std::move(message));
}
/** Returns `true` if the status is DidNothing. */
bool did_nothing() const { return severity() == kDidNothing; }
/** Returns `true` if the status is Succeeded. "Did nothing" can
also be viewed as successful but you have to check for that separately. */
bool succeeded() const { return severity() == kSucceeded; }
/** Returns `true` if the status is ReachedTermination. There will also be
a message() with more detail. */
bool reached_termination() const { return severity() == kReachedTermination; }
/** Returns `true` if the status is Failed. There will also be a message()
with more detail. */
bool failed() const { return severity() == kFailed; }
/** Returns the severity of the current status. */
Severity severity() const { return severity_; }
/** Returns the optionally-provided subsystem that generated a status
return that can include a message (reached termination or failed). Returns
nullptr if no subsystem was provided. */
const SystemBase* system() const { return system_; }
/** Returns the optionally-provided human-readable message supplied by the
event handler that produced the current status. Returns an empty string if
no message was provided. */
const std::string& message() const { return message_; }
/** If failed(), throws an std::exception with a human-readable message.
@param function_name The name of the user-callable API that encountered
the failure. Don't include "()". */
void ThrowOnFailure(const char* function_name) const;
/** (Advanced) Replaces the contents of `this` with the more-severe status
if `candidate` is a more severe status than `this` one. Does nothing if
`candidate` severity is less than or equal to `this` severity. This method is
for use in event dispatchers for accumulating status returns from a series of
event handlers for a set of simultaneous events. */
EventStatus& KeepMoreSevere(EventStatus candidate) {
if (candidate.severity() > severity()) *this = candidate;
return *this;
}
private:
explicit EventStatus(Severity severity) : severity_(severity) {}
EventStatus(Severity severity, const SystemBase* system, std::string message)
: severity_(severity), system_(system), message_(std::move(message)) {}
Severity severity_{kFailed};
const SystemBase* system_{nullptr};
std::string message_;
};
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/scalar_conversion_traits.cc | #include "drake/systems/framework/scalar_conversion_traits.h"
// This is an empty file to confirm that our header parses on its own.
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/fixed_input_port_value.h | #pragma once
#include <cstddef>
#include <functional>
#include <memory>
#include <utility>
#include <vector>
#include "drake/common/copyable_unique_ptr.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/reset_on_copy.h"
#include "drake/common/value.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/framework_common.h"
namespace drake {
namespace systems {
class ContextBase;
#ifndef DRAKE_DOXYGEN_CXX
namespace internal {
// This provides ContextBase limited "friend" access to FixedInputPortValue.
class ContextBaseFixedInputAttorney;
} // namespace internal
#endif
/** A %FixedInputPortValue encapsulates a vector or abstract value for
use as an internal value source for one of a System's input ports. The semantics
are identical to a Parameter. We assign a DependencyTracker to this object
and subscribe the InputPort to it when that port is fixed. Any modification to
the value here issues a notification to its dependent, and increments a serial
number kept here. */
class FixedInputPortValue {
public:
/** @name Does not allow move or assignment; copy is private. */
/** @{ */
FixedInputPortValue(FixedInputPortValue&&) = delete;
FixedInputPortValue& operator=(const FixedInputPortValue&) = delete;
FixedInputPortValue& operator=(FixedInputPortValue&&) = delete;
/** @} */
// Construction is private and only accessible to ContextBase via the
// attorney.
~FixedInputPortValue() = default;
/** Returns a reference to the contained abstract value. */
const AbstractValue& get_value() const {
DRAKE_DEMAND(value_ != nullptr); // Should always be a value.
return *value_;
}
/** Returns a reference to the contained `BasicVector<T>` or throws an
exception if this doesn't contain an object of that type. */
template <typename T>
const BasicVector<T>& get_vector_value() const {
return get_value().get_value<BasicVector<T>>();
}
/** Returns a pointer to the data inside this %FixedInputPortValue, and
notifies the dependent input port that the value has changed.
To ensure invalidation notifications are delivered, callers should call this
method every time they wish to update the stored value. In particular, callers
MUST NOT write through the returned pointer if there is any possibility this
%FixedInputPortValue has been accessed since the last time this method
was called. */
// TODO(sherm1) Replace these with safer Set() methods.
AbstractValue* GetMutableData();
/** Returns a pointer to the data inside this %FixedInputPortValue, and
notifies the dependent input port that the value has changed, invalidating
downstream computations.
@throws std::exception if the data is not vector data.
To ensure invalidation notifications are delivered, callers should call this
method every time they wish to update the stored value. In particular, callers
MUST NOT write through the returned pointer if there is any possibility this
%FixedInputPortValue has been accessed since the last time this method
was called.
@tparam T Scalar type of the input port's vector value. Must match the type
associated with this port. */
template <typename T>
BasicVector<T>* GetMutableVectorData() {
return &GetMutableData()->get_mutable_value<BasicVector<T>>();
}
/** Returns the serial number of the contained value. This counts up every
time the contained value changes, or when mutable access is granted. */
int64_t serial_number() const { return serial_number_; }
/** Returns the ticket used to find the associated DependencyTracker. */
DependencyTicket ticket() const {
DRAKE_ASSERT(ticket_.is_valid());
return ticket_;
}
/** Returns a const reference to the context that owns this object. */
const ContextBase& get_owning_context() const {
DRAKE_ASSERT(owning_subcontext_ != nullptr);
return *owning_subcontext_;
}
private:
friend class internal::ContextBaseFixedInputAttorney;
// Allow this adapter access to our private copy constructor. This is intended
// only for use by ContextBase.
friend class copyable_unique_ptr<FixedInputPortValue>;
// Constructs an abstract-valued FixedInputPortValue from a value
// of arbitrary type. Takes ownership of the given value and sets the serial
// number to 1. The value must not be null.
explicit FixedInputPortValue(std::unique_ptr<AbstractValue> value)
: value_(std::move(value)), serial_number_{1} {
DRAKE_DEMAND(value_ != nullptr);
}
// Copy constructor is only used for cloning and is not a complete copy --
// owning_subcontext_ is left unassigned.
FixedInputPortValue(const FixedInputPortValue& source) = default;
// Informs this FixedInputPortValue of its assigned DependencyTracker
// so it knows who to notify when its value changes.
void set_ticket(DependencyTicket ticket) {
DRAKE_DEMAND(ticket.is_valid() && !ticket_.is_valid());
ticket_ = ticket;
}
// Informs this %FixedInputPortValue of the subcontext that owns it.
// Aborts if this has already been done or given bad args.
void set_owning_subcontext(ContextBase* owning_subcontext) {
DRAKE_DEMAND(owning_subcontext != nullptr && owning_subcontext_ == nullptr);
owning_subcontext_ = owning_subcontext;
}
// Needed for invalidation.
reset_on_copy<ContextBase*> owning_subcontext_;
// The value and its serial number.
copyable_unique_ptr<AbstractValue> value_;
// The serial number is useful for debugging and counting changes but has
// no role in cache invalidation. Note that after a Context is cloned, both
// the value and serial number are copied -- the clone serial number does
// not reset. That avoids accidental serial number matches if someone has
// recorded the number somewhere. If the serial number matches, the value
// is either unchanged since you last saw it, or an identical copy.
int64_t serial_number_{-1};
// Index of the dependency tracker for this fixed value. The input port
// should have registered with this tracker.
DependencyTicket ticket_;
};
#ifndef DRAKE_DOXYGEN_CXX
namespace internal {
class ContextBaseFixedInputAttorney {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ContextBaseFixedInputAttorney);
ContextBaseFixedInputAttorney() = delete;
private:
friend class drake::systems::ContextBase;
// "Output" argument is first here since it is serving as a `this` pointer.
static void set_owning_subcontext(FixedInputPortValue* fixed,
ContextBase* owning_subcontext) {
DRAKE_DEMAND(fixed != nullptr);
fixed->set_owning_subcontext(owning_subcontext);
}
static void set_ticket(FixedInputPortValue* fixed,
DependencyTicket ticket) {
DRAKE_DEMAND(fixed != nullptr);
fixed->set_ticket(ticket);
}
// This serves as the only accessible constructor for FixedInputPortValues.
// It must be followed immediately by inserting into a Context with the
// assigned ticket and the owning subcontext set using the above methods.
static std::unique_ptr<FixedInputPortValue> CreateFixedInputPortValue(
std::unique_ptr<AbstractValue> value) {
// Can't use make_unique here since constructor is private.
return std::unique_ptr<FixedInputPortValue>(
new FixedInputPortValue(std::move(value)));
}
};
} // namespace internal
#endif
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/leaf_context.h | #pragma once
#include <memory>
#include <string>
#include "drake/common/default_scalars.h"
#include "drake/systems/framework/context.h"
namespace drake {
namespace systems {
/** %LeafContext contains all prerequisite data necessary to uniquely determine
the results of computations performed by the associated LeafSystem.
@see Context for more information.
@tparam_default_scalar
*/
template <typename T>
class LeafContext : public Context<T> {
public:
/// @name Does not allow copy, move, or assignment.
//@{
// Copy constructor is protected for use in implementing Clone().
LeafContext(LeafContext&&) = delete;
LeafContext& operator=(const LeafContext&) = delete;
LeafContext& operator=(LeafContext&&) = delete;
//@}
LeafContext();
~LeafContext() override;
#ifndef DRAKE_DOXYGEN_CXX
// Temporarily promoting these to public so that LeafSystem and testing code
// can construct a LeafContext with state & parameters. Users should never
// call these because state & parameters should not be resized once allocated
// (or at least should be done under Framework control so that dependency
// tracking can be correctly revised).
// TODO(sherm1) Make these inaccessible to users. See discussion in PR #9029.
using Context<T>::init_continuous_state;
using Context<T>::init_discrete_state;
using Context<T>::init_abstract_state;
using Context<T>::init_parameters;
#endif
protected:
/// Protected copy constructor takes care of the local data members and
/// all base class members, but doesn't update base class pointers so is
/// not a complete copy.
LeafContext(const LeafContext& source);
/// Derived classes should reimplement and replace this; don't recursively
/// invoke it.
std::unique_ptr<ContextBase> DoCloneWithoutPointers() const override;
std::unique_ptr<State<T>> DoCloneState() const override;
private:
friend class LeafContextTest;
using ContextBase::AddInputPort; // For LeafContextTest.
using ContextBase::AddOutputPort;
using ContextBase::AddDiscreteStateTicket;
using ContextBase::AddAbstractStateTicket;
using ContextBase::AddNumericParameterTicket;
using ContextBase::AddAbstractParameterTicket;
const State<T>& do_access_state() const final {
DRAKE_ASSERT(state_ != nullptr);
return *state_;
}
State<T>& do_access_mutable_state() final {
DRAKE_ASSERT(state_ != nullptr);
return *state_;
}
void notify_set_system_id(internal::SystemId id) final;
/// Returns a partial textual description of the Context, intended to be
/// human-readable. It is not guaranteed to be unambiguous nor complete.
std::string do_to_string() const final;
// The state values (x) for this LeafContext; this is never null.
std::unique_ptr<State<T>> state_;
};
} // namespace systems
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::LeafContext)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/port_base.h | #pragma once
#include <atomic>
#include <optional>
#include <string>
#include <utility>
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/framework_common.h"
namespace drake {
namespace systems {
#ifndef DRAKE_DOXYGEN_CXX
namespace internal {
// This class is defined later in this header file, below.
class PortBaseAttorney;
} // namespace internal
#endif
/** A PortBase is base class for System ports; users will typically use the
InputPort<T> or OutputPort<T> types, not this base class. */
class PortBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(PortBase)
virtual ~PortBase();
/** Get port name. */
const std::string& get_name() const { return name_; }
/** Returns a verbose human-readable description of port. This is useful for
error messages or debugging. */
std::string GetFullDescription() const;
/** Returns the port data type. */
PortDataType get_data_type() const { return data_type_; }
/** Returns the fixed size expected for a vector-valued port. Not
meaningful for abstract-valued ports. */
int size() const { return size_; }
/** When this port is deprecated, returns non-null with a (possibly empty)
deprecation message; when this port is not deprecated, returns null. */
const std::optional<std::string>& get_deprecation() const {
return deprecation_;
}
/** Sets whether this port is deprecated (and if so, the message). */
void set_deprecation(std::optional<std::string> deprecation) {
deprecation_ = std::move(deprecation);
}
/** (Advanced.) Returns the DependencyTicket for this port within the owning
System. */
DependencyTicket ticket() const {
return ticket_;
}
protected:
/** Provides derived classes the ability to set the base
class members at construction.
@param kind_string
Either "Input" or "Output", depending on the kind of subclass.
@param owning_system
The System that owns this port.
@param owning_system_id
The ID of owning_system.
@param name
A name for the port. Port names should be non-empty and unique within a
single System.
@param index
The index to be assigned to this port. Input ports and output ports each
have their own pool of indices (InputPortIndex and OutputPortIndex); this
is just that TypeSafeIndex passed as a bare int.
@param ticket
The DependencyTicket to be assigned to this port.
@param data_type
Whether the port described is vector- or abstract-valued.
@param size
If the port described is vector-valued, the number of elements. Ignored for
abstract-valued ports.
*/
PortBase(
const char* kind_string, internal::SystemMessageInterface* owning_system,
internal::SystemId owning_system_id, std::string name, int index,
DependencyTicket ticket, PortDataType data_type, int size);
/** Returns the index of this port within the owning System (i.e., an
InputPortIndex or OutputPortIndex, but as a bare integer). For a Diagram,
this will be the index within the Diagram, _not_ the index within the
LeafSystem whose output port was forwarded. */
int get_int_index() const { return index_; }
/** Returns a reference to the system that owns this port. Note that for a
diagram port this will be the diagram, not the leaf system whose port was
exported. */
const internal::SystemMessageInterface& get_system_interface() const {
return owning_system_;
}
/** Returns get_system_interface(), but without the const. */
internal::SystemMessageInterface& get_mutable_system_interface() {
return owning_system_;
}
/** (Internal use only) Checks whether the given id (nominally obtained from a
Context passed to this port) was created for the system that owns this port.
This is similar in spirit to SystemBase::ValidateContext, but ports cannot
use SystemBase.
@note This method is sufficiently fast for performance sensitive code. */
void ValidateSystemId(internal::SystemId id) const {
if (id != owning_system_id_) {
ThrowValidateContextMismatch();
}
}
/** (Internal use only) Throws std::exception with a message that the sanity
check(s) related to ValidateContext have failed. */
[[noreturn]] void ThrowValidateContextMismatch() const;
/** Pull a value of a given type from an abstract value or issue a nice
message if the type is not correct. */
template <typename ValueType>
const ValueType& PortEvalCast(const AbstractValue& abstract) const;
/** Downcast a basic vector to a more specific subclass, or else issue a nice
message if the type is not correct. */
template <typename ValueType, typename T>
const ValueType& PortEvalCast(const BasicVector<T>& basic) const;
/** Reports that the user provided a bad ValueType argument to Eval. */
template <typename ValueType>
[[noreturn]] const ValueType& ThrowBadCast(
const AbstractValue& abstract) const {
ThrowBadCast(abstract.GetNiceTypeName(), NiceTypeName::Get<ValueType>());
}
/** Reports that the user provided a bad ValueType argument to Eval. */
template <typename ValueType, typename T>
[[noreturn]] const ValueType& ThrowBadCast(
const BasicVector<T>& basic) const {
ThrowBadCast(NiceTypeName::Get(basic), NiceTypeName::Get<ValueType>());
}
/** Reports that the user provided a bad ValueType argument to Eval. The
value_typename is the type of the port's current value; the eval_typename is
the type the user asked for. */
[[noreturn]] void ThrowBadCast(
const std::string& value_typename,
const std::string& eval_typename) const;
private:
friend class internal::PortBaseAttorney;
// "Input" or "Output" (used for human-readable debugging strings).
const char* const kind_string_;
// Associated System and System resources.
internal::SystemMessageInterface& owning_system_;
const internal::SystemId owning_system_id_;
const int index_;
const DependencyTicket ticket_;
// Port details.
const PortDataType data_type_;
const int size_;
const std::string name_;
std::optional<std::string> deprecation_;
std::atomic<bool> deprecation_already_warned_{false};
};
// Keep this inlineable. Error reporting should happen in a separate method.
template <typename ValueType>
const ValueType& PortBase::PortEvalCast(const AbstractValue& abstract) const {
const ValueType* const value = abstract.maybe_get_value<ValueType>();
if (!value) {
ThrowBadCast<ValueType>(abstract);
}
return *value;
}
// Keep this inlineable. Error reporting should happen in a separate method.
template <typename ValueType, typename T>
const ValueType& PortBase::PortEvalCast(const BasicVector<T>& basic) const {
const ValueType* const value = dynamic_cast<const ValueType*>(&basic);
if (!value) {
ThrowBadCast<ValueType>(basic);
}
return *value;
}
#ifndef DRAKE_DOXYGEN_CXX
class SystemBase;
template <typename> class Diagram;
class LeafSystemDeprecationTest;
namespace internal {
// This is an attorney-client pattern class providing SystemBase and Diagram
// with access to certain specific PortBase members.
class PortBaseAttorney {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(PortBaseAttorney)
PortBaseAttorney() = delete;
private:
friend class drake::systems::SystemBase;
template <typename> friend class drake::systems::Diagram;
friend class drake::systems::LeafSystemDeprecationTest;
// Returns a reference to the system that owns this port. Note that for a
// diagram port this will be the diagram, not the leaf system whose port was
// exported.
static const SystemMessageInterface& get_system_interface(
const PortBase& port) {
return port.get_system_interface();
}
// Returns the bool stored within the given port that indicates whether we've
// already logged a deprecation warning about it.
static std::atomic<bool>* deprecation_already_warned(PortBase* port) {
return &port->deprecation_already_warned_;
}
};
} // namespace internal
#endif
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/diagram_discrete_values.cc | #include "drake/systems/framework/diagram_discrete_values.h"
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::DiagramDiscreteValues)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/system_compatibility_doxygen.h | /** @file
Doxygen-only documentation for @ref system_compatibility. */
//------------------------------------------------------------------------------
/** @defgroup system_compatibility System Compatibility
@ingroup technical_notes
System compatibility refers to the correspondence between a System and data
structures used to hold the results of computation. Examples include Context,
State, Parameters, etc. To avoid hard-to-debug errors when the wrong object is
used with a System, public methods of System and System-derived classes check
compatibility with objects by using unique system IDs. These IDs are applied to
objects when System-provided methods are used to construct them:
AllocateContext(), AllocateOutput(), etc.
In most cases users should be able to ignore this compatibility checking
mechanism; setting and checking of IDs should happen naturally in most
cases. However, when copying data values between similar systems, some care
must be taken. for example, a Clone() of a checked object will not work with a
system different from its source, but constructing a destination object using
methods of the destination System and using SetFrom() or lower level value
accessors will work.
<h2>Details</h2>
A system ID is required for checking the correspondence between a
system-specific data structure like a Context or DiscreteValues and the
(unique) System which can accept it as a value. A data structure participates
in the system ID hinting family by implementing the following concept:
@code
internal::SystemId get_system_id() const;
void set_system_id(internal::SystemId id);
@endcode
get_system_id of an object whose set_system_id has not been called will return
an invalid (default-constructed, zero-valued) ID.
A System method participates by calling ValidateCreatedForThisSystem(object)
on an object that implements the concept.
An invalid system ID represents the absence of information about the associated
System; an object carrying an invalid system ID cannot be used in any
participating System method, under penalty of std::exception.
Likewise passing an object with valid system ID into a method of a System with
different ID will result in a std::exception.
An ID-bearing structure may contain ID-bearing substructures which have
different (or invalid) IDs from their parent. Using such a structure may, but
is not guaranteed to, result in a std::exception, depending on the semantics of
the method called.
Where an ID-bearing object implements Clone(), it MUST clone the system ID and,
recursively, those of its members, whether valid or invalid.
Where an ID-bearing object implements the potentially-scalar-converting
SetFrom(), if the scalar types differ, it MUST NOT set the system IDs, nor may
it set the system IDs of its copied members (because being of the wrong type it
is no longer valid data for the original System). This prohibition does not
apply when the scalar types are the same.
Data types that currently implement the above-described scheme include Context,
ContinuousState, DiscreteValues, CompositeEventCollection, Parameters, State,
and SystemOutput.
The SystemConstraint class uses a custom mechanism to extend checking of
Context compatibility to its public methods.
<h2>Effects on Public API</h2>
This change does not declare a deprecation because virtually all of the
affected use cases were invalid to begin with and would have resulted in errors
later in the affected code. The exception is hand-constructed objects (i.e.,
objects with public constructors that were not constructed through methods of
System); most such objects have not worked reliably in the past anyway.
*/
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/port_base.cc | #include "drake/systems/framework/port_base.h"
#include <utility>
#include <fmt/format.h>
#include "drake/common/drake_assert.h"
#include "drake/common/nice_type_name.h"
namespace drake {
namespace systems {
PortBase::PortBase(
const char* kind_string, internal::SystemMessageInterface* owning_system,
internal::SystemId owning_system_id, std::string name, int index,
DependencyTicket ticket, PortDataType data_type, int size)
: kind_string_(kind_string),
owning_system_(*owning_system),
owning_system_id_(owning_system_id),
index_(index),
ticket_(ticket),
data_type_(data_type),
size_(size),
name_(std::move(name)) {
DRAKE_DEMAND(kind_string != nullptr);
DRAKE_DEMAND(owning_system != nullptr);
DRAKE_DEMAND(owning_system_id.is_valid());
DRAKE_DEMAND(!name_.empty());
}
PortBase::~PortBase() = default;
std::string PortBase::GetFullDescription() const {
return fmt::format(
"{}Port[{}] ({}) of System {} ({})",
kind_string_, index_, name_, get_system_interface().GetSystemPathname(),
NiceTypeName::RemoveNamespaces(get_system_interface().GetSystemType()));
}
void PortBase::ThrowValidateContextMismatch() const {
throw std::logic_error(fmt::format(
"{}Port: The Context given as an argument was not created for this {}",
kind_string_, GetFullDescription()));
}
void PortBase::ThrowBadCast(
const std::string& value_typename, const std::string& eval_typename) const {
throw std::logic_error(fmt::format(
"{}Port::Eval(): wrong value type {} specified; "
"actual type was {} for {}.",
kind_string_, eval_typename, value_typename, GetFullDescription()));
}
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/input_port.h | #pragma once
#include <memory>
#include <optional>
#include <string>
#include <type_traits>
#include <utility>
#include "drake/common/constants.h"
#include "drake/common/default_scalars.h"
#include "drake/common/drake_assert.h"
#include "drake/common/eigen_types.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/context.h"
#include "drake/systems/framework/framework_common.h"
#include "drake/systems/framework/input_port_base.h"
#include "drake/systems/framework/value_to_abstract_value.h"
namespace drake {
namespace systems {
// Break the System <=> InputPort physical dependency cycle. InputPorts are
// decorated with a back-pointer to their owning System<T>, but that pointer is
// forward-declared here and never dereferenced within this file.
template <typename T>
class System;
/** An InputPort is a System resource that describes the kind of input a
System accepts, on a given port. It does not directly contain any runtime
input port data; that is always contained in a Context. The actual value will
be either the value of an OutputPort to which this is connected, or a fixed
value set in a Context.
@tparam_default_scalar
*/
template <typename T>
class InputPort final : public InputPortBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(InputPort)
/** Returns a reference to the up-to-date value of this input port contained
in the given Context. This is the preferred way to obtain an input port's
value since it will not be recalculated once up to date.
If the value is not already up to date with respect to its prerequisites, it
will recalculate an up-to-date value before the reference is returned. The
recalculation may be arbitrarily expensive, but Eval() is constant time and
_very_ fast if the value is already up to date.
@param context A Context for this System that also contains the value source
for this input port. If that source is an output port of another System then
`context` must be a subcontext of the Diagram that contains both this System
and the one providing the output port.
@tparam ValueType The type of the const-reference returned by this method.
When omitted, the return type is `const VectorX<T>&` (this is only valid
when this is a vector-valued port). For abstract ports, the `ValueType`
either can be the declared type of the port (e.g., `lcmt_iiwa_status`), or
else in advanced use cases can be `AbstractValue` to get the type-erased
value.
@return reference to the up-to-date value; if a ValueType is provided, the
return type is `const ValueType&`; if a ValueType is omitted, the return type
is `const VectorX<T>&`.
@throw std::exception if the port is not connected. (Use HasValue() to check
first, if necessary.)
@pre The input port is vector-valued (when no ValueType is provided).
@pre The input port is of type ValueType (when ValueType is provided).
*/
#ifdef DRAKE_DOXYGEN_CXX
template <typename ValueType = VectorX<T>>
const ValueType& Eval(const Context<T>& context) const;
#else
// Without a template -- return Eigen.
const VectorX<T>& Eval(const Context<T>& context) const {
return Eval<BasicVector<T>>(context).value();
}
// With ValueType == AbstractValue, we don't need to downcast.
template <typename ValueType, typename = std::enable_if_t<
std::is_same_v<AbstractValue, ValueType>>>
const AbstractValue& Eval(const Context<T>& context) const {
ValidateSystemId(context.get_system_id());
return DoEvalRequired(context);
}
// With anything but a BasicVector subclass, we can just DoEval then cast.
template <typename ValueType, typename = std::enable_if_t<
!std::is_same_v<AbstractValue, ValueType> && (
!std::is_base_of_v<BasicVector<T>, ValueType> ||
std::is_same_v<BasicVector<T>, ValueType>)>>
const ValueType& Eval(const Context<T>& context) const {
ValidateSystemId(context.get_system_id());
return PortEvalCast<ValueType>(DoEvalRequired(context));
}
// With a BasicVector subclass, we need to downcast twice.
template <typename ValueType, typename = std::enable_if_t<
std::is_base_of_v<BasicVector<T>, ValueType> &&
!std::is_same_v<BasicVector<T>, ValueType>>>
const ValueType& Eval(const Context<T>& context, int = 0) const {
return PortEvalCast<ValueType>(Eval<BasicVector<T>>(context));
}
#endif // DRAKE_DOXYGEN_CXX
/** Provides a fixed value for this %InputPort in the given Context. If the
port is already connected, this value will override the connected source
value. (By "connected" we mean that the port appeared in a
DiagramBuilder::Connect() call.)
For vector-valued input ports, you can provide an Eigen vector expression,
a BasicVector object, or a scalar (treated as a Vector1). In each of these
cases the value is copied into a `Value<BasicVector>`. If the original
value was a BasicVector-derived object, its concrete type is maintained
although the stored type is still `Value<BasicVector>`. The supplied vector
must have the right size for the vector port or an std::logic_error is thrown.
For abstract-valued input ports, you can provide any ValueType that is
compatible with the model type provided when the port was declared. If the
type has a copy constructor it will be copied into a `Value<ValueType>`
object for storage. Otherwise it must have an accessible `Clone()` method and
it is stored using the type returned by that method, which must be ValueType
or a base class of ValueType. Eigen objects and expressions are not
accepted directly, but you can store then in abstract ports by providing
an already-abstract object like `Value<MatrixXd>(your_matrix)`.
The returned FixedInputPortValue reference may be used to modify the input
port's value subsequently using the appropriate FixedInputPortValue method,
which will ensure that cache invalidation notifications are delivered.
@tparam ValueType The type of the supplied `value` object. This will be
inferred so no template argument need be specified. The type must be
copy constructible or have an accessible `Clone()` method.
@param[in,out] context A Context that is compatible with the System that
owns this port.
@param[in] value The fixed value for this port. Must be convertible
to the input port's data type.
@returns a reference to the FixedInputPortValue object in the Context that
contains this port's value.
@pre `context` is compatible with the System that owns this %InputPort.
@pre `value` is compatible with this %InputPort's data type. */
template <typename ValueType>
FixedInputPortValue& FixValue(Context<T>* context,
const ValueType& value) const {
DRAKE_DEMAND(context != nullptr);
ValidateSystemId(context->get_system_id());
const bool is_vector_port = (get_data_type() == kVectorValued);
std::unique_ptr<AbstractValue> abstract_value =
is_vector_port
? internal::ValueToVectorValue<T>::ToAbstract(__func__, value)
: internal::ValueToAbstractValue::ToAbstract(__func__, value);
return context->FixInputPort(get_index(), *abstract_value);
}
/** Returns true iff this port is connected or has had a fixed value provided
in the given Context. Beware that at the moment, this could be an expensive
operation, because the value is brought up-to-date as part of this
operation. */
bool HasValue(const Context<T>& context) const {
ValidateSystemId(context.get_system_id());
return DoEvalOptional(context);
}
/** Returns a reference to the System that owns this input port. Note that
for a Diagram input port this will be the Diagram, not the LeafSystem whose
input port was exported. */
const System<T>& get_system() const { return system_; }
// A using-declaration adds these methods into our class's Doxygen.
// (Placed in an order that makes sense for the class's table of contents.)
using PortBase::get_name;
using PortBase::GetFullDescription;
using InputPortBase::get_index;
using PortBase::get_data_type;
using PortBase::size;
using InputPortBase::is_random;
using InputPortBase::get_random_type;
using PortBase::ticket;
using InputPortBase::Allocate;
private:
friend class internal::FrameworkFactory;
// See InputPortBase for the meaning of these parameters. The additional
// `system` parameter must point to the same object as `system_interface`.
// (They're separate because System is forward-declared so we can't cast.)
InputPort(
const System<T>* system,
internal::SystemMessageInterface* system_interface,
internal::SystemId system_id, std::string name,
InputPortIndex index, DependencyTicket ticket, PortDataType data_type,
int size, const std::optional<RandomDistribution>& random_type,
EvalAbstractCallback eval, ValueProducer::AllocateCallback alloc)
: InputPortBase(system_interface, system_id, std::move(name), index,
ticket, data_type, size, random_type, std::move(eval),
std::move(alloc)),
system_(*system) {
DRAKE_DEMAND(system != nullptr);
// Check the precondition on identical parameters; note that comparing as
// void* is only valid because we have single inheritance.
DRAKE_DEMAND(static_cast<const void*>(system) == system_interface);
}
const System<T>& system_;
};
} // namespace systems
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::InputPort)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/single_output_vector_source.h | #pragma once
#include <memory>
#include <utility>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/systems/framework/context.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace systems {
/// A base class that specializes LeafSystem for use with no input ports, and
/// only a single, vector output port. Subclasses should override the protected
/// method
/// @code
/// void DoCalcOutput(const Context<T>&, Eigen::VectorBlock<VectorX<T>>*) const;
/// @endcode
///
/// @system
/// name: SingleOutputVectorSource
/// output_ports:
/// - y0
/// @endsystem
///
/// @tparam_default_scalar
template <typename T>
class SingleOutputVectorSource : public LeafSystem<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SingleOutputVectorSource)
/// Deleted default constructor. Child classes must either supply the
/// vector size to the single-argument constructor of `int`, or supply a model
/// vector to the single-argument constructor of `const BasicVector<T>&`.
SingleOutputVectorSource() = delete;
~SingleOutputVectorSource() override = default;
/// Returns the sole output port.
const OutputPort<T>& get_output_port() const {
return LeafSystem<T>::get_output_port(0);
}
// Don't use the indexed get_output_port when calling this system directly.
void get_output_port(int) = delete;
protected:
/// Creates a source with the given sole output port configuration.
///
/// @note Objects created using this constructor overload do not support
/// system scalar conversion. See @ref system_scalar_conversion. Use a
/// different constructor overload if such conversion is desired.
explicit SingleOutputVectorSource(int size)
: SingleOutputVectorSource({}, size) {}
/// Creates a source with output type and dimension of the @p model_vector.
///
/// @note Objects created using this constructor overload do not support
/// system scalar conversion. See @ref system_scalar_conversion. Use a
/// different constructor overload if such conversion is desired.
explicit SingleOutputVectorSource(const BasicVector<T>& model_vector)
: SingleOutputVectorSource({}, model_vector) {}
/// Creates a source with the given sole output port configuration.
///
/// @note objects created using this constructor may support system scalar
/// conversion. See @ref system_scalar_conversion.
///
/// @param converter is per LeafSystem::LeafSystem constructor documentation;
/// see that function documentation for details.
SingleOutputVectorSource(SystemScalarConverter converter, int size)
: SingleOutputVectorSource(std::move(converter), BasicVector<T>(size)) {}
/// Creates a source with output type and dimension of the @p model_vector.
///
/// @note objects created using this constructor may support system scalar
/// conversion. See @ref system_scalar_conversion.
///
/// @param converter is per LeafSystem::LeafSystem constructor documentation;
/// see that function documentation for details.
SingleOutputVectorSource(
SystemScalarConverter converter, const BasicVector<T>& model_vector)
: LeafSystem<T>(std::move(converter)) {
this->DeclareVectorOutputPort(
kUseDefaultName, model_vector,
&SingleOutputVectorSource<T>::CalcVectorOutput);
}
/// Provides a convenience method for %SingleOutputVectorSource subclasses.
/// This method performs the same logical operation as System::DoCalcOutput
/// but provides the single output's VectorBlock instead. Subclasses should
/// override this method, and not the base class method (which is `final`).
virtual void DoCalcVectorOutput(
const Context<T>& context,
Eigen::VectorBlock<VectorX<T>>* output) const = 0;
private:
// Confirms the single-output invariant when allocating the context.
void DoValidateAllocatedLeafContext(const LeafContext<T>&) const final {
DRAKE_DEMAND(this->num_input_ports() == 0);
DRAKE_DEMAND(this->num_output_ports() == 1);
}
// Converts the parameters to Eigen::VectorBlock form, then delegates to
// DoCalcVectorOutput().
void CalcVectorOutput(const Context<T>& context,
BasicVector<T>* output) const {
Eigen::VectorBlock<VectorX<T>> block = output->get_mutable_value();
DoCalcVectorOutput(context, &block);
}
};
} // namespace systems
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::SingleOutputVectorSource)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/basic_vector.cc | #include "drake/systems/framework/basic_vector.h"
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::BasicVector)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/system_constraint.h | #pragma once
#include <functional>
#include <limits>
#include <optional>
#include <string>
#include <utility>
#include "drake/common/autodiff.h"
#include "drake/common/default_scalars.h"
#include "drake/common/drake_assert.h"
#include "drake/common/drake_bool.h"
#include "drake/common/drake_throw.h"
#include "drake/common/eigen_types.h"
#include "drake/common/never_destroyed.h"
#include "drake/common/type_safe_index.h"
#include "drake/systems/framework/context.h"
#include "drake/systems/framework/framework_common.h"
namespace drake {
namespace systems {
// Break the System <=> SystemConstraint physical dependency cycle.
// SystemConstraint is decorated with a back-pointer to its owning System,
// but that pointer is never dereferenced within this component.
template <typename T>
class System;
/// The form of a SystemConstraint.
enum class SystemConstraintType {
kEquality = 0, ///< The constraint is of the form f(x)=0.
kInequality =
1, ///< The constraint is of the form lower_bound <= f(x) <= upper_bound.
};
/// The bounds of a SystemConstraint. This also encompasses the form of the
/// constraint: equality constraints occur when both the lower and upper bounds
/// are all zeros.
class SystemConstraintBounds final {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(SystemConstraintBounds)
/// Creates constraint bounds with zero size.
SystemConstraintBounds() : SystemConstraintBounds(0) {}
/// Creates constraint of type SystemConstraintType::kEquality, with the
/// given size for `f(x)`.
static SystemConstraintBounds Equality(int size) {
DRAKE_THROW_UNLESS(size >= 0);
return SystemConstraintBounds(size);
}
/// Creates a constraint with the given upper and lower bounds for `f(x)`.
/// The type() of this constraint will be kInequality, except in the unusual
/// case where both lower and upper are all zeros (in which case it is
/// kEquality). It is not currently allowed to set lower == upper (creating
/// an equality constraint in the form f(x) = b), except when b == 0. Using
/// a non-zero b might be allowed in the future.
SystemConstraintBounds(
const Eigen::Ref<const Eigen::VectorXd>& lower,
const Eigen::Ref<const Eigen::VectorXd>& upper);
/// Creates an inequality constraint with the given lower bounds for `f(x)`.
/// The upper bounds are all positive infinity.
SystemConstraintBounds(
const Eigen::Ref<const Eigen::VectorXd>& lower,
std::nullopt_t);
/// Creates an inequality constraint with the given upper bounds for `f(x)`.
/// The lower bounds are all negative infinity.
SystemConstraintBounds(
std::nullopt_t,
const Eigen::Ref<const Eigen::VectorXd>& upper);
int size() const { return size_; }
SystemConstraintType type() const { return type_; }
const Eigen::VectorXd& lower() const { return lower_; }
const Eigen::VectorXd& upper() const { return upper_; }
private:
explicit SystemConstraintBounds(int size);
int size_{};
SystemConstraintType type_{};
Eigen::VectorXd lower_;
Eigen::VectorXd upper_;
};
/// This is the signature of a stateless function that evaluates the value of
/// the constraint function f:
/// value = f(context)
///
/// Note that in the std::function signature, the computed value is an output
/// parameter, not a return value.
///
/// See also SystemConstraintCalc, which offers the System reference.
template <typename T>
using ContextConstraintCalc =
std::function<void(const Context<T>&, VectorX<T>* value)>;
/// This is the signature of a stateless function that evaluates the value of
/// the constraint function f:
/// value = f(system, context)
///
/// Note that in the std::function signature, the computed value is an output
/// parameter, not a return value.
///
/// Instances of this function type are expected to work with *any* instance of
/// the class of System they are designed for. Specifically, they should not
/// capture pointers into an instance of a System, OutputPort, etc. Instead,
/// they should only use the System reference that is passed into this functor.
///
/// See also ContextConstraintCalc, which omits the System reference. A value
/// of type ContextConstraintCalc is allowed to assume it's only ever applied
/// to a specific System object.
template <typename T>
using SystemConstraintCalc =
std::function<void(const System<T>&, const Context<T>&, VectorX<T>* value)>;
/// A SystemConstraint is a generic base-class for constraints on Systems.
///
/// A SystemConstraint is a means to inform our algorithms *about*
/// the implemented system behavior -- declaring the constraint does not
/// *cause* the system behavior to change. It is meant to improve analysis
/// by telling our algorithms that "all valid solutions of this dynamical
/// system will satisfy the following (in)equalities". Examples could
/// include conserved quantities or joint limits on a mechanism.
///
/// This class is intentionally similar to, but (so far) independent from
/// solvers::Constraint. This is primarily because there is no notion of
/// decision variables in the system classes (yet); rather each individual
/// algorithm (e.g. trajectory optimization, or system identification)
/// constructs decision variables for the particular mathematical program that
/// is being formulated, and must bind the system constraint to those variables
/// (e.g. by populating the Context with the decision variables and calling
/// Calc).
///
/// We can convert a SystemConstraint to a solvers::Constraint by using
/// SystemConstraintWrapper or SystemConstraintAdapter.
///
/// @see LeafSystem<T>::DeclareEqualityConstraint and
/// LeafSystem<T>::DeclareInequalityConstraint for use cases.
/// @tparam_default_scalar
template <typename T>
class SystemConstraint final {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SystemConstraint)
/// (Advanced) Constructs a default (zero-sized) SystemConstraint.
///
/// Most users should call a LeafSystem method like DeclareEqualityConstraint
/// to create (and add) constraints, not call this constructor directly.
///
/// @param description a human-readable description useful for debugging.
SystemConstraint(const System<T>* system,
std::string description)
: SystemConstraint<T>(
system, &NoopSystemConstraintCalc, SystemConstraintBounds{},
std::move(description)) {}
/// (Advanced) Constructs a SystemConstraint. Depending on the `bounds` it
/// could be an equality constraint f(x) = 0, or an inequality constraint
/// lower_bound <= f(x) <= upper_bound.
///
/// Most users should call a LeafSystem method like DeclareEqualityConstraint
/// to create (and add) constraints, not call this constructor directly.
///
/// @param description a human-readable description useful for debugging.
SystemConstraint(const System<T>* system,
ContextConstraintCalc<T> calc_function,
SystemConstraintBounds bounds,
std::string description)
: system_(system),
system_calc_function_{},
context_calc_function_(std::move(calc_function)),
bounds_(std::move(bounds)),
description_(std::move(description)) {
DRAKE_DEMAND(system != nullptr);
}
/// (Advanced) Constructs a SystemConstraint. Depending on the `bounds` it
/// could be an equality constraint f(x) = 0, or an inequality constraint
/// lower_bound <= f(x) <= upper_bound.
///
/// Most users should call a LeafSystem method like DeclareEqualityConstraint
/// to create (and add) constraints, not call this constructor directly.
///
/// @param description a human-readable description useful for debugging.
SystemConstraint(const System<T>* system,
SystemConstraintCalc<T> calc_function,
SystemConstraintBounds bounds,
std::string description)
: system_(system),
system_calc_function_(std::move(calc_function)),
context_calc_function_{},
bounds_(std::move(bounds)),
description_(std::move(description)) {
DRAKE_DEMAND(system != nullptr);
}
/// Evaluates the function pointer passed in through the constructor,
/// writing the output to @p value. @p value will be (non-conservatively)
/// resized to match the constraint function output.
void Calc(const Context<T>& context, VectorX<T>* value) const {
MaybeValidateSystemIdsMatch(context);
value->resize(size());
if (context_calc_function_) {
context_calc_function_(context, value);
} else {
system_calc_function_(*system_, context, value);
}
DRAKE_DEMAND(value->size() == size());
}
/// Evaluates the function pointer, and check if all of the outputs
/// are within the desired bounds.
boolean<T> CheckSatisfied(const Context<T>& context, double tol) const {
MaybeValidateSystemIdsMatch(context);
DRAKE_DEMAND(tol >= 0.0);
VectorX<T> value(size());
Calc(context, &value);
// Special-case (tol == 0.0) cases both so that the symbolic form is
// elegant, and so that double evaluation is as fast as possible.
if (type() == SystemConstraintType::kEquality) {
if (tol == 0.0) {
return drake::all(value.array() == 0.0);
} else {
return drake::all(value.cwiseAbs().array() <= tol);
}
} else {
DRAKE_ASSERT(type() == SystemConstraintType::kInequality);
// TODO(hongkai.dai): ignore the bounds that are infinite.
if (tol == 0.0) {
return drake::all(value.array() >= lower_bound().array()) &&
drake::all(value.array() <= upper_bound().array());
} else {
return drake::all((value - lower_bound()).array() >= -tol) &&
drake::all((upper_bound() - value).array() >= -tol);
}
}
}
/// Returns a reference to the System that owns this constraint. Note that
/// for a constraint on a diagram this will be the diagram itself, never a
/// leaf system whose constraint was re-expressed.
const System<T>& get_system() const {
return *system_;
}
// Accessor methods.
const SystemConstraintBounds& bounds() const { return bounds_; }
int size() const { return bounds_.size(); }
SystemConstraintType type() const { return bounds_.type(); }
bool is_equality_constraint() const {
return (bounds_.type() == SystemConstraintType::kEquality);
}
const Eigen::VectorXd& lower_bound() const { return bounds_.lower(); }
const Eigen::VectorXd& upper_bound() const { return bounds_.upper(); }
const std::string& description() const { return description_; }
/// @name System compatibility
/// See @ref system_compatibility.
//@{
/// (Internal use only) Gets the id of the subsystem associated with this
/// object, if one has been set.
const std::optional<internal::SystemId>& get_system_id() const {
return system_id_;
}
/// (Internal use only) Records the id of the subsystem associated with this
/// object.
void set_system_id(internal::SystemId id) { system_id_ = id; }
//@}
private:
static void NoopSystemConstraintCalc(
const System<T>&, const Context<T>&, VectorX<T>*) {}
// If this object has a system id, check that it matches the id of the
// context parameter.
void MaybeValidateSystemIdsMatch(const Context<T>& context) const {
DRAKE_DEMAND(!system_id_.has_value() ||
*system_id_ == context.get_system_id());
}
const System<T>* const system_;
const SystemConstraintCalc<T> system_calc_function_;
const ContextConstraintCalc<T> context_calc_function_;
const SystemConstraintBounds bounds_;
const std::string description_;
// The id of the subsystem associated with this object.
std::optional<internal::SystemId> system_id_;
};
/// An "external" constraint on a System. This class is intended for use by
/// applications that are examining a System by adding additional constraints
/// based on their particular situation (e.g., that a velocity state element
/// has an upper bound); it is not intended for declaring intrinsic constraints
/// that some particular System subclass might always impose on itself (e.g.,
/// that a mass parameter is non-negative).
class ExternalSystemConstraint final {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(ExternalSystemConstraint)
/// Creates an empty constraint.
ExternalSystemConstraint()
: ExternalSystemConstraint("empty", {}, {}) {}
/// Creates a constraint with the given arguments.
/// The calc functions (other than calc_double) may be omitted.
ExternalSystemConstraint(
std::string description,
SystemConstraintBounds bounds,
SystemConstraintCalc<double> calc_double,
SystemConstraintCalc<AutoDiffXd> calc_autodiffxd = {},
SystemConstraintCalc<symbolic::Expression> calc_expression = {})
: description_(std::move(description)),
bounds_(std::move(bounds)),
calc_double_(std::move(calc_double)),
calc_autodiffxd_(std::move(calc_autodiffxd)),
calc_expression_(std::move(calc_expression)) {}
/// Creates a constraint based on generic lambda. This constraint will
/// supply Calc functions for Drake's default scalar types.
template <typename GenericSystemConstraintCalc>
static ExternalSystemConstraint MakeForAllScalars(
std::string description,
SystemConstraintBounds bounds,
GenericSystemConstraintCalc calc) {
return ExternalSystemConstraint(
std::move(description),
std::move(bounds),
calc, calc, calc);
}
/// Creates a constraint based on generic lambda. This constraint will
/// supply Calc functions for Drake's non-symbolic default scalar types.
template <typename GenericSystemConstraintCalc>
static ExternalSystemConstraint MakeForNonsymbolicScalars(
std::string description,
SystemConstraintBounds bounds,
GenericSystemConstraintCalc calc) {
return ExternalSystemConstraint(
std::move(description),
std::move(bounds),
calc, calc, {});
}
/// Returns a human-readable description of this constraint.
const std::string& description() const { return description_; }
/// Returns the bounds of this constraint (and whether it is an equality or
/// inequality constraint.)
const SystemConstraintBounds& bounds() const { return bounds_; }
/// Retrieves the evaluation function `value = f(system, context)` for this
/// constraint. The result may be a default-constructed (missing) function,
/// if the scalar type T is not supported by this constraint instance.
///
/// @tparam T denotes the scalar type of the System<T>.
template <typename T>
const SystemConstraintCalc<T>& get_calc() const {
return do_get_calc<T>();
}
private:
// This is the generic fallback implementation for unknown scalars. Below,
// we specialize this template function for the scalars that we know about
// (i.e., for when we can return references to our calc_foo_ member fields).
template <typename T>
const SystemConstraintCalc<T>& do_get_calc() const {
static const never_destroyed<SystemConstraintCalc<T>> empty;
return empty.access();
}
std::string description_;
SystemConstraintBounds bounds_;
SystemConstraintCalc<double> calc_double_;
SystemConstraintCalc<AutoDiffXd> calc_autodiffxd_;
SystemConstraintCalc<symbolic::Expression> calc_expression_;
};
template <> inline
const SystemConstraintCalc<double>&
ExternalSystemConstraint::do_get_calc() const {
return calc_double_;
}
template <> inline
const SystemConstraintCalc<AutoDiffXd>&
ExternalSystemConstraint::do_get_calc() const {
return calc_autodiffxd_;
}
template <> inline
const SystemConstraintCalc<symbolic::Expression>&
ExternalSystemConstraint::do_get_calc() const {
return calc_expression_;
}
} // namespace systems
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::SystemConstraint)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/context_base.cc | #include "drake/systems/framework/context_base.h"
#include <string>
#include <typeinfo>
#include "drake/common/unused.h"
namespace drake {
namespace systems {
std::unique_ptr<ContextBase> ContextBase::Clone() const {
if (!is_root_context()) {
throw std::logic_error(fmt::format(
"Context::Clone(): Cannot clone a non-root Context; "
"this Context was created by '{}'.", system_name_));
}
std::unique_ptr<ContextBase> clone_ptr(CloneWithoutPointers(*this));
ContextBase& clone = *clone_ptr;
// Create a complete mapping of tracker pointers.
DependencyTracker::PointerMap tracker_map;
BuildTrackerPointerMap(*this, clone, &tracker_map);
// Then do a pointer fixup pass.
FixContextPointers(*this, tracker_map, &clone);
return clone_ptr;
}
ContextBase::~ContextBase() {}
std::string ContextBase::GetSystemPathname() const {
const std::string parent_path = get_parent_base()
? get_parent_base()->GetSystemPathname()
: std::string();
return parent_path + internal::SystemMessageInterface::path_separator() +
GetSystemName();
}
FixedInputPortValue& ContextBase::FixInputPort(
int index, const AbstractValue& value) {
std::unique_ptr<FixedInputPortValue> fixed =
internal::ContextBaseFixedInputAttorney::CreateFixedInputPortValue(
value.Clone());
FixedInputPortValue& fixed_ref = *fixed;
SetFixedInputPortValue(InputPortIndex(index), std::move(fixed));
return fixed_ref;
}
void ContextBase::AddInputPort(
InputPortIndex expected_index, DependencyTicket ticket,
std::function<void(const AbstractValue&)> fixed_input_type_checker) {
DRAKE_DEMAND(expected_index.is_valid() && ticket.is_valid());
DRAKE_DEMAND(expected_index == num_input_ports());
DRAKE_DEMAND(input_port_tickets_.size() == input_port_values_.size());
DRAKE_DEMAND(input_port_tickets_.size() == input_port_type_checkers_.size());
if (!fixed_input_type_checker) {
fixed_input_type_checker = [](const AbstractValue&) {};
}
auto& ui_tracker = graph_.CreateNewDependencyTracker(
ticket, "u_" + std::to_string(expected_index));
input_port_values_.emplace_back(nullptr);
input_port_tickets_.emplace_back(ticket);
input_port_type_checkers_.emplace_back(std::move(fixed_input_type_checker));
auto& u_tracker = graph_.get_mutable_tracker(
DependencyTicket(internal::kAllInputPortsTicket));
u_tracker.SubscribeToPrerequisite(&ui_tracker);
}
void ContextBase::AddOutputPort(
OutputPortIndex expected_index, DependencyTicket ticket,
const internal::OutputPortPrerequisite& prerequisite) {
DRAKE_DEMAND(expected_index.is_valid() && ticket.is_valid());
DRAKE_DEMAND(expected_index == num_output_ports());
auto& yi_tracker = graph_.CreateNewDependencyTracker(
ticket, "y_" + std::to_string(expected_index));
output_port_tickets_.push_back(ticket);
// If no child subsystem was specified then this output port's dependency is
// resolvable within this subcontext so we can subscribe now. Inter-subcontext
// dependencies are set up by Diagram after all child intra-subcontext
// dependency trackers have been allocated.
if (!prerequisite.child_subsystem) {
yi_tracker.SubscribeToPrerequisite(
&get_mutable_tracker(prerequisite.dependency));
}
}
void ContextBase::SetFixedInputPortValue(
InputPortIndex index,
std::unique_ptr<FixedInputPortValue> port_value) {
DRAKE_DEMAND(0 <= index && index < num_input_ports());
DRAKE_DEMAND(port_value != nullptr);
// Fail-fast if the user supplied the wrong type or size.
input_port_type_checkers_[index](port_value->get_value());
DependencyTracker& port_tracker =
get_mutable_tracker(input_port_tickets_[index]);
FixedInputPortValue* old_value =
input_port_values_[index].get_mutable();
DependencyTicket ticket_to_use;
if (old_value != nullptr) {
// All the dependency wiring should be in place already.
ticket_to_use = old_value->ticket();
DRAKE_DEMAND(graph_.has_tracker(ticket_to_use));
DRAKE_ASSERT(graph_.get_tracker(ticket_to_use).HasSubscriber(port_tracker));
DRAKE_ASSERT(
port_tracker.HasPrerequisite(graph_.get_tracker(ticket_to_use)));
} else {
// Create a new tracker and subscribe to it.
DependencyTracker& value_tracker = graph_.CreateNewDependencyTracker(
"Value for fixed input port " + std::to_string(index));
ticket_to_use = value_tracker.ticket();
port_tracker.SubscribeToPrerequisite(&value_tracker);
}
// Fill in the FixedInputPortValue object and install it.
internal::ContextBaseFixedInputAttorney::set_ticket(port_value.get(),
ticket_to_use);
internal::ContextBaseFixedInputAttorney::set_owning_subcontext(
port_value.get(), this);
input_port_values_[index] = std::move(port_value);
// Invalidate anyone who cares about this input port.
graph_.get_tracker(ticket_to_use).NoteValueChange(start_new_change_event());
}
// Set up trackers for independent sources: time, accuracy, state, parameters,
// and input ports, and the predefined computations for derivatives, energy,
// and power. This code should set up everything listed in the
// internal::BuiltInTicketNumbers enum, and do so in the same order. The code
// for individual trackers below must be kept up to date with the API contracts
// for the corresponding tickets in SystemBase.
void ContextBase::CreateBuiltInTrackers() {
DependencyGraph& graph = graph_;
// This is the dummy "tracker" used for constants and anything else that has
// no dependencies on any Context source. Ignoring return value.
graph.CreateNewDependencyTracker(
DependencyTicket(internal::kNothingTicket), "nothing");
// Allocate trackers for time and accuracy.
auto& time_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kTimeTicket), "t");
auto& accuracy_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kAccuracyTicket), "accuracy");
// Allocate trackers for continuous state variables. These are independent
// in leaf systems but diagrams must add dependencies on their children's
// q, v, and z trackers respectively.
auto& q_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kQTicket), "q");
auto& v_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kVTicket), "v");
auto& z_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kZTicket), "z");
// Continuous state xc depends on q, v, and z.
auto& xc_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kXcTicket), "xc");
xc_tracker.SubscribeToPrerequisite(&q_tracker);
xc_tracker.SubscribeToPrerequisite(&v_tracker);
xc_tracker.SubscribeToPrerequisite(&z_tracker);
// Allocate the "all discrete variables" xd tracker. The associated System is
// responsible for allocating the individual discrete variable group xdᵢ
// trackers and subscribing this one to each of those. Diagrams must add
// dependencies on each child subcontext's xd tracker.
auto& xd_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kXdTicket), "xd");
// Allocate the "all abstract variables" xa tracker. The associated System is
// responsible for allocating the individual abstract variable xaᵢ
// trackers and subscribing this one to each of those. Diagrams must add
// dependencies on each child subcontext's xa tracker.
auto& xa_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kXaTicket), "xa");
// The complete state x={xc,xd,xa}.
auto& x_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kXTicket), "x");
x_tracker.SubscribeToPrerequisite(&xc_tracker);
x_tracker.SubscribeToPrerequisite(&xd_tracker);
x_tracker.SubscribeToPrerequisite(&xa_tracker);
// Allocate a tracker representing all the numeric parameters. The associated
// System is responsible for allocating the individual numeric parameters pnᵢ
// and subscribing the pn tracker to each one. Diagrams must add dependencies
// on each child subcontext's pn tracker.
auto& pn_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kPnTicket), "pn");
// Allocate a tracker representing all the abstract parameters. The associated
// System is responsible for allocating the individual numeric parameters paᵢ
// and subscribing the pa tracker to each one. Diagrams must add dependencies
// on each child subcontext's pa tracker.
auto& pa_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kPaTicket), "pa");
// Allocate a tracker representing all the parameters, p={pn,pa}.
auto& p_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kAllParametersTicket), "p");
p_tracker.SubscribeToPrerequisite(&pn_tracker);
p_tracker.SubscribeToPrerequisite(&pa_tracker);
// Allocate the "all input ports" u tracker. The associated System is
// responsible for allocating the individual input port uᵢ
// trackers and subscribing this one to each of those.
auto& u_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kAllInputPortsTicket), "u");
// Allocate the "all sources except input ports" tracker. The complete list of
// known sources is t,a,x,p. Note that cache entries are not included.
// Usually that won't matter since cache entries typically depend on at least
// one of t,a,x, or p so will be invalided for the same reason the current
// computation is. However, any dependency on a cache entry that depends only
// on input ports would have to be declared explicitly. (In practice specific
// input port trackers should be active with this one and logically that
// should take care of cache entries also -- otherwise there is a contributing
// input port that wasn't listed.)
auto& all_sources_except_input_ports_tracker =
graph.CreateNewDependencyTracker(
DependencyTicket(internal::kAllSourcesExceptInputPortsTicket),
"all sources except input ports");
all_sources_except_input_ports_tracker.SubscribeToPrerequisite(&time_tracker);
all_sources_except_input_ports_tracker.SubscribeToPrerequisite(
&accuracy_tracker);
all_sources_except_input_ports_tracker.SubscribeToPrerequisite(&x_tracker);
all_sources_except_input_ports_tracker.SubscribeToPrerequisite(&p_tracker);
// Allocate the "all sources" tracker. The complete list of known sources
// is t,a,x,p,u. Note that cache entries are not included. Under normal
// operation that doesn't matter because cache entries are invalidated only
// when one of these source values changes. Any computation that has
// declared "all sources" dependence will also have been invalidated for the
// same reason so doesn't need to explicitly list cache entries.
auto& all_sources_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kAllSourcesTicket), "all sources");
all_sources_tracker.SubscribeToPrerequisite(
&all_sources_except_input_ports_tracker);
all_sources_tracker.SubscribeToPrerequisite(&u_tracker);
// Allocate kinematics trackers to provide a level of abstraction from the
// specific state variables that are used to represent configuration and
// rate of change of configuration. For example, a kinematics cache entry
// should depend on configuration regardless of whether we use continuous or
// discrete variables. And it should be possible to switch between continuous
// and discrete representations without having to change the specified
// dependency, which remains "configuration" either way.
//
// See SystemBase::configuration_ticket() and kinematics_ticket() for the API
// contract that must be implemented here and make sure this code is kept
// up to date with that contract.
// TODO(sherm1) Should track changes to configuration and velocity regardless
// of how represented. See issue #9171. Until that is resolved, we must
// assume that "configuration" results (like end effector location and PE)
// can be affected by anything *except* time, v, and u; and "kinematics"
// results (like end effector velocity and KE) can be affected by anything
// except time and u.
auto& configuration_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kConfigurationTicket), "configuration");
// Compare with "all sources" above.
configuration_tracker.SubscribeToPrerequisite(&accuracy_tracker);
configuration_tracker.SubscribeToPrerequisite(&q_tracker); // Not v.
configuration_tracker.SubscribeToPrerequisite(&z_tracker);
configuration_tracker.SubscribeToPrerequisite(&xd_tracker);
configuration_tracker.SubscribeToPrerequisite(&xa_tracker);
configuration_tracker.SubscribeToPrerequisite(&p_tracker);
// This tracks configuration & velocity regardless of how represented.
auto& kinematics_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kKinematicsTicket), "kinematics");
kinematics_tracker.SubscribeToPrerequisite(&configuration_tracker);
kinematics_tracker.SubscribeToPrerequisite(&v_tracker);
// The following trackers are for well-known cache entries which don't
// exist yet at this point in Context creation. When the corresponding cache
// entry values are created (by SystemBase), these trackers will be subscribed
// to the Calc() method's prerequisites, and set to invalidate the cache entry
// value when the prerequisites change. Diagrams must add dependencies on
// their constituent subcontexts' corresponding trackers.
auto& xcdot_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kXcdotTicket), "xcdot");
unused(xcdot_tracker);
auto& pe_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kPeTicket), "PE");
unused(pe_tracker);
auto& ke_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kKeTicket), "KE");
unused(ke_tracker);
auto& pc_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kPcTicket), "pc");
unused(pc_tracker);
auto& pnc_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kPncTicket), "pnc");
unused(pnc_tracker);
auto& xd_unique_periodic_update_tracker = graph.CreateNewDependencyTracker(
DependencyTicket(internal::kXdUniquePeriodicUpdateTicket),
"xd_unique_periodic_update");
unused(xd_unique_periodic_update_tracker);
}
void ContextBase::BuildTrackerPointerMap(
const ContextBase& source, const ContextBase& clone,
DependencyTracker::PointerMap* tracker_map) {
// First map the pointers local to this context.
source.graph_.AppendToTrackerPointerMap(clone.get_dependency_graph(),
&*tracker_map);
// Then recursively ask our descendants to add their information to the map.
source.DoPropagateBuildTrackerPointerMap(clone, &*tracker_map);
}
void ContextBase::FixContextPointers(
const ContextBase& source, const DependencyTracker::PointerMap& tracker_map,
ContextBase* clone) {
// First repair pointers local to this context.
clone->graph_.RepairTrackerPointers(source.get_dependency_graph(),
tracker_map, clone, &clone->cache_);
// Cache and FixedInputs only need their back pointers set to `this`.
clone->cache_.RepairCachePointers(clone);
for (auto& fixed_input : clone->input_port_values_) {
if (fixed_input != nullptr) {
internal::ContextBaseFixedInputAttorney::set_owning_subcontext(
fixed_input.get_mutable(), clone);
}
}
// Then recursively ask our descendants to repair their pointers.
clone->DoPropagateFixContextPointers(source, tracker_map);
}
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/output_port_base.cc | #include "drake/systems/framework/output_port_base.h"
#include <utility>
namespace drake {
namespace systems {
OutputPortBase::OutputPortBase(
internal::SystemMessageInterface* owning_system,
internal::SystemId owning_system_id, std::string name,
OutputPortIndex index, DependencyTicket ticket, PortDataType data_type,
int size)
: PortBase("Output", owning_system, owning_system_id, std::move(name),
index, ticket, data_type, size) {}
OutputPortBase::~OutputPortBase() = default;
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/input_port_base.h | #pragma once
#include <memory>
#include <optional>
#include <string>
#include "drake/common/random.h"
#include "drake/systems/framework/context_base.h"
#include "drake/systems/framework/framework_common.h"
#include "drake/systems/framework/port_base.h"
#include "drake/systems/framework/value_producer.h"
namespace drake {
namespace systems {
/** An InputPort is a System resource that describes the kind of input a
System accepts, on a given port. It does not directly contain any runtime
input port data; that is always contained in a Context. The actual value will
be either the value of an OutputPort to which this is connected, or a fixed
value set in a Context.
%InputPortBase is the scalar type-independent part of an InputPort. */
class InputPortBase : public PortBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(InputPortBase)
~InputPortBase() override;
/** Returns the index of this input port within the owning System. For a
Diagram, this will be the index within the Diagram, _not_ the index within
a LeafSystem whose input port was exported. */
InputPortIndex get_index() const { return InputPortIndex(get_int_index()); }
/** Returns true if this is a random port. */
bool is_random() const { return static_cast<bool>(random_type_); }
/** Returns the RandomDistribution if this is a random port. */
std::optional<RandomDistribution> get_random_type() const {
return random_type_;
}
/** Allocates a concrete object suitable for holding the value to be provided
by this input port, and returns that as an AbstractValue. The returned object
will never be null. */
std::unique_ptr<AbstractValue> Allocate() const;
// A using-declaration adds these methods into our class's Doxygen.
// (Placed in an order that makes sense for the class's table of contents.)
using PortBase::get_name;
using PortBase::GetFullDescription;
using PortBase::get_data_type;
using PortBase::size;
using PortBase::ticket;
protected:
/** Signature of a function suitable for returning the cached value of a
particular input port. Will return nullptr if the port is not connected. */
using EvalAbstractCallback =
std::function<const AbstractValue*(const ContextBase&)>;
/** (Internal use only) Provides derived classes the ability to set the base
class members at construction.
@param owning_system
The System that owns this input port.
@param owning_system_id
The ID of owning_system.
@param name
A name for the port. Input port names should be non-empty and unique
within a single System.
@param index
The index to be assigned to this InputPort.
@param ticket
The DependencyTicket to be assigned to this InputPort.
@param data_type
Whether the port described is vector- or abstract-valued.
@param size
If the port described is vector-valued, the number of elements. Ignored for
abstract-valued ports.
@param random_type
Input ports may optionally be labeled as random, if the port is intended to
model a random-source "noise" or "disturbance" input. */
InputPortBase(
internal::SystemMessageInterface* owning_system,
internal::SystemId owning_system_id, std::string name,
InputPortIndex index, DependencyTicket ticket, PortDataType data_type,
int size, const std::optional<RandomDistribution>& random_type,
EvalAbstractCallback eval, ValueProducer::AllocateCallback alloc);
/** Evaluate this port; throws an exception if the port is not connected. */
const AbstractValue& DoEvalRequired(const ContextBase& context) const {
const AbstractValue* const result = eval_(context);
if (!result) { ThrowRequiredMissing(); }
return *result;
}
/** Evaluate this port; returns nullptr if the port is not connected. */
const AbstractValue* DoEvalOptional(const ContextBase& context) const {
return eval_(context);
}
/** Throws an exception that this port is not connected, but was expected to
be connected (i.e., an Eval caller expected that it was always connected). */
[[noreturn]] void ThrowRequiredMissing() const;
private:
const EvalAbstractCallback eval_;
const ValueProducer::AllocateCallback alloc_;
const std::optional<RandomDistribution> random_type_;
};
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/output_port_base.h | #pragma once
#include <string>
#include "drake/systems/framework/framework_common.h"
#include "drake/systems/framework/port_base.h"
namespace drake {
namespace systems {
/** %OutputPortBase handles the scalar type-independent aspects of an
OutputPort. An OutputPort belongs to a System and represents the properties of
one of that System's output ports. */
class OutputPortBase : public PortBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(OutputPortBase)
~OutputPortBase() override;
/** Returns the index of this output port within the owning System. For a
Diagram, this will be the index within the Diagram, _not_ the index within
the LeafSystem whose output port was forwarded. */
OutputPortIndex get_index() const {
return OutputPortIndex(get_int_index());
}
// A using-declaration adds these methods into our class's Doxygen.
// (Placed in an order that makes sense for the class's table of contents.)
using PortBase::get_name;
using PortBase::GetFullDescription;
using PortBase::get_data_type;
using PortBase::size;
using PortBase::ticket;
#ifndef DRAKE_DOXYGEN_CXX
// Internal use only. Returns the prerequisite for this output port -- either
// a cache entry in this System, or an output port of a child System.
internal::OutputPortPrerequisite GetPrerequisite() const {
return DoGetPrerequisite();
}
#endif
protected:
/** Provides derived classes the ability to set the base class members at
construction.
@param owning_system
The System that owns this output port.
@param owning_system_id
The ID of owning_system.
@param name
A name for the port. Must not be empty. Output port names should be unique
within a single System.
@param index
The index to be assigned to this OutputPort.
@param ticket
The DependencyTicket to be assigned to this OutputPort.
@param data_type
Whether the port described is vector or abstract valued.
@param size
If the port described is vector-valued, the number of elements expected,
otherwise ignored. */
OutputPortBase(
internal::SystemMessageInterface* owning_system,
internal::SystemId owning_system_id, std::string name,
OutputPortIndex index, DependencyTicket ticket, PortDataType data_type,
int size);
/** Concrete output ports must implement this to return the prerequisite
dependency ticket for this port, which may be in the current System or one
of its immediate child subsystems. */
virtual internal::OutputPortPrerequisite DoGetPrerequisite() const = 0;
};
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/model_values.cc | #include "drake/systems/framework/model_values.h"
#include <memory>
#include <vector>
namespace drake {
namespace systems {
namespace internal {
int ModelValues::size() const {
return static_cast<int>(values_.size());
}
void ModelValues::AddModel(
int index, std::unique_ptr<AbstractValue> model_value) {
// Grow the values_ so that our new model will live at @p index.
DRAKE_DEMAND(index >= size());
values_.resize(index);
values_.emplace_back(std::move(model_value));
}
std::unique_ptr<AbstractValue> ModelValues::CloneModel(int index) const {
if (index < size()) {
const AbstractValue* const model_value = values_[index].get();
if (model_value != nullptr) {
std::unique_ptr<AbstractValue> result = model_value->Clone();
DRAKE_DEMAND(result.get() != nullptr);
return result;
}
}
return nullptr;
}
} // namespace internal
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/cache_doxygen.h | /** @file
Doxygen-only documentation for @ref cache_design_notes. */
#pragma once
// Putting this document in drake::systems namespace makes the links work.
namespace drake {
namespace systems {
/** @defgroup cache_design_notes System Cache Design and Implementation Notes
@ingroup technical_notes
<!-- Fluff needed to keep Doxygen from misformatting due to quotes and
this being in the "autobrief" location. -->
@parblock <center>
\"There are only two hard things in computer science:<br>
<b>cache invalidation</b>, and naming things.\"<br>
-- Phil Karlton
</center>
@endparblock
<h2>Background</h2>
Drake System objects are used to specify the computational _structure_ of a
model to be studied. The actual _values_ during computation are stored in a
separate Context object. The %Context contains _source_ values (time,
parameters, states, input ports, accuracy) and _computed_ values (e.g.
derivatives, output ports) that depend on some or all of the source values. We
call the particular dependencies of a computed value its _prerequisites_. The
caching system described here manages computed values so that
- they are recomputed _only if_ a prerequisite has changed,
- they are marked out of date _whenever_ a prerequisite changes, and
- _every_ access to a computed value first ensures that it is up to date.
Accessing computed values is a critical, inner-loop activity during
simulation (many times per step) so the implementation is designed to provide
validity-checked access at minimal computational cost. Marking computations
out of date as prerequisites change is also frequent (at least once per step),
and potentially expensive, so must be efficient; the implementation goes to
great lengths to minimize the cost of that operation.
Caching is enabled by default in Drake. Methods are provided for disabling and
otherwise manipulating cache entries. See ContextBase for more information.
@anchor cache_design_goals
<h2>Design Constraints and Goals</h2>
Caching is entirely about performance. Hence, other than correctness, the
performance goals listed above are the primary architectural constraints. Other
goals also influenced the design. Here are the main goals in roughly descending
order of importance.
1. Must be correct (same result with caching on or off).
2. Must be fast.
3. Must preserve independence of System and Context objects (e.g., no
cross-pointers).
4. Should provide a simple conceptual model and API for users.
5. Should treat all value sources and dependencies in Drake uniformly.
6. Should be backwards compatible with the existing API.
In service of correctness and speed we need instrumentation for debugging and
performance measurement. For example, it should be possible to disable caching
to verify that the results don't change.
<b>Not a goal</b> for the initial implementation: automatic determination or
validation of dependency lists. Instead we rely on a conservative default
(depends on everything), and the ability to disable caching during testing.
Several follow-ons are possible to improve this:
- Runtime validation that computations only request sub-computations for which
they hold tickets (probably affordable only in Debug), and
- Use of symbolic expressions to calculate dependency lists automatically.
@anchor cache_design_architecture
<h2>Architecture</h2>
This is the basic architecture Drake uses to address the above design goals.
Every declared source and computed value is assigned a small-integer
DependencyTicket ("ticket") by the System (unique within a subsystem). The
Context contains corresponding DependencyTracker ("tracker") objects that manage
that value's downstream dependents and upstream prerequisites; these can be
accessed efficiently using the ticket. Cached computations are declared and
accessed through System-owned CacheEntry objects; their values are stored in
Context-owned CacheEntryValue objects whose validity with respect to source
values is tracked via their associated dependency trackers. Computed
values may in turn serve as source values for further computations. A change to
a source value invalidates any computed values that depend on it, recursively.
Such changes are initiated via %Context methods that send "out of date"
notifications to all downstream dependency trackers, which set the "out of date"
flag on cache entry values.
Any value contained in a Context may be exported via an output port that exposes
that value to downstream Systems; inter-subsystem dependencies are tracked using
the same mechanism as intra-subsystem dependencies. The current implementation
assigns a cache entry to each output port and requires copying %Context values
to that cache entry in order to expose them. This may be improved later to allow
values to be exposed directly without the intermediate cache entry, but the
semantics will be unchanged.
From a user perspective:
- Cache entries of arbitrary type are allocated to hold the results of all
significant computations, including built-ins like derivatives, energy,
and output ports as well as user-defined internal computations.
Prerequisites for these computations are explicitly noted at the time they
are declared; the default for user-defined cache entries is that they are
dependent on all sources.
- Computation is initiated when a result is requested via an "Eval" method, if
the result is not already up to date with respect to its prerequisites, which
are recursively obtained using their Eval methods.
- Cached results are automatically marked out of date when any of their
prerequisites may have changed.
Figure 1 below illustrates the computational structure of a Drake LeafSystem,
paired with its LeafContext. A Drake Diagram interconnects subsystems like
these by connecting output ports of subsystems to input ports of other
subsystems, and aggregates results such as derivative calculations. When
referring to individual Systems within a diagram, we use the terms
"subsystem" and "subcontext".
<!--
drake::systems::LeafSystem
┌─────────────────────────────────────┐
time ──────>│>──────┐ ┌───────┐ ···───│───> derivatives,
│ └─────────>│cache │──────────│───> energy, etc.
input ───>│>────────────────>│entry │ │
ports u ───>│ └───────┘ │──────┐
┌───>│ ┌───────┐ ···───│──────────> output
│ │ (Parameters p)──>│cache │──────────│──────────> ports y
│ │ (State x)───────>│entry │ ···───│──────────>
│ │ └───────┘ │ │
│ └─────────────────────────────────────┘ │
│ │ │
└<──────────│─(Fixed input) │
│ │
└─────────────────────────────────────┘
drake::systems::LeafContext
-->
@image html drake/systems/framework/images/system_context_cache.png "Figure 1: Computational structure of a Drake System."
In Figure 1 above, values are shown in gray like the Context to emphasize
that they are actually being stored in the %Context. The System can declare the
structure (colored borders), but does not contain the actual values. There can
also be values in the %Context of which the %System is unaware, including the
Fixed Input values as shown, and additional cached computations. Computed values
depend on source values, but are shown rounded on one side to emphasize that
they then become sources to downstream computations. The arrows as drawn should
be considered "is-prerequisite-of" edges; drawn in the reverse direction they
could be labeled "depends-on" edges.
@anchor cache_design_value_sources
<h2>%Value sources</h2>
When a cache entry is allocated, a list of prerequisite value sources is
provided by listing the dependency tickets for those sources. Only
_intra_-System dependencies are permitted; _inter_-System dependencies are
expressed by listing an input port as a prerequisite. There are six kinds of
value sources within a System's Context that can serve as prerequisites for
cached results within that %Context:
1. Time
2. Input ports
3. %Parameters (numerical and abstract)
4. %State (including continuous, discrete, and abstract variables)
5. Other cache entries
6. Accuracy
In addition, we support "fixed" input ports whose values are provided locally;
each such value is a value source, but is restricted to its corresponding
input port. Fixed values are semantically like additional %Parameters.
The Accuracy setting serves as a prerequisite for cached computations that are
computed approximately, to make sure they get recomputed if accuracy
requirements change. That is a technical detail not of interest to most users.
Its dependencies are handled similarly to time dependencies.
Each value source has a unique DependencyTicket that is used to locate its
DependencyTracker in the Context. Further granularity is provided for individual
value sources from the above categories. For example, configuration variables q
and velocity variables v have separate tickets. The ticket is used to designate
that source as a prerequisite for a cache entry. Tickets are assigned during
%System construction, whenever a component is specified that can serve as a
value source. Each value source's %DependencyTracker maintains a list of its
dependents (called "subscribers") so that it can perform "out of date"
notifications at run time, and is registered with its prerequisites so that it
can be properly notified when it may be invalid.
@anchor cache_design_output_ports
<h2>Output ports</h2>
An Output Port for a System is a "window" onto one of the value sources within
that %System's Context; that is the only way in which internal values of a
%System are exported to other Systems in a Diagram. That value source may be
- a cache entry allocated specifically for the output port, or
- a pre-existing source like a state subgroup or a cached value that has other
uses (not implemented yet), or
- an output port of a contained subsystem that has been exported.
An output port is a subscriber to its source, and a prerequisite to the
downstream input ports that it drives.
Every output port has an associated dependency ticket and tracker. If there is
a cache entry associated with the output port, it has its own ticket and tracker
to which the output port's tracker subscribes. A Diagram output port that is
exported from a contained subsystem still has its own tracker and subscribes
to the source output port's tracker.
@anchor cache_design_input_ports
<h2>Input ports</h2>
The value source for a subsystem input port is either
- an output port of a peer subsystem, or
- an input port of its parent Diagram, or
- a locally-stored value.
When an input port's value comes from a locally-stored value, we call it a
_fixed_ input port. Note that the fixed value is stored as a source value in the
Context. There is no corresponding entry in the System since providing values
for input ports is done exclusively via the %Context (see Figure 1 above).
Fixed input ports are treated identically to Parameters -- they may have
numerical or abstract value types; they may be changed with downstream
invalidation handled automatically; and their values do not change during a
time-advancing simulation. The values for fixed input ports are represented by
FixedInputPortValue objects, which have their own ticket and tracker to
which the corresponding input port subscribes.
Every input port has an associated dependency ticket and tracker. The tracker
is automatically subscribed to the input port's source's tracker.
@anchor cache_design_known_computations
<h2>Known computations</h2>
Certain computations are defined by the system framework so are automatically
assigned cache entries in the Context. Currently those are:
- Leaf output ports
- Time derivatives
- Power and energy (scalars)
Output ports that have their own Calc() methods are also automatically assigned
cache entries. Currently that applies to every leaf output port, but not to
diagram output ports.
@anchor cache_design_declaring
<h2>Declaring a cache entry</h2>
The API for declaring a cache entry is similar to the existing output port API.
A cache entry is defined by an Allocator() method returning an AbstractValue,
and a Calculator() method that takes a const (sub)Context and an AbstractValue
object of the type returned by the Allocator, and computes the correct value
given the %Context, and a list of prerequisites for the Calculator() function,
which are DependencyTickets for value sources in the same subcontext.
In the absence of explicit prerequisites, a cache entry is implicitly presumed
to be dependent on all possible values sources, so will be marked "out of date"
whenever accuracy, time, any input port, parameter, or state variable may have
a changed value. However, no implicit dependency on other cache entries
is assumed.
A typical declaration looks like this (in the constructor for a LeafSystem):
@code{.cpp}
const CacheEntry& pe_cache_entry =
DeclareCacheEntry("potential energy", 0.0,
&MySystem::CalcPotentialEnergy,
{all_parameters_ticket(), q_ticket()});
@endcode
That is a templatized "sugar" method where the allocator has been specified to
simply copy the given default value. The usual variants are available, as for
output port declarations.
See @ref DeclareCacheEntry_documentation "Declare cache entries" in SystemBase
for the full collection of variants.
If no dependencies are listed in a cache entry declaration, the default is
`{all_sources_ticket()}`. A cache entry that is truly independent of all sources
must explicitly say so by specifying `{nothing_ticket()}`. The available tickets
are defined in the SystemBase class; see
@ref DependencyTicket_documentation "Dependency tickets" there. Once declared,
the new CacheEntry object's CacheIndex and DependencyTicket can be obtained from
the entry if needed.
@anchor predefined_dependency_tickets
<h2>Predefined dependency tickets</h2>
The following dependency tickets are always available and are used to select
particular built-in dependency trackers. During System construction, an API user
can obtain the ticket number as the return value of methods
like `time_ticket()` that are provided by SystemBase. Add `_ticket()` to
the names in the first column of the table below to obtain the name of the
method to use in a prerequisite list as shown in the previous section. Ticket
methods followed by `(i)` in the table below are assigned as the indicated
resource is allocated; they do not have pre-assigned ticket numbers.
Ticket name |Abbr| Prerequisite indicated | Subscribes to
:--------------------|:--:|:-------------------------|:------------------
nothing | | has no prerequisite | —
time | t | simulated time | —
accuracy | a | accuracy setting | —
q | | continuous configuration | — ¹
v | | continuous velocity | — ¹
z | | misc. continuous state | — ¹
xc | | any continuous state | q v z
xd | | any discrete state | xdᵢ ∀i ¹ ²
xa | | any abstract state | xaᵢ ∀i ¹ ²
all_state | x | any state variable | xc xd xa
pn | | any numeric parameter | pnᵢ ∀i ¹ ²
pa | | any abstract parameter | paᵢ ∀i ¹ ²
all_parameters | p | any parameter p | pn pa
all_input_ports | u | any input port u | uᵢ ∀i
all_sources | | any change to %Context | t, a, x, p, u
configuration | | may affect pose or PE | q, z, a, p, xd, xa ³
kinematics | | may affect pose/motion | configuration, v ³
xcdot | | d/dt xc cached value | all_sources ¹ ⁵
pe | | potential energy | all_sources ¹ ⁵
ke | | kinetic energy | all_sources ¹ ⁵
pc | | conservative power | all_sources ¹ ⁵
pnc | | non-conservative power | all_sources ¹ ⁵
numeric_parameter(i) |pnᵢ | one numeric parameter | — ²
abstract_parameter(i)|paᵢ | one abstract parameter | — ²
discrete_state(i) |xdᵢ | one discrete state group | — ²
abstract_state(i) |xaᵢ | one abstract state | — ²
input_port(i) | uᵢ | one input port | peer, parent, or self ⁴
cache_entry(i) | cᵢ | one cache entry | explicit prerequisites
_Notes_
1. %Diagram has additional subscriptions for this tracker. See the
diagram-specific table in the
@ref caching_implementation_for_diagrams "Diagram-specific implementation"
section below.
2. There are no Diagram-level trackers for individual discrete/abstract
variables and numeric/abstract parameters.
3. Until issue [#9171](https://github.com/RobotLocomotion/drake/issues/9171)
is resolved we don't know which non-`v` state variables or which parameters
may affect kinematics, so we have to depend on all of them. However,
we do not propagate downstream notifications from state variable trackers
if a LeafContext does not have any of those state variables (see next section
for more information).
4. Input ports are dependent on the source that provides their values. That
may be the output port of a peer subsystem, the input port of the parent
diagram, or a locally-stored fixed input port value.
5. %Diagram currently subscribes to all_sources for this tracker, but in the
future it will only subscribe to the corresponding leaf trackers and no
longer subscribe to the Diagram's all_sources tracker. The leaf trackers
are sufficient on their own; the all_sources tracker is redundant.
Fixed input port values and output ports also have associated trackers. There
are methods for obtaining their tickets also but they are for internal use.
Only input ports may subscribe to those trackers, and that is handled by the
framework when the source for an input port is established.
@anchor cache_handling_composite_trackers
<h3>Handling of composite trackers</h3>
In the above table, entries that don't subscribe to anything ("—") are primary
source objects. For example, q is an independent state variable so its tracker
doesn't depend on anything else. Trackers like xc are composites, meaning they
are shorthand for a group of independent objects. xc is a tracker that
subscribes to the trackers for q, v, and z. Similarly xd stands for _all_
discrete state variables, and subscribes to each of the individual discrete
state trackers. That way if a q is modified, xc gets notified automatically.
Similarly a change to a single discrete state variable notifies xd. Once those
subscriptions are set up, no additional code is required in Drake to propagate
the notifications. As an optimization, we do not propagate notifications from
a state variable source tracker (q, v, z, xd, xa) in LeafContexts that do not
have any of that particular kind of state variable -- see issue
[#21133](https://github.com/RobotLocomotion/drake/issues/21133) for
why this is an important optimization.
Let's call the above the "forward" direction,where a source entity notifies a
subscribing composite entity.
More subtly, we also have to issue notifications in the "backward" direction.
That's because the Context provides methods like SetContinuousState() and
get_mutable_state() which effectively change a group of source objects. That
_could_ be handled with more subscriptions, at the cost of introducing cycles
into the dependency DAG (the "change event" would serve to break those cycles
during notification sweeps). Instead, since we always know the constituents at
the time a high-level modification request is made, we simply have bespoke code
that notifies the lowest-level constituents, then depend on the "forward"
direction subscriptions to get the composite trackers notified. See the
@ref context_base_change_notification_methods "notifications methods" in
ContextBase.
There are additional considerations for Diagram notifications; those are
discussed in the next section.
@anchor caching_implementation_for_diagrams
<h2>Diagram-specific implementation</h2>
Diagrams have some implementation details that don't apply to leaf systems.
Diagrams do not have their own state variables and parameters. Instead, their
states and parameters are references to their child subsystems' corresponding
states and parameters. This applies individually to each state and parameter
category. Diagram contexts do have trackers for their composite state and
parameters, and we must subscribe those to the corresponding child subsystem
trackers to ensure notifications propagate upward. Using capital letters to
denote the %Diagram composite trackers we have:
- Q = { qₛ : s ∈ 𝕊}
- V = { vₛ : s ∈ 𝕊}
- Z = { zₛ : s ∈ 𝕊}
- Xd = {xdₛ : s ∈ 𝕊}
- Xa = {xaₛ : s ∈ 𝕊}
- Pn = {pnₛ : s ∈ 𝕊}
- Pa = {paₛ : s ∈ 𝕊}
where 𝕊 is the set of immediate child subsystems of a %Diagram. Note that the
higher-level built-in trackers (all_state, all_parameters, configuration, etc.)
do not require special treatment. They simply subscribe to some or all of the
diagram source trackers listed above. They may also subscribe to time, accuracy,
and diagram-level input ports, none of which have dependencies on child
subsystems.
In addition to composite sources, Diagrams have a limited set of built-in
computations that are composites of their children's corresponding computations.
These are
- xcdot: composite time derivatives
- pe: summed potential energy
- ke: summed kinetic energy
- pc: summed conservative power
- pnc: summed non-conservative power
Each of these has a cache entry and an associated Calc() method that sets the
cache value by visiting the children to Eval() the corresponding quantities,
which are then combined to produce the composite quantity. xcdot is just a
container for the collected child quantities so just needs to ensure these are
up to date. Energy and power are scalars formed by summing the corresponding
scalar quantities from each child subsystem. To ensure that the diagram cache
entries are updated appropriately, they subscribe to the corresponding child
cache entries' dependency trackers. That way if a leaf quantity gets notified
of a leaf context change, any composite diagram quantity that needs that
leaf quantity is automatically notified also.
Modifications to state variables and parameters are always initiated through one
of the mutable methods of the Context class, but not necessarily at the root
DiagramContext of a %Context tree. Wherever a modification is initiated, we
must propagate that change in both directions: down to the child subsystems,
and up to the parent diagram. If someone changes the root diagram Q, that is
a change to each of its constituents qₛ, so we need to notify "down" to the
trackers for each of those, to make sure that subsystem s computations that
depend on qₛ will be properly marked "out of date". In the "up" direction, a
user who has access to one of the child subcontexts may initiate a change to a
qₛ; that should be propagated to the diagram Q since some part of it
has changed.
We implement the two directions asymmetrically. The "up" direction is
implemented simply by subscribing every diagram-level tracker to each of
its constituent object's trackers. That way any change to a constituent
notifies its parent via the usual subscriber notification code. Other than the
code to set up the subscriptions properly, there is no explicit code needed to
handle the "up" notifications.
See `%DiagramContext::SubscribeDiagramCompositeTrackersToChildrens()` for the
code that sets up these subscriptions. The following table shows the
Diagram-specific notifications and subscriptions:
Diagram tracker | Notifications sent ("down") | Subscribes to ("up")
:--------------------|:----------------------------|:---------------------
time | subsystem time | — ¹
accuracy | subsystem accuracy | — ¹
q | subsystem q | subsystem q
v | subsystem v | subsystem v
z | subsystem z | subsystem z
xd | subsystem xd | subsystem xd
xa | subsystem xa | subsystem xa
pn | subsystem pn | subsystem pn
pa | subsystem pa | subsystem pa
xcdot | — | subsystem xcdot
pe | — | subsystem pe
ke | — | subsystem ke
pc | — | subsystem pc
pnc | — | subsystem pnc
_Notes_
1. Time and accuracy can be set only in the root Context so can only
propagate downward.
The "down" direction _could_ have been handled via subscriptions also, at the
cost of introducing cycles into the dependency DAG (the "change event" would
serve to break those cycles during notification sweeps). Instead, the "down"
direction is implemented via bespoke code for the
@ref context_value_change_methods "Context modification methods"
that recursively visits each subcontext and executes the same modification
and out of date notifications there. That is similar to the treatment of local
composite trackers as discussed in
@ref cache_handling_composite_trackers "Handling of composite trackers"
above.
Note that a lower-level subcontext may also have fixed input port values, and
that a Diagram is completely unaware of any subsystem input ports whose values
have been fixed locally. When a subcontext fixed input port value changes, all
downstream computations are properly notified. For example, a subcontext
time derivative cache entry might depend on the fixed input port. As long as
the composite %Diagram time derivatives cache entry has subscribed to its
subsystems' time derivative cache entries, that change will also mark the
%Diagram time derivative out of date.
@anchor cache_trackers_figure
<h2>Tracker Subscription Summary</h2>
The figure below depicts the tracker subscriptions detailed in the above sections.
The arrow direction reads as "subscribes to (up)", i.e., "depends on":
- Folder-shaped nodes denote a Diagram tracker.
- Oval-shaped nodes denote a System tracker (the same for both LeafSystem or
Diagram).
- \b Black arrows are per the "Subscribes to" column in the "Predefined
dependency tickets" table.
- <span style="color:green">\b Green</span> arrows are per the input_port(i)
row in the same table. Unlike black arrows which are always subscribed,
the green arrows are only subscribed if that particular input port source
is in effect.
- <span style="color:blue">\b Blue</span> arrows are per the "Subscribes to"
column in the "Diagram-specific implementation" table.
- <span style="color:red">\b Red</span> arrows are the implicit subscriptions
implemented as "Context modification methods", per the "Notifications sent"
column in the "Diagram-specific implementation" table. When the diagram
quantity at the arrowhead is modified, the leaf quantities at the tail are
invalidated. The dotted line style denotes an implicit subscription, not
part of the tracker.
- <span style="border-bottom: 1px dashed">\b Dashed</span> lines indicate an
overly conservative subscription, planned to be made more precise in the
future. See the specific text in the prior sections for details.
- Doubled-line edges indicate that the item has a multiplicity of 0..many (∀i).
@dotfile systems/framework/images/cache_doxygen_trackers.dot
@anchor cache_design_implementation
<h2>Implementation</h2>
The logical cache entry object is split into two pieces to reflect the const
and mutable aspects. Given a CacheIndex, either piece may be obtained very
efficiently. The `const` part is a CacheEntry owned by the System, and consists
of:
- The Allocator() and Calculator() methods,
- a list of the Calculator's prerequisites, and
- the assigned dependency ticket for this cache entry.
The mutable part is a CacheEntryValue and associated DependencyTracker, both
owned by the Context. The CacheEntryValue is designed to optimize access
efficiency. It contains:
- an AbstractValue (obtained by invoking the Allocator()), and
- a flag indicating whether the value is out of date with respect to its
prerequisites, and
- a serial number that is incremented whenever the contained value changes, and
- the index to its DependencyTracker (i.e. the ticket).
When a prerequisite of a cache entry value changes, the associated
DependencyTracker sets its CacheEntryValue's "out of date" boolean `true`. When
a new value is computed and assigned the "out of date" boolean is cleared to
`false` by the code that performed the assignment. For debugging and performance
analysis, there is also a flag indicating whether caching has been disabled for
this entry, in which case the value is considered in need of recomputation every
time it is accessed. The out of date flag operates even when caching is disabled
but is ignored in that case by Eval() methods. The sense of these flags is
chosen so that only a single check that an int is zero is required to know that
a value may be returned without computation.
To summarize, the Eval() method for a CacheEntry operates as follows:
1. The CacheEntryValue is obtained using an array index into the Context's
cache.
2. If the value is out of date (or caching is disabled), call the
Calc() method to bring it up to date, and clear the "out of date"
boolean to false.
3. Return a reference to the cache entry's AbstractValue.
4. Downcast to the specified concrete type.
The DependencyTracker is designed to optimize invalidation efficiency.
It contains:
- Pointers to the prerequisite DependencyTrackers to which it has subscribed,
- pointers to downstream subscribers that have registered as dependents of
this cache entry,
- a pointer back to the CacheEntryValue for efficient invalidation, and
- bookkeeping and statistics-gathering members.
A prerequisite change to a particular value source works like this:
1. A "set" method or method providing mutable access to a source is invoked
on a Context.
2. A unique "change event" number N is assigned.
3. The ticket associated with the source is used to find its DependencyTracker
(just an array index operation).
4. The tracker's notification method is invoked, providing the change event
number N.
5. The tracker records N, and then notifies all trackers on its "subscribers"
list that change event N is occurring.
6. A notified tracker first checks its recorded change event number. If it is
already set to N then no further action is taken. Otherwise, it records N,
marks the associated cache entry (if any) out of date, and recursively
notifies all trackers on its "subscribers" list.
For efficiency, changes to multiple value sources can be grouped into the same
change event. Also, DependencyTracker subscriber lists and cache entry
references are just direct pointers (internal to the overall diagram Context)
so no lookups are required. This is very fast but makes cloning a %Context more
difficult because the pointers must be fixed up to point to corresponding
entities in the clone.
(Note that the "down" direction for Diagram notifications (as described above)
currently uses bespoke recursive code to notify all the subsystems. It would
likely be faster to use the subscription mechanism there also.)
@anchor cache_design_loose_ends
<h2>Notes & Loose Ends</h2>
<h3>No cross pointers</h3>
It is important to emphasize that a Context _never_ contains pointers to a
particular System. Thus the allocator and calculator functors for a cache entry
reside in the (sub)%System, not in the (sub)%Context. That implies that you
cannot evaluate a cache entry without both a %System and a %Context. It also
means you can use the same %Context with different Systems, and that a %Context
could be serialized then deserialized to use later, provided that a compatible
%System is available.
<h3>%System vs %Context</h3>
Drake's System framework provides a careful separation between the persistent
structure of a %System and its ephemeral values (Context). The structure is
represented in const objects derived from SystemBase, while the values are
represented in mutable objects derived from ContextBase. Generally that means
that what are logically single objects are split into two separate classes.
Since users are intended to interact primarily with %System objects, we use
the logical names for the %System half of the object, and more obscure names
for the %Context half that stores the runtime values. Here are some examples:
Logical object | System-side class | Context-side class
:------------------|:--------------------|:------------------
%System | System | Context
Output port | OutputPort | (cache entry)
Input port | InputPort | FixedInputPortValue
%Cache entry | CacheEntry | CacheEntryValue
Dependency tracker | (ticket only) | DependencyTracker
The System-side objects are used for declaring the computational structure of
a System; the Context-side objects are used to maintain correct current values.
For example, the necessary allocation and calculation methods for a cache entry
are stored in the System-side CacheEntry object in the %System, while the result
of executing those methods is stored in the corresponding CacheEntryValue object
in the Context.
<h3>Output Port cache entries</h3>
Each port and each cache entry is assigned a unique DependencyTracker object.
Output ports generally also have their own cache entries for storing their
values; that results in two DependencyTrackers -- the output port
%DependencyTracker lists its cache entry's %DependencyTracker as a prerequisite.
(TODO: In the initial implementation there will always be a cache entry
assigned for leaf output ports, but this design is intended to allow output
ports to forward from other sources without making unnecessary copies -- an
output port %DependencyTracker is still needed in those cases even though there
won't be an associated cache entry.)
The `Calc()` function and list of prerequisite supplied to the
@ref DeclareLeafOutputPort_documentation "declare output ports APIs" are
used directly to construct the output port's cache entry.
<h3>Declaring dependencies for built-in computations</h3>
The built-in computations like time derivatives, energy, and power are
associated with bespoke "Calc" methods which need to have known dependency
lists. Rather than add these with yet more System methods, we should consider
changing the API to define them analogously to the OutputPort and CacheEntry
declarations which accept Allocator() and Calculator() functors and a
dependency list for the Calculator(). Currently they are just defaulting to
"depends on everything".
See Drake issue [#9205](https://github.com/RobotLocomotion/drake/issues/9205)
on GitHub for a checklist of caching loose ends.
*/
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/leaf_system.cc | #include "drake/systems/framework/leaf_system.h"
#include <cmath>
#include <limits>
#include "absl/container/inlined_vector.h"
#include "drake/common/pointer_cast.h"
#include "drake/systems/framework/system_symbolic_inspector.h"
#include "drake/systems/framework/value_checker.h"
namespace drake {
namespace systems {
namespace {
// Returns the next sample time for the given @p attribute.
template <typename T>
T GetNextSampleTime(
const PeriodicEventData& attribute,
const T& current_time_sec) {
const double period = attribute.period_sec();
DRAKE_ASSERT(period > 0);
const double offset = attribute.offset_sec();
DRAKE_ASSERT(offset >= 0);
// If the first sample time hasn't arrived yet, then that is the next
// sample time.
if (current_time_sec < offset) {
return offset;
}
// Compute the index in the sequence of samples for the next time to sample,
// which should be greater than the present time.
using std::ceil;
const T offset_time = current_time_sec - offset;
const T next_k = ceil(offset_time / period);
T next_t = offset + next_k * period;
if (next_t <= current_time_sec) {
next_t = offset + (next_k + 1) * period;
}
DRAKE_ASSERT(next_t > current_time_sec);
return next_t;
}
} // namespace
template <typename T>
LeafSystem<T>::~LeafSystem() {}
template <typename T>
std::unique_ptr<CompositeEventCollection<T>>
LeafSystem<T>::DoAllocateCompositeEventCollection() const {
return std::make_unique<LeafCompositeEventCollection<T>>();
}
template <typename T>
std::unique_ptr<LeafContext<T>> LeafSystem<T>::AllocateContext() const {
return dynamic_pointer_cast_or_throw<LeafContext<T>>(
System<T>::AllocateContext());
}
template <typename T>
std::unique_ptr<EventCollection<PublishEvent<T>>>
LeafSystem<T>::AllocateForcedPublishEventCollection() const {
auto collection =
LeafEventCollection<PublishEvent<T>>::MakeForcedEventCollection();
if (this->forced_publish_events_exist())
collection->SetFrom(this->get_forced_publish_events());
return collection;
}
template <typename T>
std::unique_ptr<EventCollection<DiscreteUpdateEvent<T>>>
LeafSystem<T>::AllocateForcedDiscreteUpdateEventCollection() const {
auto collection =
LeafEventCollection<
DiscreteUpdateEvent<T>>::MakeForcedEventCollection();
if (this->forced_discrete_update_events_exist())
collection->SetFrom(this->get_forced_discrete_update_events());
return collection;
}
template <typename T>
std::unique_ptr<EventCollection<UnrestrictedUpdateEvent<T>>>
LeafSystem<T>::AllocateForcedUnrestrictedUpdateEventCollection() const {
auto collection =
LeafEventCollection<
UnrestrictedUpdateEvent<T>>::MakeForcedEventCollection();
if (this->forced_unrestricted_update_events_exist())
collection->SetFrom(this->get_forced_unrestricted_update_events());
return collection;
}
template <typename T>
std::unique_ptr<ContextBase> LeafSystem<T>::DoAllocateContext() const {
std::unique_ptr<LeafContext<T>> context = DoMakeLeafContext();
this->InitializeContextBase(&*context);
// Reserve parameters via delegation to subclass.
context->init_parameters(this->AllocateParameters());
// Reserve state via delegation to subclass.
context->init_continuous_state(this->AllocateContinuousState());
context->init_discrete_state(this->AllocateDiscreteState());
context->init_abstract_state(this->AllocateAbstractState());
// At this point this LeafContext is complete except possibly for
// inter-Context dependencies involving port connections to peers or
// parent. We can now perform some final sanity checks.
// The numeric vectors used for parameters and state must be contiguous,
// i.e., valid BasicVectors. In general, a Context's numeric vectors can be
// any kind of VectorBase including scatter-gather implementations like
// Supervector. But for a LeafContext, we only allow BasicVectors, which are
// guaranteed to have a contiguous storage layout.
// If xc is not BasicVector, the dynamic_cast will yield nullptr, and the
// invariant-checker will complain.
const VectorBase<T>* const xc = &context->get_continuous_state_vector();
internal::CheckBasicVectorInvariants(
dynamic_cast<const BasicVector<T>*>(xc));
// The discrete state must all be valid BasicVectors.
for (const BasicVector<T>* group :
context->get_state().get_discrete_state().get_data()) {
internal::CheckBasicVectorInvariants(group);
}
// The numeric parameters must all be valid BasicVectors.
const int num_numeric_parameters =
context->num_numeric_parameter_groups();
for (int i = 0; i < num_numeric_parameters; ++i) {
const BasicVector<T>& group = context->get_numeric_parameter(i);
internal::CheckBasicVectorInvariants(&group);
}
// Allow derived LeafSystem to validate allocated Context.
DoValidateAllocatedLeafContext(*context);
return context;
}
template <typename T>
void LeafSystem<T>::SetDefaultParameters(
const Context<T>& context, Parameters<T>* parameters) const {
this->ValidateContext(context);
this->ValidateCreatedForThisSystem(parameters);
for (int i = 0; i < parameters->num_numeric_parameter_groups(); i++) {
BasicVector<T>& p = parameters->get_mutable_numeric_parameter(i);
auto model_vector = model_numeric_parameters_.CloneVectorModel<T>(i);
if (model_vector != nullptr) {
p.SetFrom(*model_vector);
} else {
p.SetFromVector(VectorX<T>::Constant(p.size(), 1.0));
}
}
for (int i = 0; i < parameters->num_abstract_parameters(); i++) {
AbstractValue& p = parameters->get_mutable_abstract_parameter(i);
auto model_value = model_abstract_parameters_.CloneModel(i);
p.SetFrom(*model_value);
}
}
template <typename T>
void LeafSystem<T>::SetDefaultState(
const Context<T>& context, State<T>* state) const {
this->ValidateContext(context);
DRAKE_DEMAND(state != nullptr);
this->ValidateCreatedForThisSystem(state);
ContinuousState<T>& xc = state->get_mutable_continuous_state();
xc.SetFromVector(model_continuous_state_vector_->get_value());
DiscreteValues<T>& xd = state->get_mutable_discrete_state();
// Check that _if_ we have models, there is one for each group.
DRAKE_DEMAND(model_discrete_state_.num_groups() == 0 ||
model_discrete_state_.num_groups() == xd.num_groups());
if (model_discrete_state_.num_groups() > 0) {
xd.SetFrom(model_discrete_state_);
} else {
// With no model vector, we just zero all the discrete variables.
for (int i = 0; i < xd.num_groups(); i++) {
BasicVector<T>& s = xd.get_mutable_vector(i);
s.SetFromVector(VectorX<T>::Zero(s.size()));
}
}
AbstractValues& xa = state->get_mutable_abstract_state();
xa.SetFrom(AbstractValues(model_abstract_states_.CloneAllModels()));
}
template <typename T>
std::unique_ptr<ContinuousState<T>> LeafSystem<T>::AllocateTimeDerivatives()
const {
return AllocateContinuousState();
}
template <typename T>
std::unique_ptr<DiscreteValues<T>> LeafSystem<T>::AllocateDiscreteVariables()
const {
return AllocateDiscreteState();
}
namespace {
template <typename T>
std::unique_ptr<SystemSymbolicInspector> MakeSystemSymbolicInspector(
const System<T>& system) {
using symbolic::Expression;
// We use different implementations when T = Expression or not.
if constexpr (std::is_same_v<T, Expression>) {
return std::make_unique<SystemSymbolicInspector>(system);
} else {
std::unique_ptr<System<Expression>> converted = system.ToSymbolicMaybe();
if (converted) {
return std::make_unique<SystemSymbolicInspector>(*converted);
} else {
return nullptr;
}
}
}
} // namespace
template <typename T>
std::multimap<int, int> LeafSystem<T>::GetDirectFeedthroughs() const {
// The input -> output feedthrough result we'll return to the user.
std::multimap<int, int> feedthrough;
// The set of pairs for which we don't know an answer yet; currently all.
std::set<std::pair<InputPortIndex, OutputPortIndex>> unknown;
for (InputPortIndex u{0}; u < this->num_input_ports(); ++u) {
for (OutputPortIndex v{0}; v < this->num_output_ports(); ++v) {
unknown.emplace(std::make_pair(u, v));
}
}
// A System with no input ports or no output ports has no feedthrough!
if (unknown.empty())
return feedthrough; // Also empty.
// A helper function that removes an item from `unknown`.
const auto remove_unknown = [&unknown](const auto& in_out_pair) {
const auto num_erased = unknown.erase(in_out_pair);
DRAKE_DEMAND(num_erased == 1);
};
// A helper function that adds this in/out pair to the feedthrough result.
const auto add_to_feedthrough = [&feedthrough](const auto& in_out_pair) {
feedthrough.emplace(in_out_pair.first, in_out_pair.second);
};
// Ask the dependency graph if it can provide definitive information about
// the input/output pairs. If so remove those pairs from the `unknown` set.
auto context = this->AllocateContext();
const auto orig_unknown = unknown;
for (const auto& input_output : orig_unknown) {
// Get the CacheEntry associated with the output port in this pair.
const OutputPortBase& output = this->GetOutputPortBaseOrThrow(
__func__, input_output.second, /* warn_deprecated = */ false);
DRAKE_ASSERT(typeid(output) == typeid(LeafOutputPort<T>));
const auto& leaf_output = static_cast<const LeafOutputPort<T>&>(output);
const auto& cache_entry = leaf_output.cache_entry();
// If the user left the output prerequisites unspecified, then the cache
// entry tells us nothing useful about feedthrough for this pair.
if (cache_entry.has_default_prerequisites())
continue; // Leave this one "unknown".
// Probe the dependency path and believe the result.
const InputPortBase& input = this->GetInputPortBaseOrThrow(
__func__, input_output.first, /* warn_deprecated = */ false);
const auto& input_tracker = context->get_tracker(input.ticket());
auto& value = cache_entry.get_mutable_cache_entry_value(*context);
value.mark_up_to_date();
const int64_t change_event = context->start_new_change_event();
input_tracker.NoteValueChange(change_event);
if (value.is_out_of_date())
add_to_feedthrough(input_output);
// Regardless of the result we have all we need to know now.
remove_unknown(input_output);
// Undo the mark_up_to_date() we just did a few lines up. It shouldn't
// matter at all on this throwaway context, but perhaps it's best not
// to leave garbage values marked valid for longer than required.
value.mark_out_of_date();
}
// If the dependency graph resolved all pairs, no need for symbolic analysis.
if (unknown.empty())
return feedthrough;
// Otherwise, see if we can get a symbolic inspector to analyze them.
// If not, we have to assume they are feedthrough.
auto inspector = MakeSystemSymbolicInspector(*this);
for (const auto& input_output : unknown) {
if (!inspector || inspector->IsConnectedInputToOutput(
input_output.first, input_output.second)) {
add_to_feedthrough(input_output);
}
// No need to clean up the `unknown` set here.
}
return feedthrough;
}
template <typename T>
LeafSystem<T>::LeafSystem() : LeafSystem(SystemScalarConverter{}) {}
template <typename T>
LeafSystem<T>::LeafSystem(SystemScalarConverter converter)
: System<T>(std::move(converter)) {
this->set_forced_publish_events(
AllocateForcedPublishEventCollection());
this->set_forced_discrete_update_events(
AllocateForcedDiscreteUpdateEventCollection());
this->set_forced_unrestricted_update_events(
AllocateForcedUnrestrictedUpdateEventCollection());
per_step_events_.set_system_id(this->get_system_id());
initialization_events_.set_system_id(this->get_system_id());
model_discrete_state_.set_system_id(this->get_system_id());
}
template <typename T>
std::unique_ptr<LeafContext<T>> LeafSystem<T>::DoMakeLeafContext() const {
return std::make_unique<LeafContext<T>>();
}
template <typename T>
T LeafSystem<T>::DoCalcWitnessValue(
const Context<T>& context, const WitnessFunction<T>& witness_func) const {
DRAKE_DEMAND(this == &witness_func.get_system());
return witness_func.CalcWitnessValue(context);
}
template <typename T>
void LeafSystem<T>::AddTriggeredWitnessFunctionToCompositeEventCollection(
Event<T>* event, CompositeEventCollection<T>* events) const {
DRAKE_DEMAND(event != nullptr);
DRAKE_DEMAND(event->template has_event_data<WitnessTriggeredEventData<T>>());
DRAKE_DEMAND(events != nullptr);
event->AddToComposite(events);
}
template <typename T>
void LeafSystem<T>::DoCalcNextUpdateTime(
const Context<T>& context,
CompositeEventCollection<T>* events, T* time) const {
T min_time = std::numeric_limits<double>::infinity();
if (!periodic_events_.HasEvents()) {
*time = min_time;
return;
}
// Calculate which events to fire. Use an InlinedVector so that small-ish
// numbers of events can be processed without heap allocations. Our threshold
// for "small" is the same amount that would cause an EventCollection to
// grow beyond its pre-allocated size.
using NextEventsVector = absl::InlinedVector<
const Event<T>*, LeafEventCollection<PublishEvent<T>>::kDefaultCapacity>;
NextEventsVector next_events;
// Find the minimum next sample time across all declared periodic events,
// and store the set of declared events that will occur at that time.
// There are three lists to run through in a CompositeEventCollection.
// We give absl hidden visibility in Drake so can't capture the absl vector
// (otherwise we suffer a warning). Works as a parameter though.
auto scan_events = [&context, &min_time](const auto& typed_events,
NextEventsVector* event_list) {
for (const auto* event : typed_events.get_events()) {
const PeriodicEventData* event_data =
event->template get_event_data<PeriodicEventData>();
DRAKE_DEMAND(event_data != nullptr);
const T t = GetNextSampleTime(*event_data, context.get_time());
if (t < min_time) {
min_time = t;
*event_list = {event};
} else if (t == min_time) {
event_list->push_back(event);
}
}
};
scan_events(periodic_events_.get_publish_events(), &next_events);
scan_events(periodic_events_.get_discrete_update_events(), &next_events);
scan_events(periodic_events_.get_unrestricted_update_events(), &next_events);
// Write out the events that fire at min_time.
*time = min_time;
for (const Event<T>* event : next_events) {
event->AddToComposite(events);
}
}
template <typename T>
std::unique_ptr<ContinuousState<T>> LeafSystem<T>::AllocateContinuousState()
const {
DRAKE_DEMAND(model_continuous_state_vector_->size() ==
this->num_continuous_states());
const SystemBase::ContextSizes& sizes = this->get_context_sizes();
auto result = std::make_unique<ContinuousState<T>>(
model_continuous_state_vector_->Clone(),
sizes.num_generalized_positions, sizes.num_generalized_velocities,
sizes.num_misc_continuous_states);
result->set_system_id(this->get_system_id());
return result;
}
template <typename T>
std::unique_ptr<DiscreteValues<T>> LeafSystem<T>::AllocateDiscreteState()
const {
return model_discrete_state_.Clone();
}
template <typename T>
std::unique_ptr<AbstractValues> LeafSystem<T>::AllocateAbstractState() const {
return std::make_unique<AbstractValues>(
model_abstract_states_.CloneAllModels());
}
template <typename T>
std::unique_ptr<Parameters<T>> LeafSystem<T>::AllocateParameters() const {
std::vector<std::unique_ptr<BasicVector<T>>> numeric_params;
numeric_params.reserve(model_numeric_parameters_.size());
for (int i = 0; i < model_numeric_parameters_.size(); ++i) {
auto param = model_numeric_parameters_.CloneVectorModel<T>(i);
DRAKE_ASSERT(param != nullptr);
numeric_params.emplace_back(std::move(param));
}
std::vector<std::unique_ptr<AbstractValue>> abstract_params;
abstract_params.reserve(model_abstract_parameters_.size());
for (int i = 0; i < model_abstract_parameters_.size(); ++i) {
auto param = model_abstract_parameters_.CloneModel(i);
DRAKE_ASSERT(param != nullptr);
abstract_params.emplace_back(std::move(param));
}
auto result = std::make_unique<Parameters<T>>(std::move(numeric_params),
std::move(abstract_params));
result->set_system_id(this->get_system_id());
return result;
}
template <typename T>
int LeafSystem<T>::DeclareNumericParameter(const BasicVector<T>& model_vector) {
const NumericParameterIndex index(model_numeric_parameters_.size());
model_numeric_parameters_.AddVectorModel(index, model_vector.Clone());
MaybeDeclareVectorBaseInequalityConstraint(
"parameter " + std::to_string(index), model_vector,
[index](const Context<T>& context) -> const VectorBase<T>& {
const BasicVector<T>& result = context.get_numeric_parameter(index);
return result;
});
this->AddNumericParameter(index);
return index;
}
template <typename T>
int LeafSystem<T>::DeclareAbstractParameter(const AbstractValue& model_value) {
const AbstractParameterIndex index(model_abstract_parameters_.size());
model_abstract_parameters_.AddModel(index, model_value.Clone());
this->AddAbstractParameter(index);
return index;
}
template <typename T>
ContinuousStateIndex LeafSystem<T>::DeclareContinuousState(
int num_state_variables) {
const int num_q = 0, num_v = 0;
return DeclareContinuousState(num_q, num_v, num_state_variables);
}
template <typename T>
ContinuousStateIndex LeafSystem<T>::DeclareContinuousState(
int num_q, int num_v, int num_z) {
const int n = num_q + num_v + num_z;
return DeclareContinuousState(
BasicVector<T>(VectorX<T>::Zero(n)), num_q, num_v, num_z);
}
template <typename T>
ContinuousStateIndex LeafSystem<T>::DeclareContinuousState(
const BasicVector<T>& model_vector) {
const int num_q = 0, num_v = 0;
const int num_z = model_vector.size();
return DeclareContinuousState(model_vector, num_q, num_v, num_z);
}
template <typename T>
ContinuousStateIndex LeafSystem<T>::DeclareContinuousState(
const BasicVector<T>& model_vector, int num_q, int num_v, int num_z) {
DRAKE_DEMAND(model_vector.size() == num_q + num_v + num_z);
model_continuous_state_vector_ = model_vector.Clone();
// Note that only the last DeclareContinuousState() takes effect;
// we're not accumulating these as we do for discrete & abstract states.
SystemBase::ContextSizes& context_sizes =
this->get_mutable_context_sizes();
context_sizes.num_generalized_positions = num_q;
context_sizes.num_generalized_velocities = num_v;
context_sizes.num_misc_continuous_states = num_z;
MaybeDeclareVectorBaseInequalityConstraint(
"continuous state", model_vector,
[](const Context<T>& context) -> const VectorBase<T>& {
const ContinuousState<T>& state = context.get_continuous_state();
return state.get_vector();
});
return ContinuousStateIndex(0);
}
template <typename T>
DiscreteStateIndex LeafSystem<T>::DeclareDiscreteState(
const BasicVector<T>& model_vector) {
const DiscreteStateIndex index(model_discrete_state_.num_groups());
model_discrete_state_.AppendGroup(model_vector.Clone());
this->AddDiscreteStateGroup(index);
MaybeDeclareVectorBaseInequalityConstraint(
"discrete state", model_vector,
[index](const Context<T>& context) -> const VectorBase<T>& {
const BasicVector<T>& state = context.get_discrete_state(index);
return state;
});
return index;
}
template <typename T>
DiscreteStateIndex LeafSystem<T>::DeclareDiscreteState(
const Eigen::Ref<const VectorX<T>>& vector) {
return DeclareDiscreteState(BasicVector<T>(vector));
}
template <typename T>
DiscreteStateIndex LeafSystem<T>::DeclareDiscreteState(
int num_state_variables) {
DRAKE_DEMAND(num_state_variables >= 0);
return DeclareDiscreteState(VectorX<T>::Zero(num_state_variables));
}
template <typename T>
AbstractStateIndex LeafSystem<T>::DeclareAbstractState(
const AbstractValue& model_value) {
const AbstractStateIndex index(model_abstract_states_.size());
model_abstract_states_.AddModel(index, model_value.Clone());
this->AddAbstractState(index);
return index;
}
template <typename T>
InputPort<T>& LeafSystem<T>::DeclareVectorInputPort(
std::variant<std::string, UseDefaultName> name,
const BasicVector<T>& model_vector,
std::optional<RandomDistribution> random_type) {
const int size = model_vector.size();
const int index = this->num_input_ports();
model_input_values_.AddVectorModel(index, model_vector.Clone());
MaybeDeclareVectorBaseInequalityConstraint(
"input " + std::to_string(index), model_vector,
[this, index](const Context<T>& context) -> const VectorBase<T>& {
return this->get_input_port(index).
template Eval<BasicVector<T>>(context);
});
return this->DeclareInputPort(NextInputPortName(std::move(name)),
kVectorValued, size, random_type);
}
template <typename T>
InputPort<T>& LeafSystem<T>::DeclareVectorInputPort(
std::variant<std::string, UseDefaultName> name, int size,
std::optional<RandomDistribution> random_type) {
return DeclareVectorInputPort(std::move(name), BasicVector<T>(size),
random_type);
}
template <typename T>
InputPort<T>& LeafSystem<T>::DeclareAbstractInputPort(
std::variant<std::string, UseDefaultName> name,
const AbstractValue& model_value) {
const int next_index = this->num_input_ports();
model_input_values_.AddModel(next_index, model_value.Clone());
return this->DeclareInputPort(NextInputPortName(std::move(name)),
kAbstractValued, 0 /* size */);
}
template <typename T>
void LeafSystem<T>::DeprecateInputPort(
const InputPort<T>& port, std::string message) {
InputPort<T>& mutable_port = const_cast<InputPort<T>&>(
this->get_input_port(port.get_index()));
DRAKE_THROW_UNLESS(&mutable_port == &port);
DRAKE_THROW_UNLESS(mutable_port.get_deprecation() == std::nullopt);
mutable_port.set_deprecation({std::move(message)});
}
template <typename T>
LeafOutputPort<T>& LeafSystem<T>::DeclareVectorOutputPort(
std::variant<std::string, UseDefaultName> name,
const BasicVector<T>& model_vector,
typename LeafOutputPort<T>::CalcVectorCallback vector_calc_function,
std::set<DependencyTicket> prerequisites_of_calc) {
auto& port = CreateVectorLeafOutputPort(NextOutputPortName(std::move(name)),
model_vector.size(), MakeAllocateCallback(model_vector),
std::move(vector_calc_function), std::move(prerequisites_of_calc));
return port;
}
template <typename T>
LeafOutputPort<T>& LeafSystem<T>::DeclareAbstractOutputPort(
std::variant<std::string, UseDefaultName> name,
typename LeafOutputPort<T>::AllocCallback alloc_function,
typename LeafOutputPort<T>::CalcCallback calc_function,
std::set<DependencyTicket> prerequisites_of_calc) {
auto calc = [captured_calc = std::move(calc_function)](
const ContextBase& context_base, AbstractValue* result) {
const Context<T>& context = dynamic_cast<const Context<T>&>(context_base);
return captured_calc(context, result);
};
auto& port = CreateAbstractLeafOutputPort(
NextOutputPortName(std::move(name)),
ValueProducer(std::move(alloc_function), std::move(calc)),
std::move(prerequisites_of_calc));
return port;
}
template <typename T>
LeafOutputPort<T>& LeafSystem<T>::DeclareStateOutputPort(
std::variant<std::string, UseDefaultName> name,
ContinuousStateIndex state_index) {
DRAKE_THROW_UNLESS(state_index.is_valid());
DRAKE_THROW_UNLESS(state_index == 0);
return DeclareVectorOutputPort(
std::move(name), *model_continuous_state_vector_,
[](const Context<T>& context, BasicVector<T>* output) {
output->SetFrom(context.get_continuous_state_vector());
},
{this->xc_ticket()});
}
template <typename T>
LeafOutputPort<T>& LeafSystem<T>::DeclareStateOutputPort(
std::variant<std::string, UseDefaultName> name,
DiscreteStateIndex state_index) {
// DiscreteValues::get_vector already bounds checks the index, so we don't
// need to guard it here.
return DeclareVectorOutputPort(
std::move(name), this->model_discrete_state_.get_vector(state_index),
[state_index](const Context<T>& context, BasicVector<T>* output) {
output->SetFrom(context.get_discrete_state(state_index));
},
{this->discrete_state_ticket(state_index)});
}
template <typename T>
LeafOutputPort<T>& LeafSystem<T>::DeclareStateOutputPort(
std::variant<std::string, UseDefaultName> name,
AbstractStateIndex state_index) {
DRAKE_THROW_UNLESS(state_index.is_valid());
DRAKE_THROW_UNLESS(state_index >= 0);
DRAKE_THROW_UNLESS(state_index < this->model_abstract_states_.size());
return DeclareAbstractOutputPort(
std::move(name),
[this, state_index]() {
return this->model_abstract_states_.CloneModel(state_index);
},
[state_index](const Context<T>& context, AbstractValue* output) {
output->SetFrom(context.get_abstract_state().get_value(state_index));
},
{this->abstract_state_ticket(state_index)});
}
template <typename T>
void LeafSystem<T>::DeprecateOutputPort(
const OutputPort<T>& port, std::string message) {
OutputPort<T>& mutable_port = const_cast<OutputPort<T>&>(
this->get_output_port(port.get_index()));
DRAKE_THROW_UNLESS(&mutable_port == &port);
DRAKE_THROW_UNLESS(mutable_port.get_deprecation() == std::nullopt);
mutable_port.set_deprecation({std::move(message)});
}
template <typename T>
std::unique_ptr<WitnessFunction<T>> LeafSystem<T>::MakeWitnessFunction(
const std::string& description,
const WitnessFunctionDirection& direction_type,
std::function<T(const Context<T>&)> calc) const {
return std::make_unique<WitnessFunction<T>>(
this, this, description, direction_type, calc);
}
template <typename T>
std::unique_ptr<WitnessFunction<T>> LeafSystem<T>::MakeWitnessFunction(
const std::string& description,
const WitnessFunctionDirection& direction_type,
std::function<T(const Context<T>&)> calc,
const Event<T>& e) const {
return std::make_unique<WitnessFunction<T>>(
this, this, description, direction_type, calc, e.Clone());
}
template <typename T>
SystemConstraintIndex LeafSystem<T>::DeclareEqualityConstraint(
ContextConstraintCalc<T> calc, int count,
std::string description) {
return DeclareInequalityConstraint(
std::move(calc), SystemConstraintBounds::Equality(count),
std::move(description));
}
template <typename T>
SystemConstraintIndex LeafSystem<T>::DeclareInequalityConstraint(
ContextConstraintCalc<T> calc,
SystemConstraintBounds bounds,
std::string description) {
return this->AddConstraint(std::make_unique<SystemConstraint<T>>(
this, std::move(calc), std::move(bounds), std::move(description)));
}
template <typename T>
std::unique_ptr<AbstractValue> LeafSystem<T>::DoAllocateInput(
const InputPort<T>& input_port) const {
std::unique_ptr<AbstractValue> model_result =
model_input_values_.CloneModel(input_port.get_index());
if (model_result) {
return model_result;
}
if (input_port.get_data_type() == kVectorValued) {
return std::make_unique<Value<BasicVector<T>>>(input_port.size());
}
throw std::logic_error(fmt::format(
"System::AllocateInputAbstract(): a System with abstract input ports "
"must pass a model_value to DeclareAbstractInputPort; the port[{}] "
"named '{}' did not do so (System {})",
input_port.get_index(), input_port.get_name(),
this->GetSystemPathname()));
}
template <typename T>
std::map<PeriodicEventData, std::vector<const Event<T>*>,
PeriodicEventDataComparator>
LeafSystem<T>::DoMapPeriodicEventsByTiming(const Context<T>&) const {
std::map<PeriodicEventData, std::vector<const Event<T>*>,
PeriodicEventDataComparator>
periodic_events_map;
// Build a mapping from (offset,period) to the periodic events sharing
// that trigger. There are three lists of different types in a
// CompositeEventCollection; we use this generic lambda for all.
auto map_events = [&periodic_events_map](const auto& typed_events) {
for (const auto* event : typed_events.get_events()) {
const PeriodicEventData* event_data =
event->template get_event_data<PeriodicEventData>();
DRAKE_DEMAND(event_data != nullptr);
periodic_events_map[*event_data].push_back(event);
}
};
map_events(periodic_events_.get_publish_events());
map_events(periodic_events_.get_discrete_update_events());
map_events(periodic_events_.get_unrestricted_update_events());
return periodic_events_map;
}
template <typename T>
EventStatus LeafSystem<T>::DispatchPublishHandler(
const Context<T>& context,
const EventCollection<PublishEvent<T>>& events) const {
const LeafEventCollection<PublishEvent<T>>& leaf_events =
dynamic_cast<const LeafEventCollection<PublishEvent<T>>&>(events);
// This function shouldn't have been called if no publish events.
DRAKE_DEMAND(leaf_events.HasEvents());
EventStatus overall_status = EventStatus::DidNothing();
for (const PublishEvent<T>* event : leaf_events.get_events()) {
const EventStatus per_event_status = event->handle(*this, context);
overall_status.KeepMoreSevere(per_event_status);
// Unlike the discrete & unrestricted event policy, we don't stop handling
// publish events when one fails; we just report the first failure after all
// the publishes are done.
}
return overall_status;
}
template <typename T>
EventStatus LeafSystem<T>::DispatchDiscreteVariableUpdateHandler(
const Context<T>& context,
const EventCollection<DiscreteUpdateEvent<T>>& events,
DiscreteValues<T>* discrete_state) const {
const LeafEventCollection<DiscreteUpdateEvent<T>>& leaf_events =
dynamic_cast<const LeafEventCollection<DiscreteUpdateEvent<T>>&>(
events);
// This function shouldn't have been called if no discrete update events.
DRAKE_DEMAND(leaf_events.HasEvents());
// Must initialize the output argument with current discrete state contents.
discrete_state->SetFrom(context.get_discrete_state());
EventStatus overall_status = EventStatus::DidNothing();
for (const DiscreteUpdateEvent<T>* event : leaf_events.get_events()) {
const EventStatus per_event_status =
event->handle(*this, context, discrete_state);
overall_status.KeepMoreSevere(per_event_status);
if (overall_status.failed()) break; // Stop at the first disaster.
}
return overall_status;
}
template <typename T>
void LeafSystem<T>::DoApplyDiscreteVariableUpdate(
const EventCollection<DiscreteUpdateEvent<T>>& events,
DiscreteValues<T>* discrete_state, Context<T>* context) const {
DRAKE_ASSERT(
dynamic_cast<const LeafEventCollection<DiscreteUpdateEvent<T>>*>(
&events) != nullptr);
DRAKE_DEMAND(events.HasEvents());
// TODO(sherm1) Should swap rather than copy.
context->get_mutable_discrete_state().SetFrom(*discrete_state);
}
template <typename T>
EventStatus LeafSystem<T>::DispatchUnrestrictedUpdateHandler(
const Context<T>& context,
const EventCollection<UnrestrictedUpdateEvent<T>>& events,
State<T>* state) const {
const LeafEventCollection<UnrestrictedUpdateEvent<T>>& leaf_events =
dynamic_cast<const LeafEventCollection<UnrestrictedUpdateEvent<T>>&>(
events);
// This function shouldn't have been called if no unrestricted update events.
DRAKE_DEMAND(leaf_events.HasEvents());
// Must initialize the output argument with current state contents.
// TODO(sherm1) Shouldn't require preloading of the output state; better to
// note just the changes since usually only a small subset will be changed by
// the callback function.
state->SetFrom(context.get_state());
EventStatus overall_status = EventStatus::DidNothing();
for (const UnrestrictedUpdateEvent<T>* event : leaf_events.get_events()) {
const EventStatus per_event_status = event->handle(*this, context, state);
overall_status.KeepMoreSevere(per_event_status);
if (overall_status.failed()) break; // Stop at the first disaster.
}
return overall_status;
}
template <typename T>
void LeafSystem<T>::DoApplyUnrestrictedUpdate(
const EventCollection<UnrestrictedUpdateEvent<T>>& events,
State<T>* state, Context<T>* context) const {
DRAKE_ASSERT(
dynamic_cast<const LeafEventCollection<UnrestrictedUpdateEvent<T>>*>(
&events) != nullptr);
DRAKE_DEMAND(events.HasEvents());
// TODO(sherm1) Should swap rather than copy.
context->get_mutable_state().SetFrom(*state);
}
// The Diagram implementation of this method recursively visits sub-Diagrams
// until we get to this LeafSystem implementation, where we can actually look
// at the periodic discrete update Events. When no timing has yet been
// established (`timing` parameter is empty), the first LeafSystem
// to find a periodic discrete update event sets the timing for all the rest.
// After that every periodic discrete update event must have the same timing
// or this method throws an error message. If the timing is good, we return
// all the periodic discrete update events we find in this LeafSystem.
//
// Unit testing for this method is in diagram_test.cc where it is used in
// the leaf computation for the Diagram EvalUniquePeriodicDiscreteUpdate()
// recursion.
template <typename T>
void LeafSystem<T>::DoFindUniquePeriodicDiscreteUpdatesOrThrow(
const char* api_name, const Context<T>& context,
std::optional<PeriodicEventData>* timing,
EventCollection<DiscreteUpdateEvent<T>>* events) const {
unused(context);
auto& leaf_collection =
dynamic_cast<LeafEventCollection<DiscreteUpdateEvent<T>>&>(*events);
for (const DiscreteUpdateEvent<T>* event :
periodic_events_.get_discrete_update_events().get_events()) {
DRAKE_DEMAND(event->get_trigger_type() == TriggerType::kPeriodic);
const PeriodicEventData* const event_timing =
event->template get_event_data<PeriodicEventData>();
DRAKE_DEMAND(event_timing != nullptr);
if (!timing->has_value()) // First find sets the required timing.
*timing = *event_timing;
if (!(*event_timing == *(*timing))) {
throw std::logic_error(fmt::format(
"{}(): found more than one "
"periodic timing that triggers discrete update events. "
"Timings were (offset,period)=({},{}) and ({},{}).",
api_name, (*timing)->offset_sec(), (*timing)->period_sec(),
event_timing->offset_sec(), event_timing->period_sec()));
}
leaf_collection.AddEvent(*event);
}
}
template <typename T>
void LeafSystem<T>::DoGetPeriodicEvents(
const Context<T>&,
CompositeEventCollection<T>* events) const {
events->SetFrom(periodic_events_);
}
template <typename T>
void LeafSystem<T>::DoGetPerStepEvents(
const Context<T>&,
CompositeEventCollection<T>* events) const {
events->SetFrom(per_step_events_);
}
template <typename T>
void LeafSystem<T>::DoGetInitializationEvents(
const Context<T>&,
CompositeEventCollection<T>* events) const {
events->SetFrom(initialization_events_);
}
template <typename T>
LeafOutputPort<T>& LeafSystem<T>::CreateVectorLeafOutputPort(
std::string name,
int fixed_size,
typename LeafOutputPort<T>::AllocCallback vector_allocator,
typename LeafOutputPort<T>::CalcVectorCallback vector_calculator,
std::set<DependencyTicket> calc_prerequisites) {
// Construct a suitable type-erased cache calculator from the given
// BasicVector<T> calculator function.
auto cache_calc_function = [vector_calculator](
const ContextBase& context_base, AbstractValue* abstract) {
// Profiling revealed that it is too expensive to do a dynamic_cast here.
// A static_cast is safe as long as this is invoked only by methods that
// validate the SystemId, so that we know this Context is ours. As of this
// writing, only OutputPort::Eval and OutputPort::Calc invoke this and
// they do so safely.
auto& context = static_cast<const Context<T>&>(context_base);
// The abstract value must be a Value<BasicVector<T>>, even if the
// underlying object is a more-derived vector type.
auto* value = abstract->maybe_get_mutable_value<BasicVector<T>>();
// TODO(sherm1) Make this error message more informative by capturing
// system and port index info.
if (value == nullptr) {
throw std::logic_error(fmt::format(
"An output port calculation required a {} object for its result "
"but got a {} object instead.",
NiceTypeName::Get<Value<BasicVector<T>>>(),
abstract->GetNiceTypeName()));
}
vector_calculator(context, value);
};
// The allocator function is identical between output port and cache.
return CreateCachedLeafOutputPort(
std::move(name), fixed_size,
ValueProducer(
std::move(vector_allocator), std::move(cache_calc_function)),
std::move(calc_prerequisites));
}
template <typename T>
LeafOutputPort<T>& LeafSystem<T>::CreateAbstractLeafOutputPort(
std::string name,
ValueProducer producer,
std::set<DependencyTicket> calc_prerequisites) {
return CreateCachedLeafOutputPort(
std::move(name), std::nullopt /* size */, std::move(producer),
std::move(calc_prerequisites));
}
template <typename T>
LeafOutputPort<T>& LeafSystem<T>::CreateCachedLeafOutputPort(
std::string name, const std::optional<int>& fixed_size,
ValueProducer value_producer,
std::set<DependencyTicket> calc_prerequisites) {
DRAKE_DEMAND(!calc_prerequisites.empty());
// Create a cache entry for this output port.
const OutputPortIndex oport_index(this->num_output_ports());
CacheEntry& cache_entry = this->DeclareCacheEntry(
"output port " + std::to_string(oport_index) + "(" + name + ") cache",
std::move(value_producer), std::move(calc_prerequisites));
// Create and install the port. Note that it has a separate ticket from
// the cache entry; the port's tracker will be subscribed to the cache
// entry's tracker when a Context is created.
// TODO(sherm1) Use implicit_cast when available (from abseil).
auto port = internal::FrameworkFactory::Make<LeafOutputPort<T>>(
this, // implicit_cast<const System<T>*>(this)
this, // implicit_cast<const SystemBase*>(this)
this->get_system_id(),
std::move(name),
oport_index, this->assign_next_dependency_ticket(),
fixed_size.has_value() ? kVectorValued : kAbstractValued,
fixed_size.value_or(0),
&cache_entry);
LeafOutputPort<T>* const port_ptr = port.get();
this->AddOutputPort(std::move(port));
return *port_ptr;
}
template <typename T>
void LeafSystem<T>::MaybeDeclareVectorBaseInequalityConstraint(
const std::string& kind, const VectorBase<T>& model_vector,
const std::function<const VectorBase<T>&(const Context<T>&)>&
get_vector_from_context) {
Eigen::VectorXd lower_bound, upper_bound;
model_vector.GetElementBounds(&lower_bound, &upper_bound);
if (lower_bound.size() == 0 && upper_bound.size() == 0) {
return;
}
// `indices` contains the indices in model_vector that are constrained,
// namely either or both lower_bound(indices[i]) or upper_bound(indices[i])
// is not inf.
std::vector<int> indices;
indices.reserve(model_vector.size());
for (int i = 0; i < model_vector.size(); ++i) {
if (!std::isinf(lower_bound(i)) || !std::isinf(upper_bound(i))) {
indices.push_back(i);
}
}
if (indices.empty()) {
return;
}
Eigen::VectorXd constraint_lower_bound(indices.size());
Eigen::VectorXd constraint_upper_bound(indices.size());
for (int i = 0; i < static_cast<int>(indices.size()); ++i) {
constraint_lower_bound(i) = lower_bound(indices[i]);
constraint_upper_bound(i) = upper_bound(indices[i]);
}
this->DeclareInequalityConstraint(
[get_vector_from_context, indices](const Context<T>& context,
VectorX<T>* value) {
const VectorBase<T>& model_vec = get_vector_from_context(context);
value->resize(indices.size());
for (int i = 0; i < static_cast<int>(indices.size()); ++i) {
(*value)[i] = model_vec[indices[i]];
}
},
{constraint_lower_bound, constraint_upper_bound},
kind + " of type " + NiceTypeName::Get(model_vector));
}
} // namespace systems
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::LeafSystem)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/input_port.cc | #include "drake/systems/framework/input_port.h"
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::InputPort)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/continuous_state.cc | #include "drake/systems/framework/continuous_state.h"
#include <stdexcept>
#include <string>
#include <unordered_set>
#include <utility>
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/subvector.h"
namespace drake {
namespace systems {
template <typename T>
ContinuousState<T>::ContinuousState(std::unique_ptr<VectorBase<T>> state) {
state_ = std::move(state);
generalized_position_.reset(
new Subvector<T>(state_.get(), 0, 0));
generalized_velocity_.reset(
new Subvector<T>(state_.get(), 0, 0));
misc_continuous_state_.reset(
new Subvector<T>(state_.get(), 0, state_->size()));
DRAKE_ASSERT_VOID(DemandInvariants());
}
template <typename T>
ContinuousState<T>::ContinuousState(
std::unique_ptr<VectorBase<T>> state, int num_q, int num_v, int num_z) {
state_ = std::move(state);
if (state_->size() != num_q + num_v + num_z) {
throw std::out_of_range(
"Continuous state of size " + std::to_string(state_->size()) +
"cannot be partitioned as" + " q " + std::to_string(num_q) + " v " +
std::to_string(num_v) + " z " + std::to_string(num_z));
}
if (num_v > num_q) {
throw std::logic_error("Number of velocity variables " +
std::to_string(num_v) +
" must not exceed number of position variables " +
std::to_string(num_q));
}
generalized_position_.reset(new Subvector<T>(state_.get(), 0, num_q));
generalized_velocity_.reset(new Subvector<T>(state_.get(), num_q, num_v));
misc_continuous_state_.reset(
new Subvector<T>(state_.get(), num_q + num_v, num_z));
DRAKE_ASSERT_VOID(DemandInvariants());
}
template <typename T>
ContinuousState<T>::ContinuousState()
: ContinuousState(std::make_unique<BasicVector<T>>(0)) {}
template <typename T>
ContinuousState<T>::~ContinuousState() {}
template <typename T>
std::unique_ptr<ContinuousState<T>> ContinuousState<T>::Clone() const {
auto result = DoClone();
result->set_system_id(this->get_system_id());
return result;
}
template <typename T>
ContinuousState<T>::ContinuousState(
std::unique_ptr<VectorBase<T>> state,
std::unique_ptr<VectorBase<T>> q,
std::unique_ptr<VectorBase<T>> v,
std::unique_ptr<VectorBase<T>> z)
: state_(std::move(state)),
generalized_position_(std::move(q)),
generalized_velocity_(std::move(v)),
misc_continuous_state_(std::move(z)) {
DRAKE_ASSERT_VOID(DemandInvariants());
}
template <typename T>
std::unique_ptr<ContinuousState<T>> ContinuousState<T>::DoClone() const {
auto state = dynamic_cast<const BasicVector<T>*>(state_.get());
DRAKE_DEMAND(state != nullptr);
return std::make_unique<ContinuousState>(state->Clone(), num_q(), num_v(),
num_z());
}
template <typename T>
void ContinuousState<T>::DemandInvariants() const {
// Nothing is nullptr.
DRAKE_DEMAND(generalized_position_ != nullptr);
DRAKE_DEMAND(generalized_velocity_ != nullptr);
DRAKE_DEMAND(misc_continuous_state_ != nullptr);
// The sizes are consistent.
DRAKE_DEMAND(num_q() >= 0);
DRAKE_DEMAND(num_v() >= 0);
DRAKE_DEMAND(num_z() >= 0);
DRAKE_DEMAND(num_v() <= num_q());
const int num_total = (num_q() + num_v() + num_z());
DRAKE_DEMAND(state_->size() == num_total);
// The storage addresses of `state_` elements contain no duplicates.
std::unordered_set<const T*> state_element_pointers;
for (int i = 0; i < num_total; ++i) {
const T* element = &(state_->GetAtIndex(i));
state_element_pointers.emplace(element);
}
DRAKE_DEMAND(static_cast<int>(state_element_pointers.size()) == num_total);
// The storage addresses of (q, v, z) elements contain no duplicates, and
// are drawn from the set of storage addresses of `state_` elements.
// Therefore, the `state_` vector and (q, v, z) vectors form views into the
// same unique underlying data, just with different indexing.
std::unordered_set<const T*> qvz_element_pointers;
for (int i = 0; i < num_q(); ++i) {
const T* element = &(generalized_position_->GetAtIndex(i));
qvz_element_pointers.emplace(element);
DRAKE_DEMAND(state_element_pointers.contains(element));
}
for (int i = 0; i < num_v(); ++i) {
const T* element = &(generalized_velocity_->GetAtIndex(i));
qvz_element_pointers.emplace(element);
DRAKE_DEMAND(state_element_pointers.contains(element));
}
for (int i = 0; i < num_z(); ++i) {
const T* element = &(misc_continuous_state_->GetAtIndex(i));
qvz_element_pointers.emplace(element);
DRAKE_DEMAND(state_element_pointers.contains(element));
}
DRAKE_DEMAND(static_cast<int>(qvz_element_pointers.size()) == num_total);
}
} // namespace systems
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::ContinuousState)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/system_type_tag.cc | #include "drake/systems/framework/system_type_tag.h"
// This is an empty file to confirm that our header parses on its own.
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/subvector.h | #pragma once
#include <stdexcept>
#include <fmt/format.h>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/drake_throw.h"
#include "drake/systems/framework/vector_base.h"
namespace drake {
namespace systems {
/// Subvector is a concrete class template that implements
/// VectorBase by providing a sliced view of a VectorBase.
///
/// @tparam_default_scalar
template <typename T>
class Subvector final : public VectorBase<T> {
public:
// Subvector objects are neither copyable nor moveable.
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Subvector)
/// Constructs a subvector of vector that consists of num_elements starting
/// at first_element.
/// @param vector The vector to slice. Must not be nullptr. Must remain
/// valid for the lifetime of this object.
Subvector(VectorBase<T>* vector, int first_element, int num_elements)
: vector_(vector),
first_element_(first_element),
num_elements_(num_elements) {
if (vector_ == nullptr) {
throw std::logic_error("Cannot create Subvector of a nullptr vector.");
}
if ((first_element < 0) || (num_elements < 0) ||
(first_element + num_elements > vector->size())) {
throw std::logic_error(fmt::format(
"Subvector range [{}, {}) falls outside the valid range [{}, {}).",
first_element, first_element + num_elements, 0, vector->size()));
}
}
int size() const final { return num_elements_; }
private:
const T& DoGetAtIndexUnchecked(int index) const final {
DRAKE_ASSERT(index < size());
return (*vector_)[first_element_ + index];
}
T& DoGetAtIndexUnchecked(int index) final {
DRAKE_ASSERT(index < size());
return (*vector_)[first_element_ + index];
}
const T& DoGetAtIndexChecked(int index) const final {
if (index >= size()) { this->ThrowOutOfRange(index); }
return (*vector_)[first_element_ + index];
}
T& DoGetAtIndexChecked(int index) final {
if (index >= size()) { this->ThrowOutOfRange(index); }
return (*vector_)[first_element_ + index];
}
VectorBase<T>* vector_{nullptr};
int first_element_{0};
int num_elements_{0};
};
} // namespace systems
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::Subvector)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/dependency_tracker.cc | #include "drake/systems/framework/dependency_tracker.h"
#include <algorithm>
#include "drake/common/unused.h"
namespace drake {
namespace systems {
namespace {
// For debugging use, provide an indent of 2*depth characters.
std::string Indent(int depth) {
std::string s;
for (int i = 0; i < depth; ++i) s += "| ";
return s;
}
} // namespace
// Our associated value has initiated a change (e.g. the associated value is
// time and someone advanced time). Short circuit if this is part of a change
// event that we have already heard about. Otherwise, let the subscribers know
// that things have changed. Update statistics.
void DependencyTracker::NoteValueChange(int64_t change_event) const {
DRAKE_LOGGER_DEBUG("Tracker '{}' value change event {} ...",
GetPathDescription(), change_event);
DRAKE_ASSERT(change_event > 0);
++num_value_change_notifications_received_;
if (last_change_event_ == change_event || suppress_notifications_) {
++num_ignored_notifications_;
DRAKE_LOGGER_DEBUG(
"... ignoring repeated or suppressed value change notification.");
return;
}
last_change_event_ = change_event;
NotifySubscribers(change_event, 0);
}
// A prerequisite says it has changed. Short circuit if we've already heard
// about this change event. Otherwise, invalidate the associated cache entry and
// then pass on the bad news to our subscribers. Update statistics.
void DependencyTracker::NotePrerequisiteChange(
int64_t change_event,
const DependencyTracker& prerequisite,
int depth) const {
unused(Indent); // Avoid warning in non-Debug builds.
DRAKE_LOGGER_DEBUG(
"{}Tracker '{}': prerequisite '{}' changed (event {}) ...",
Indent(depth), GetPathDescription(), prerequisite.GetPathDescription(),
change_event);
DRAKE_ASSERT(change_event > 0);
DRAKE_ASSERT(HasPrerequisite(prerequisite)); // Expensive.
++num_prerequisite_notifications_received_;
if (last_change_event_ == change_event || suppress_notifications_) {
++num_ignored_notifications_;
DRAKE_LOGGER_DEBUG(
"{}... ignoring repeated or suppressed prereq change notification.",
Indent(depth));
return;
}
last_change_event_ = change_event;
// Invalidate associated cache entry value if any.
cache_value_->mark_out_of_date();
// Follow up with downstream subscribers.
NotifySubscribers(change_event, depth);
}
void DependencyTracker::NotifySubscribers(int64_t change_event,
int depth) const {
DRAKE_LOGGER_DEBUG("{}... {} downstream subscribers.{}", Indent(depth),
num_subscribers(),
num_subscribers() > 0 ? " Notifying:" : "");
DRAKE_ASSERT(change_event > 0);
DRAKE_ASSERT(depth >= 0);
for (const DependencyTracker* subscriber : subscribers_) {
DRAKE_ASSERT(subscriber != nullptr);
DRAKE_LOGGER_DEBUG("{}->{}", Indent(depth),
subscriber->GetPathDescription());
subscriber->NotePrerequisiteChange(change_event, *this, depth + 1);
}
num_downstream_notifications_sent_ += num_subscribers();
}
// Given a DependencyTracker that is supposed to be a prerequisite to this
// one, subscribe to it. This is done only at Context allocation and copying
// so we can afford Release-build checks and general mucking about to make
// runtime execution fast.
void DependencyTracker::SubscribeToPrerequisite(
DependencyTracker* prerequisite) {
DRAKE_DEMAND(prerequisite != nullptr);
DRAKE_LOGGER_DEBUG("Tracker '{}' subscribing to prerequisite '{}'",
GetPathDescription(), prerequisite->GetPathDescription());
// Make sure we haven't already added this prerequisite.
DRAKE_ASSERT(!HasPrerequisite(*prerequisite)); // Expensive.
prerequisites_.push_back(prerequisite);
prerequisite->AddDownstreamSubscriber(*this);
}
void DependencyTracker::AddDownstreamSubscriber(
const DependencyTracker& subscriber) {
DRAKE_LOGGER_DEBUG("Tracker '{}' adding subscriber '{}'",
GetPathDescription(), subscriber.GetPathDescription());
// Make sure we haven't already added this subscriber.
DRAKE_ASSERT(!HasSubscriber(subscriber)); // Expensive.
// Subscriber must have *already* recorded this prerequisite.
DRAKE_ASSERT(subscriber.HasPrerequisite(*this)); // Expensive.
subscribers_.push_back(&subscriber);
}
namespace {
// Convenience function for linear search of a vector to see if it contains
// a given value.
template <typename T>
bool Contains(const T& value, const std::vector<T>& to_search) {
return std::find(to_search.begin(), to_search.end(), value)
!= to_search.end();
}
// Look for the given value and erase it. Fail if not found.
template <typename T>
void Remove(const T& value, std::vector<T>* to_search) {
auto found = std::find(to_search->begin(), to_search->end(), value);
DRAKE_DEMAND(found != to_search->end());
to_search->erase(found);
}
} // namespace
// Remove a subscription that we made earlier.
void DependencyTracker::UnsubscribeFromPrerequisite(
DependencyTracker* prerequisite) {
DRAKE_DEMAND(prerequisite != nullptr);
DRAKE_LOGGER_DEBUG("Tracker '{}' unsubscribing from prerequisite '{}'",
GetPathDescription(), prerequisite->GetPathDescription());
// Make sure we have already added this prerequisite.
DRAKE_ASSERT(HasPrerequisite(*prerequisite)); // Expensive.
Remove<const DependencyTracker*>(prerequisite, &prerequisites_);
prerequisite->RemoveDownstreamSubscriber(*this);
}
void DependencyTracker::RemoveDownstreamSubscriber(
const DependencyTracker& subscriber) {
DRAKE_LOGGER_DEBUG("Tracker '{}' removing subscriber '{}'",
GetPathDescription(), subscriber.GetPathDescription());
// Make sure we already added this subscriber.
DRAKE_ASSERT(HasSubscriber(subscriber)); // Expensive.
// Subscriber must have *already* removed this prerequisite.
DRAKE_ASSERT(!subscriber.HasPrerequisite(*this)); // Expensive.
Remove<const DependencyTracker*>(&subscriber, &subscribers_);
}
std::string DependencyTracker::GetPathDescription() const {
return GetSystemPathname() + ":" + description();
}
bool DependencyTracker::HasPrerequisite(
const DependencyTracker& prerequisite) const {
return Contains(&prerequisite, prerequisites_);
}
bool DependencyTracker::HasSubscriber(
const DependencyTracker& subscriber) const {
return Contains(&subscriber, subscribers_);
}
void DependencyTracker::ThrowIfBadDependencyTracker(
const internal::ContextMessageInterface* owning_subcontext,
const CacheEntryValue* cache_value) const {
if (owning_subcontext_ == nullptr) {
// Can't use FormatName() here because that depends on us having an owning
// context to talk to.
throw std::logic_error("DependencyTracker(" + description() + ")::" +
__func__ +
"(): tracker has no owning subcontext.");
}
if (owning_subcontext && owning_subcontext_ != owning_subcontext) {
throw std::logic_error(FormatName(__func__) + "wrong owning subcontext.");
}
if (cache_value_ == nullptr) {
throw std::logic_error(
FormatName(__func__) +
"no associated cache entry value (should at least be a dummy).");
}
if (cache_value && cache_value_ != cache_value) {
throw std::logic_error(FormatName(__func__) +
"wrong associated cache entry value.");
}
if (!ticket_.is_valid()) {
throw std::logic_error(FormatName(__func__) +
"dependency ticket invalid.");
}
if (last_change_event_ < -1) {
throw std::logic_error(FormatName(__func__) +
"last change event has an absurd value.");
}
if (num_value_change_notifications_received_ < 0 ||
num_prerequisite_notifications_received_ < 0 ||
num_ignored_notifications_ < 0 ||
num_downstream_notifications_sent_ < 0) {
throw std::logic_error(FormatName(__func__) +
"a counter has a negative value.");
}
}
void DependencyTracker::RepairTrackerPointers(
const DependencyTracker& source,
const DependencyTracker::PointerMap& tracker_map,
const internal::ContextMessageInterface* owning_subcontext, Cache* cache) {
DRAKE_DEMAND(owning_subcontext != nullptr);
DRAKE_DEMAND(cache != nullptr);
owning_subcontext_ = owning_subcontext;
// Set the cache entry pointer to refer to the new cache, either to a real
// CacheEntryValue or the cache's dummy value.
DRAKE_DEMAND(has_associated_cache_entry_ ==
source.has_associated_cache_entry_);
if (has_associated_cache_entry_) {
const CacheIndex source_index(source.cache_value_->cache_index());
cache_value_ = &cache->get_mutable_cache_entry_value(source_index);
DRAKE_LOGGER_DEBUG(
"Cloned tracker '{}' repairing cache entry {} invalidation to {:#x}.",
GetPathDescription(), source.cache_value_->cache_index(),
size_t(cache_value_));
} else {
cache_value_ = &cache->dummy_cache_entry_value();
}
// Set the subscriber pointers.
DRAKE_DEMAND(num_subscribers() == source.num_subscribers());
for (int i = 0; i < num_subscribers(); ++i) {
DRAKE_ASSERT(subscribers_[i] == nullptr);
auto map_entry = tracker_map.find(source.subscribers()[i]);
DRAKE_DEMAND(map_entry != tracker_map.end());
subscribers_[i] = map_entry->second;
}
// Set the prerequisite pointers.
DRAKE_DEMAND(num_prerequisites() == source.num_prerequisites());
for (int i = 0; i < num_prerequisites(); ++i) {
DRAKE_ASSERT(prerequisites_[i] == nullptr);
auto map_entry = tracker_map.find(source.prerequisites()[i]);
DRAKE_DEMAND(map_entry != tracker_map.end());
prerequisites_[i] = map_entry->second;
}
// This should never happen, but ...
ThrowIfBadDependencyTracker();
}
void DependencyGraph::AppendToTrackerPointerMap(
const DependencyGraph& clone,
DependencyTracker::PointerMap* tracker_map) const {
DRAKE_DEMAND(tracker_map != nullptr);
DRAKE_DEMAND(clone.trackers_size() == trackers_size());
for (DependencyTicket ticket(0); ticket < trackers_size(); ++ticket) {
if (!has_tracker(ticket))
continue;
const bool added = tracker_map->emplace(&get_tracker(ticket),
&clone.get_tracker(ticket)).second;
DRAKE_DEMAND(added); // Shouldn't have been there.
}
}
void DependencyGraph::RepairTrackerPointers(
const DependencyGraph& source,
const DependencyTracker::PointerMap& tracker_map,
const internal::ContextMessageInterface* owning_subcontext,
Cache* new_cache) {
DRAKE_DEMAND(owning_subcontext != nullptr);
owning_subcontext_ = owning_subcontext;
for (DependencyTicket ticket(0); ticket < trackers_size(); ++ticket) {
if (!has_tracker(ticket))
continue;
get_mutable_tracker(ticket).RepairTrackerPointers(
source.get_tracker(ticket), tracker_map, owning_subcontext, new_cache);
}
}
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/context.h | #pragma once
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_throw.h"
#include "drake/common/fmt.h"
#include "drake/common/value.h"
#include "drake/systems/framework/context_base.h"
#include "drake/systems/framework/parameters.h"
#include "drake/systems/framework/state.h"
namespace drake {
namespace systems {
/** %Context is an abstract class template that represents all the typed values
that are used in a System's computations: time, numeric-valued input ports,
numerical state, and numerical parameters. There are also type-erased
abstract state variables, abstract-valued input ports, abstract parameters,
and a double accuracy setting. The framework provides two concrete
subclasses of %Context: LeafContext (for leaf Systems) and DiagramContext
(for composite System Diagrams). Users are forbidden to extend
DiagramContext and are discouraged from subclassing LeafContext.
A %Context is designed to be used only with the System that created it.
Data encapsulated with State and Parameter objects can be copied between
contexts for compatible systems with some restrictions. For details, see
@ref system_compatibility.
@tparam_default_scalar */
template <typename T>
class Context : public ContextBase {
public:
/** @name Does not allow copy, move, or assignment. */
//@{
// Copy constructor is protected for use in implementing Clone().
Context(Context&&) = delete;
Context& operator=(const Context&) = delete;
Context& operator=(Context&&) = delete;
//@}
/** @name Accessors for locally-stored values
Methods in this group provide `const` access to values stored locally in
this %Context. The available values are:
- time
- state
- parameters
- accuracy
Fixed input port values and cached values (including output port values)
are also stored in the %Context but are accessed indirectly via methods
like SystemBase::EvalInputValue(), through CacheEntry and OutputPort
objects, or via the FixedInputPortValue object that was returned when
an input port value was set.
@see FixInputPort() */
//@{
/** Returns the current time in seconds.
@see SetTime() */
const T& get_time() const { return time_; }
/** Returns a const reference to the whole State. */
const State<T>& get_state() const {
return do_access_state();
}
/** Returns true if the Context has no state. */
bool is_stateless() const {
const int nxc = num_continuous_states();
const int nxd = num_discrete_state_groups();
const int nxa = num_abstract_states();
return nxc == 0 && nxd == 0 && nxa == 0;
}
/** Returns true if the Context has continuous state, but no discrete or
abstract state. */
bool has_only_continuous_state() const {
const int nxc = num_continuous_states();
const int nxd = num_discrete_state_groups();
const int nxa = num_abstract_states();
return nxc > 0 && nxd == 0 && nxa == 0;
}
/** Returns true if the Context has discrete state, but no continuous or
abstract state. */
bool has_only_discrete_state() const {
const int nxc = num_continuous_states();
const int nxd = num_discrete_state_groups();
const int nxa = num_abstract_states();
return nxd > 0 && nxc == 0 && nxa == 0;
}
/** Returns the total dimension of all of the basic vector states (as if they
were muxed).
@throws std::exception if the system contains any abstract state. */
int num_total_states() const {
DRAKE_THROW_UNLESS(num_abstract_states() == 0);
int count = num_continuous_states();
for (int i = 0; i < num_discrete_state_groups(); i++)
count += get_discrete_state(i).size();
return count;
}
/** Returns the number of continuous state variables `xc = {q, v, z}`. */
int num_continuous_states() const {
return get_continuous_state().size();
}
/** Returns a const reference to the continuous component of the state,
which may be of size zero. */
const ContinuousState<T>& get_continuous_state() const {
return get_state().get_continuous_state();
}
/** Returns a reference to the continuous state vector, devoid of second-order
structure. The vector may be of size zero. */
const VectorBase<T>& get_continuous_state_vector() const {
return get_continuous_state().get_vector();
}
/** Returns the number of vectors (groups) in the discrete state. */
int num_discrete_state_groups() const {
return get_state().get_discrete_state().num_groups();
}
/** Returns a reference to the entire discrete state, which may consist of
multiple discrete state vectors (groups). */
const DiscreteValues<T>& get_discrete_state() const {
return get_state().get_discrete_state();
}
/** Returns a reference to the _only_ discrete state vector. The vector may be
of size zero.
@pre There is only one discrete state group. */
const BasicVector<T>& get_discrete_state_vector() const {
return get_discrete_state().get_vector();
}
/** Returns a const reference to group (vector) `index` of the discrete
state.
@pre `index` must identify an existing group. */
const BasicVector<T>& get_discrete_state(int index) const {
const DiscreteValues<T>& xd = get_state().get_discrete_state();
return xd.get_vector(index);
}
/** Returns the number of elements in the abstract state. */
int num_abstract_states() const {
return get_state().get_abstract_state().size();
}
/** Returns a const reference to the abstract component of the state, which
may be of size zero. */
const AbstractValues& get_abstract_state() const {
return get_state().get_abstract_state();
}
/** Returns a const reference to the abstract component of the
state at `index`.
@pre `index` must identify an existing element.
@pre the abstract state's type must match the template argument. */
template <typename U>
const U& get_abstract_state(int index) const {
const AbstractValues& xa = get_state().get_abstract_state();
return xa.get_value(index).get_value<U>();
}
/** Returns the accuracy setting (if any). Note that the return type is
`optional<double>` rather than the double value itself.
@see SetAccuracy() for details. */
const std::optional<double>& get_accuracy() const { return accuracy_; }
/** Returns a const reference to this %Context's parameters. */
const Parameters<T>& get_parameters() const { return *parameters_; }
/** Returns the number of vector-valued parameters. */
int num_numeric_parameter_groups() const {
return parameters_->num_numeric_parameter_groups();
}
/** Returns a const reference to the vector-valued parameter at `index`.
@pre `index` must identify an existing parameter. */
const BasicVector<T>& get_numeric_parameter(int index) const {
return parameters_->get_numeric_parameter(index);
}
/** Returns the number of abstract-valued parameters. */
int num_abstract_parameters() const {
return get_parameters().num_abstract_parameters();
}
/** Returns a const reference to the abstract-valued parameter at `index`.
@pre `index` must identify an existing parameter. */
const AbstractValue& get_abstract_parameter(int index) const {
return get_parameters().get_abstract_parameter(index);
}
//@}
/** @anchor context_value_change_methods
@name Methods for changing locally-stored values
Methods in this group allow changes to the values of quantities stored
locally in this %Context. The changeable quantities are:
- time
- state
- parameters
- accuracy
- fixed input port values
Expensive computations may be performed that depend on the current values
of some or all of the above quantities. For efficiency, we save the
results of such computations in the %Context so that we can reuse
those results without unnecessary recomputation.
<h3>Terminology</h3>
We call a quantity whose value is needed in order to perform a particular
computation a _prerequisite_ of that computation, and we say that the
computation is a _dependent_ of that prerequisite. If a prerequisite's
value changes, a result computed using an earlier value is _invalid_; we
say that the prerequisite change _invalidates_ that result, and that the
result is _out of date_ with respect to its prerequisites. It is important
to note that the result of one computation can serve as a prerequisite to
another computation; we call the dependent computation a _downstream_
computation and the prerequisite an _upstream_ computation.
<h3>Caching</h3>
Drake provides a caching system that is responsible for
- storing computed results in the %Context's _cache_, and
- ensuring that any cached result that _may_ be invalid is marked
"out of date".
The correctness of results reported by Drake depends critically on _every_
cached result being correctly flagged as up to date or out of date with
respect to its prerequisites. Only when it is known _for certain_ that
a result is valid can it be marked up to date. Access to cached results
is performed through `Eval()` methods that return up to date results
immediately but initiate recomputation first for results marked out of
date. The methods in the group below are responsible for ensuring that
cached results are marked out of date whenever a prerequisite value may
have changed. These methods _do not_ initiate such recomputation
themselves.
@sa @ref cache_design_notes
<h3>Invalidation and "out of date" notification</h3>
Each method in this group provides the ability to change a particular
subset of the available quantities listed above. This triggers "out of
date" notifications to the cached results for all computations for which
any element of that subset is a prerequisite. Such notifications
propagate to downstream computations, whose cached results may reside
anywhere in the full Diagram context tree of which this %Context is a
part. That ensures that "out of date" flags are set correctly for the
cached results of all computations that could be made invalid by a value
change to any of the affected subset of quantities. We call this
process a _notification sweep_.
<h3>Which method to use</h3>
Choose the most-specific method in this group that permits you to perform
the modifications you need. For example, if you need to modify only
continuous state variables, don't use a method that provides mutable
access to the whole state. That provides two performance advantages:
- fewer downstream computations need to be marked out of date, making the
notification sweep faster, and
- fewer results will need to be recomputed later.
The methods below may be grouped into "safe" methods that only set values
in the context, and "dangerous" methods return a mutable reference. In
addition, the `FixInputPort` methods return an object that has its own
dangerous methods (see FixedInputPortValue). Prefer the safe methods when
possible.
<h4>Safe "Set" methods</h4>
The `set` and `Set` methods that don't also contain `GetMutable` in their
names are safe in the sense that they perform both the "mark as out of
date" notification sweep through dependent cached results and the update
to the local quantity's value. They do not return a reference to the value
object. Using these methods ensures that no value modification can occur
without an appropriate notification sweep. Also, these methods can be used
to perform multiple changes at once (say time and state), requiring only a
single notification sweep, and _may_ perform optimizations to avoid
notifications in case some of the new values are the same as the old ones.
<h4>Dangerous "GetMutable" methods</h4>
@anchor dangerous_get_mutable
The `GetMutable` methods return a mutable reference to the local value
object within this %Context. The notification sweep is done prior to
returning that reference. You can then use the reference to make the
desired change. Note that with these methods we do not actually know
whether dependent computations are invalid; that depends what you do with
the reference once you have it. Nevertheless you will pay the cost of
the notifications sweep immediately and the cost of recomputation later
when you ask for the value. So don't call one of these methods unless
you are certain you will be writing through the returned reference.
You _must not_ hold on to the returned reference expecting
to be able to make subsequent changes, because those changes can't be
seen by the framework and thus will not cause the necessary notification
sweep to occur. Instead, request the mutable reference again when
you need it so that the necessary notification sweep can be performed.
The dangerous methods are segregated into their own
@ref dangerous_context_value_change_methods "documentation group".
<h4>Advanced context-modifying methods</h4>
Specialized methods are provided for expert users implementing
integrators and other state-modifying solvers. Those are segregated to
a separate
@ref advanced_context_value_change_methods "documentation group".
<!-- TODO(sherm1) The "get mutable" methods here should be moved to
the Advanced section also once we have civilized replacements
for them. -->
<h3>Implementation note</h3>
Each method in the group below guarantees to mark as out of date any
dependents of the quantities to which it permits modification, including
all downstream dependents. However, the current implementations may also
perform some unnecessary notifications. If so, that is noted in the method
documentation. You should still use the most-specific available method so
that you will benefit from later improvements that result in fewer
notifications. */
//@{
// TODO(sherm1) Consider whether this should avoid the notification sweep
// if the new time is the same as the old time.
/** Sets the current time in seconds. Sends out of date notifications for all
time-dependent computations (at least if the time has actually changed).
Time must have the same value in every subcontext within the same Diagram
context tree so may only be modified at the root context of the tree.
@throws std::exception if this is not the root context. */
void SetTime(const T& time_sec);
// TODO(sherm1) Add more-specific state "set" methods for smaller
// state groupings (issue #9205).
/** Sets the continuous state to `xc`, including q, v, and z partitions.
The supplied vector must be the same size as the existing continuous
state. Sends out of date notifications for all continuous-state-dependent
computations. */
void SetContinuousState(const Eigen::Ref<const VectorX<T>>& xc) {
get_mutable_continuous_state().SetFromVector(xc);
}
// TODO(sherm1) Consider whether this should avoid invalidation of
// time-dependent quantities if the new time is the same as the old time.
/** Sets time to `time_sec` and continuous state to `xc`. Performs a single
notification sweep to avoid duplicate notifications for computations that
depend on both time and state.
@throws std::exception if this is not the root context. */
void SetTimeAndContinuousState(const T& time_sec,
const Eigen::Ref<const VectorX<T>>& xc) {
VectorBase<T>& xc_vector =
SetTimeAndGetMutableContinuousStateHelper(__func__, time_sec)
.get_mutable_vector();
xc_vector.SetFromVector(xc);
}
/** Sets the discrete state to `xd`, assuming there is just one discrete
state group. The supplied vector must be the same size as the existing
discrete state. Sends out of date notifications for all
discrete-state-dependent computations. Use the other signature for this
method if you have multiple discrete state groups.
@pre There is exactly one discrete state group.
@pydrake_mkdoc_identifier{single_group} */
void SetDiscreteState(const Eigen::Ref<const VectorX<T>>& xd) {
if (num_discrete_state_groups() != 1) {
throw std::logic_error(fmt::format(
"Context::SetDiscreteState(): expected exactly 1 discrete state "
"group but there were {} groups. Use the other signature if "
"you have multiple groups.", num_discrete_state_groups()));
}
SetDiscreteState(DiscreteStateIndex(0), xd);
}
// TODO(sherm1) Invalidate only dependents of this one discrete group.
/** Sets the discrete state group indicated by `group_index` to `xd`.
The supplied vector `xd` must be the same size as the existing discrete
state group. Sends out of date notifications for all computations that
depend on this discrete state group.
@pre `group_index` identifies an existing group.
@note Currently notifies dependents of _all_ groups.
@pydrake_mkdoc_identifier{select_one_group} */
void SetDiscreteState(int group_index,
const Eigen::Ref<const VectorX<T>>& xd) {
get_mutable_discrete_state(DiscreteStateIndex(group_index))
.SetFromVector(xd);
}
/** Sets all the discrete state variables in this %Context from a
compatible DiscreteValues object.
@throws std::exception unless the number of groups and size of each group
of `xd` matches those in this %Context.
@pydrake_mkdoc_identifier{set_everything} */
void SetDiscreteState(const DiscreteValues<T>& xd) {
get_mutable_discrete_state().SetFrom(xd);
}
// TODO(sherm1) Invalidate only dependents of this one abstract variable.
/** Sets the value of the abstract state variable selected by `index`. Sends
out of date notifications for all computations that depend on that
abstract state variable. The template type will be inferred and need not
be specified explicitly.
@pre `index` must identify an existing abstract state variable.
@pre the abstract state's type must match the template argument.
@note Currently notifies dependents of _any_ abstract state variable. */
template <typename ValueType>
void SetAbstractState(int index, const ValueType& value) {
get_mutable_abstract_state<ValueType>(index) = value;
}
// TODO(xuchenhan-tri) Should treat fixed input port values the same as
// parameters.
// TODO(xuchenhan-tri) Change the name of this method to be more inclusive
// since it also set fixed input port values (pending above TODO).
/** Copies all state and parameters in `source`, where numerical values are
of type `U`, to `this` context. Time and accuracy are unchanged in `this`
context, which means that this method can be called on a subcontext.
Sends out of date notifications for all dependent computations in `this`
context.
@note Currently does not copy fixed input port values from `source`.
See System::FixInputPortsFrom() if you want to copy those.
@see SetTimeStateAndParametersFrom() if you want to copy time and accuracy
along with state and parameters to a root context. */
template <typename U>
void SetStateAndParametersFrom(const Context<U>& source) {
// A single change event for all these changes is faster than doing
// each separately.
const int64_t change_event = this->start_new_change_event();
SetStateAndParametersFromHelper(source, change_event);
}
// TODO(xuchenhan-tri) Should treat fixed input port values the same as
// parameters.
// TODO(xuchenhan-tri) Change the name of this method to be more inclusive
// since it also copies accuracy (now) and fixed input port values
// (pending above TODO).
/** Copies time, accuracy, all state and all parameters in `source`, where
numerical values are of type `U`, to `this` context. This method can only
be called on root contexts because time and accuracy are copied.
Sends out of date notifications for all dependent computations in this
context.
@throws std::exception if this is not the root context.
@note Currently does not copy fixed input port values from `source`.
See System::FixInputPortsFrom() if you want to copy those.
@see SetStateAndParametersFrom() if you want to copy state and parameters
to a non-root context. */
template <typename U>
void SetTimeStateAndParametersFrom(const Context<U>& source) {
ThrowIfNotRootContext(__func__, "Time");
// A single change event for all these changes is faster than doing
// each separately.
const int64_t change_event = this->start_new_change_event();
// These two both set the value and perform notifications.
const scalar_conversion::ValueConverter<T, U> converter;
PropagateTimeChange(this, converter(source.get_time()), {}, change_event);
PropagateAccuracyChange(this, source.get_accuracy(), change_event);
// Set state and parameters (and fixed input port values pending TODO) from
// the source.
SetStateAndParametersFromHelper(source, change_event);
}
// Allow access to the base class method (takes an AbstractValue).
using ContextBase::FixInputPort;
// TODO(sherm1) Consider whether to avoid invalidation if the new value is
// the same as the old one.
/** Records the user's requested accuracy, which is a unit-less quantity
designed for use with simulation and other numerical studies. Since
accuracy is unit-less, algorithms and systems are free to interpret this
quantity as they wish. The intention is that more computational work is
acceptable as the accuracy setting is tightened (set closer to zero). If
no accuracy is requested, computations are free to choose suitable
defaults, or to refuse to proceed without an explicit accuracy setting.
The accuracy of a complete simulation or other numerical study depends on
the accuracy of _all_ contributing computations, so it is important that
each computation is done in accordance with the requested accuracy. Some
examples of where this is needed:
- Error-controlled numerical integrators use the accuracy setting to
decide what step sizes to take.
- The Simulator employs a numerical integrator, but also uses accuracy to
decide how precisely to isolate witness function zero crossings.
- Iterative calculations reported as results or cached internally depend
on accuracy to decide how strictly to converge the results. Examples of
these are: constraint projection, calculation of distances between
smooth shapes, and deformation calculations for soft contact.
The common thread among these examples is that they all share the
same %Context, so by keeping accuracy here it can be used effectively to
control all accuracy-dependent computations.
Any accuracy-dependent computation in this Context and its subcontexts may
be invalidated by a change to the accuracy setting, so out of date
notifications are sent to all such computations (at least if the accuracy
setting has actually changed). Accuracy must have the same value in every
subcontext within the same context tree so may only be modified at the
root context of a tree.
Requested accuracy is stored in the %Context for two reasons:
- It permits all computations performed over a System to see the _same_
accuracy request since accuracy is stored in one shared place, and
- it allows us to notify accuracy-dependent cached results that they are
out of date when the accuracy setting changes.
@throws std::exception if this is not the root context. */
void SetAccuracy(const std::optional<double>& accuracy);
//@}
/** @anchor dangerous_context_value_change_methods
@name Dangerous methods for changing locally-stored values
Methods in this group return mutable references into the state and
parameters in the %Context. Although they do issue out-of-date
notifications when invoked, so you can safely write to the reference
_once_, there is no way to issue notifications if you make subsequent
changes. So you _must not_ hold these references for writing. See
@ref dangerous_get_mutable "Dangerous GetMutable methods"
for more information. */
//@{
// TODO(sherm1) All these methods perform invalidation sweeps so aren't
// entitled to lower_case_names. Deprecate and replace (see #9205).
/** Returns a mutable reference to the whole State, potentially invalidating
_all_ state-dependent computations so requiring out of date notifications
to be made for all such computations. If you don't mean to change the
whole state, use more focused methods to modify only a portion of the
state. See class documentation for more information.
@warning You _must not_ use the returned reference to modify the size,
number, or types of state variables. */
State<T>& get_mutable_state();
/** Returns a mutable reference to the continuous component of the state,
which may be of size zero. Sends out of date notifications for all
continuous-state-dependent computations. */
ContinuousState<T>& get_mutable_continuous_state();
/** Returns a mutable reference to the continuous state vector, devoid
of second-order structure. The vector may be of size zero. Sends out of
date notifications for all continuous-state-dependent computations. */
VectorBase<T>& get_mutable_continuous_state_vector() {
return get_mutable_continuous_state().get_mutable_vector();
}
/** Returns a mutable reference to the discrete component of the state,
which may be of size zero. Sends out of date notifications for all
discrete-state-dependent computations.
@warning You _must not_ use the returned reference to modify the size or
number of discrete state variables. */
DiscreteValues<T>& get_mutable_discrete_state();
/** Returns a mutable reference to the _only_ discrete state vector.
Sends out of date notifications for all discrete-state-dependent
computations.
@sa get_discrete_state_vector().
@pre There is only one discrete state group. */
BasicVector<T>& get_mutable_discrete_state_vector() {
return get_mutable_discrete_state().get_mutable_vector();
}
// TODO(sherm1) Invalidate only dependents of this one discrete group.
/** Returns a mutable reference to group (vector) `index` of the discrete
state. Sends out of date notifications for all computations that depend
on this discrete state group.
@pre `index` must identify an existing group.
@note Currently notifies dependents of _all_ groups. */
BasicVector<T>& get_mutable_discrete_state(int index) {
DiscreteValues<T>& xd = get_mutable_discrete_state();
return xd.get_mutable_vector(index);
}
/** Returns a mutable reference to the abstract component of the state,
which may be of size zero. Sends out of date notifications for all
abstract-state-dependent computations.
@warning You _must not_ use the returned reference to modify the size,
number, or types of abstract state variables. */
AbstractValues& get_mutable_abstract_state();
// TODO(sherm1) Invalidate only dependents of this one abstract variable.
/** Returns a mutable reference to element `index` of the abstract state.
Sends out of date notifications for all computations that depend on this
abstract state variable.
@pre `index` must identify an existing element.
@pre the abstract state's type must match the template argument.
@note Currently notifies dependents of _any_ abstract state variable. */
template <typename U>
U& get_mutable_abstract_state(int index) {
AbstractValues& xa = get_mutable_abstract_state();
return xa.get_mutable_value(index).get_mutable_value<U>();
}
/** Returns a mutable reference to this %Context's parameters. Sends out of
date notifications for all parameter-dependent computations. If you don't
mean to change all the parameters, use the indexed methods to modify only
some of the parameters so that fewer computations are invalidated and
fewer notifications need be sent.
@warning You _must not_ use the returned reference to modify the size,
number, or types of parameters. */
Parameters<T>& get_mutable_parameters();
// TODO(sherm1) Invalidate only dependents of this one parameter.
/** Returns a mutable reference to element `index` of the vector-valued
(numeric) parameters. Sends out of date notifications for all computations
dependent on this parameter.
@pre `index` must identify an existing numeric parameter.
@note Currently notifies dependents of _all_ numeric parameters. */
BasicVector<T>& get_mutable_numeric_parameter(int index);
// TODO(sherm1) Invalidate only dependents of this one parameter.
/** Returns a mutable reference to element `index` of the abstract-valued
parameters. Sends out of date notifications for all computations dependent
on this parameter.
@pre `index` must identify an existing abstract parameter.
@note Currently notifies dependents of _all_ abstract parameters. */
AbstractValue& get_mutable_abstract_parameter(int index);
//@}
/** @anchor advanced_context_value_change_methods
@name Advanced methods for changing locally-stored values
Methods in this group are specialized for expert users writing numerical
integrators and other context-modifying solvers where careful cache
management can improve performance. Please see
@ref context_value_change_methods "Context Value-Change Methods"
for general information, and prefer to use the methods in that section
unless you _really_ know what you're doing! */
//@{
/** (Advanced) Sets time and returns a mutable reference to the continuous
state xc (including q, v, z) as a VectorBase. Performs a single
notification sweep to avoid duplicate notifications for computations that
depend on both time and state.
@throws std::exception if this is not the root context.
@see SetTimeAndNoteContinuousStateChange()
@see SetTimeAndGetMutableContinuousState() */
VectorBase<T>& SetTimeAndGetMutableContinuousStateVector(const T& time_sec) {
return SetTimeAndGetMutableContinuousStateHelper(__func__, time_sec)
.get_mutable_vector();
}
/** (Advanced) Sets time and returns a mutable reference to the second-order
continuous state partition q from xc. Performs a single notification sweep
to avoid duplicate notifications for computations that depend on both time
and q.
@throws std::exception if this is not the root context.
@see GetMutableVZVectors()
@see SetTimeAndGetMutableContinuousStateVector() */
VectorBase<T>& SetTimeAndGetMutableQVector(const T& time_sec);
/** (Advanced) Returns mutable references to the first-order continuous
state partitions v and z from xc. Performs a single notification sweep
to avoid duplicate notifications for computations that depend on both
v and z. Does _not_ invalidate computations that depend on time or
pose q, unless those also depend on v or z.
@see SetTimeAndGetMutableQVector() */
std::pair<VectorBase<T>*, VectorBase<T>*> GetMutableVZVectors();
/** (Advanced) Sets time and registers an intention to modify the continuous
state xc. Intended use is for integrators that are already holding a
mutable reference to xc which they are going to modify. Performs a single
notification sweep to avoid duplicate notifications for computations that
depend on both time and state.
@throws std::exception if this is not the root context.
@see SetTimeAndGetMutableContinuousStateVector() */
void SetTimeAndNoteContinuousStateChange(const T& time_sec) {
SetTimeAndNoteContinuousStateChangeHelper(__func__, time_sec);
}
/** (Advanced) Registers an intention to modify the continuous
state xc. Intended use is for integrators that are already holding a
mutable reference to xc which they are going to modify. Performs a
notification sweep to invalidate computations that depend on any
continuous state variables. If you need to change the time also, use
SetTimeAndNoteContinuousStateChange() instead to avoid unnecessary
duplicate notifications.
@see SetTimeAndNoteContinuousStateChange() */
void NoteContinuousStateChange() {
const int64_t change_event = this->start_new_change_event();
PropagateBulkChange(change_event,
&Context<T>::NoteAllContinuousStateChanged);
}
//@}
/** @name Miscellaneous public methods */
//@{
/** Returns a deep copy of this Context.
@throws std::exception if this is not the root context. */
// This is just an intentional shadowing of the base class method to return
// a more convenient type.
std::unique_ptr<Context<T>> Clone() const;
/** Returns a deep copy of this Context's State. */
std::unique_ptr<State<T>> CloneState() const;
/** Returns a partial textual description of the Context, intended to be
human-readable. It is not guaranteed to be unambiguous nor complete. */
std::string to_string() const;
//@}
#ifndef DRAKE_DOXYGEN_CXX
// See Drake issue #13296 for why these two methods are needed.
/* (Advanced) Sets the Context time to `time` but notes that this is not the
true current time but some small perturbation away from it. The true
current time is recorded and propagated. This is used by
Simulator::Initialize() to ensure that initialize-time periodic and
scheduled events are not missed due to "right now" events. */
void PerturbTime(const T& time, const T& true_time);
// TODO(sherm1) Consider whether get_true_time() ought to be visible (though
// certainly marked (Advanced)). It may be needed for some obscure overloads
// of DoCalcNextUpdateTime().
/* (Advanced) If time was set with PerturbTime(), returns the true time. If '
this is empty then the true time is just get_time(). This is used for
processing of CalcNextUpdateTime() to ensure that overloads which want
events to occur "right now" work properly during initialization. */
const std::optional<T>& get_true_time() const { return true_time_; }
#endif
protected:
Context();
// Default implementation invokes the base class copy constructor and then
// the local member copy constructors.
/** Copy constructor takes care of base class and `Context<T>` data members.
Derived classes must implement copy constructors that delegate to this
one for use in their DoCloneWithoutPointers() implementations. */
Context(const Context<T>&);
// Structuring these methods as statics permits a DiagramContext to invoke
// the protected functionality on its children.
/** (Internal use only) Sets a new time and notifies time-dependent
quantities that they are now invalid, as part of a given change event. */
static void PropagateTimeChange(Context<T>* context, const T& time,
const std::optional<T>& true_time,
int64_t change_event);
/** (Internal use only) Sets a new accuracy and notifies accuracy-dependent
quantities that they are now invalid, as part of a given change event. */
static void PropagateAccuracyChange(Context<T>* context,
const std::optional<double>& accuracy,
int64_t change_event);
/** (Internal use only) Returns a reference to mutable parameters _without_
invalidation notifications. Use get_mutable_parameters() instead for
normal access. */
static Parameters<T>& access_mutable_parameters(Context<T>* context) {
DRAKE_ASSERT(context != nullptr);
return *context->parameters_;
}
/** (Internal use only) Returns a reference to a mutable state _without_
invalidation notifications. Use get_mutable_state() instead for normal
access. */
static State<T>& access_mutable_state(Context<T>* context) {
DRAKE_ASSERT(context != nullptr);
return context->do_access_mutable_state();
}
// This is just an intentional shadowing of the base class method to return a
// more convenient type.
/** (Internal use only) Clones a context but without any of its internal
pointers. */
static std::unique_ptr<Context<T>> CloneWithoutPointers(
const Context<T>& source);
/** Returns a const reference to its concrete State object. */
virtual const State<T>& do_access_state() const = 0;
/** Returns a mutable reference to its concrete State object _without_ any
invalidation. We promise not to allow user access to this object without
invalidation. */
virtual State<T>& do_access_mutable_state() = 0;
/** Returns the appropriate concrete State object to be returned by
CloneState(). The implementation should not set_system_id on the result,
the caller will set an id on the state after this method returns. */
virtual std::unique_ptr<State<T>> DoCloneState() const = 0;
/** Returns a partial textual description of the Context, intended to be
human-readable. It is not guaranteed to be unambiguous nor complete. */
virtual std::string do_to_string() const = 0;
/** Invokes PropagateTimeChange() on all subcontexts of this Context. The
default implementation does nothing, which is suitable for leaf contexts.
Diagram contexts must override. */
virtual void DoPropagateTimeChange(const T& time_sec,
const std::optional<T>& true_time, int64_t change_event) {
unused(time_sec, true_time, change_event);
}
/** Invokes PropagateAccuracyChange() on all subcontexts of this Context. The
default implementation does nothing, which is suitable for leaf contexts.
Diagram contexts must override. */
virtual void DoPropagateAccuracyChange(const std::optional<double>& accuracy,
int64_t change_event) {
unused(accuracy, change_event);
}
/** (Internal use only) Sets the continuous state to `xc`, deleting whatever
was there before.
@warning Does _not_ invalidate state-dependent computations. */
void init_continuous_state(std::unique_ptr<ContinuousState<T>> xc);
/** (Internal use only) Sets the discrete state to `xd`, deleting whatever
was there before.
@warning Does _not_ invalidate state-dependent computations. */
void init_discrete_state(std::unique_ptr<DiscreteValues<T>> xd);
/** (Internal use only) Sets the abstract state to `xa`, deleting whatever
was there before.
@warning Does _not_ invalidate state-dependent computations. */
void init_abstract_state(std::unique_ptr<AbstractValues> xa);
/** (Internal use only) Sets the parameters to `params`, deleting whatever
was there before. You must supply a Parameters object; null is not
acceptable.
@warning Does _not_ invalidate parameter-dependent computations. */
void init_parameters(std::unique_ptr<Parameters<T>> params);
private:
// Call with arguments like (__func__, "Time"), capitalized as shown.
void ThrowIfNotRootContext(const char* func_name,
const char* quantity) const;
// TODO(xuchenhan-tri) Should treat fixed input port values the same as
// parameters.
// TODO(xuchenhan-tri) Change the name of this method to be more inclusive
// since it also fixed input port values (pending above TODO).
// This helper allow us to reuse this code in several APIs with a single
// change_event.
template <typename U>
void SetStateAndParametersFromHelper(const Context<U>& source,
int64_t change_event) {
// Notification is separate from the actual value change for bulk changes.
PropagateBulkChange(change_event, &Context<T>::NoteAllStateChanged);
do_access_mutable_state().SetFrom(source.get_state());
PropagateBulkChange(change_event, &Context<T>::NoteAllParametersChanged);
parameters_->SetFrom(source.get_parameters());
// TODO(xuchenhan-tri) Fixed input copying goes here.
}
// These helpers allow us to reuse this code in several APIs while the
// error message contains the actual API name.
void SetTimeAndNoteContinuousStateChangeHelper(const char* func_name,
const T& time_sec);
ContinuousState<T>& SetTimeAndGetMutableContinuousStateHelper(
const char* func_name, const T& time_sec) {
SetTimeAndNoteContinuousStateChangeHelper(func_name, time_sec);
return do_access_mutable_state().get_mutable_continuous_state();
}
// Current time in seconds. Must be the same for a Diagram root context and
// all its subcontexts so we only allow setting this in the root.
T time_{0.};
// For ugly reasons, it is sometimes necessary to set time_ to a slight
// difference from the actual time. That is done using the internal
// PerturbTime() method which records the actual time here, where it
// can be retrieved during CalcNextUpdateTime() processing.
std::optional<T> true_time_;
// Accuracy setting.
std::optional<double> accuracy_;
// The parameter values (p) for this Context; this is never null.
copyable_unique_ptr<Parameters<T>> parameters_{
std::make_unique<Parameters<T>>()};
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const Context<T>& context) {
os << context.to_string();
return os;
}
} // namespace systems
} // namespace drake
DRAKE_FORMATTER_AS(typename T, drake::systems, Context<T>, x, x.to_string())
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::Context)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/leaf_context.cc | #include "drake/systems/framework/leaf_context.h"
#include <utility>
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/state.h"
namespace drake {
namespace systems {
template <typename T>
LeafContext<T>::LeafContext()
: state_(std::make_unique<State<T>>()) {}
template <typename T>
LeafContext<T>::~LeafContext() {}
template <typename T>
LeafContext<T>::LeafContext(const LeafContext& source) : Context<T>(source) {
// Make a deep copy of the state.
state_ = source.CloneState();
// Everything else was handled by the Context<T> copy constructor.
}
template <typename T>
std::unique_ptr<ContextBase> LeafContext<T>::DoCloneWithoutPointers() const {
return std::unique_ptr<ContextBase>(new LeafContext<T>(*this));
}
template <typename T>
std::unique_ptr<State<T>> LeafContext<T>::DoCloneState() const {
auto clone = std::make_unique<State<T>>();
// Make a deep copy of the continuous state using BasicVector::Clone().
const ContinuousState<T>& xc = this->get_continuous_state();
const int num_q = xc.get_generalized_position().size();
const int num_v = xc.get_generalized_velocity().size();
const int num_z = xc.get_misc_continuous_state().size();
const BasicVector<T>& xc_vector =
dynamic_cast<const BasicVector<T>&>(xc.get_vector());
clone->set_continuous_state(std::make_unique<ContinuousState<T>>(
xc_vector.Clone(), num_q, num_v, num_z));
// Make deep copies of the discrete and abstract states.
clone->set_discrete_state(state_->get_discrete_state().Clone());
clone->set_abstract_state(state_->get_abstract_state().Clone());
return clone;
}
template <typename T>
std::string LeafContext<T>::do_to_string() const {
std::ostringstream os;
os << this->GetSystemPathname() << " Context\n";
os << std::string(this->GetSystemPathname().size() + 9, '-') << "\n";
os << "Time: " << this->get_time() << "\n";
if (this->num_continuous_states() ||
this->num_discrete_state_groups() ||
this->num_abstract_states()) {
os << "States:\n";
if (this->num_continuous_states()) {
os << " " << this->num_continuous_states()
<< " continuous states\n";
os << " " << this->get_continuous_state_vector() << "\n";
}
if (this->num_discrete_state_groups()) {
os << " " << this->num_discrete_state_groups()
<< " discrete state groups with\n";
for (int i = 0; i < this->num_discrete_state_groups(); i++) {
os << " " << this->get_discrete_state(i).size() << " states\n";
os << " " << this->get_discrete_state(i) << "\n";
}
}
if (this->num_abstract_states()) {
os << " " << this->num_abstract_states() << " abstract states\n";
}
os << "\n";
}
if (this->num_numeric_parameter_groups() ||
this->num_abstract_parameters()) {
os << "Parameters:\n";
if (this->num_numeric_parameter_groups()) {
os << " " << this->num_numeric_parameter_groups()
<< " numeric parameter groups";
os << " with\n";
for (int i = 0; i < this->num_numeric_parameter_groups(); i++) {
os << " " << this->get_numeric_parameter(i).size()
<< " parameters\n";
os << " " << this->get_numeric_parameter(i) << "\n";
}
}
if (this->num_abstract_parameters()) {
os << " " << this->num_abstract_parameters()
<< " abstract parameters\n";
}
}
return os.str();
}
template <typename T>
void LeafContext<T>::notify_set_system_id(internal::SystemId id) {
state_->set_system_id(id);
}
} // namespace systems
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::LeafContext)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/fixed_input_port_value.cc | #include "drake/systems/framework/fixed_input_port_value.h"
#include "drake/systems/framework/context_base.h"
namespace drake {
namespace systems {
AbstractValue* FixedInputPortValue::GetMutableData() {
DRAKE_DEMAND(owning_subcontext_ != nullptr);
ContextBase& context = *owning_subcontext_;
const DependencyTracker& tracker = context.get_tracker(ticket_);
const int64_t change_event = context.start_new_change_event();
tracker.NoteValueChange(change_event);
++serial_number_;
return value_.get_mutable();
}
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/abstract_values.cc | #include "drake/systems/framework/abstract_values.h"
#include <utility>
namespace drake {
namespace systems {
AbstractValues::~AbstractValues() {}
AbstractValues::AbstractValues() {}
AbstractValues::AbstractValues(
std::vector<std::unique_ptr<AbstractValue>>&& data)
: owned_data_(std::move(data)) {
for (auto& datum : owned_data_) {
data_.push_back(datum.get());
}
}
AbstractValues::AbstractValues(const std::vector<AbstractValue*>& data)
: data_(data) {}
AbstractValues::AbstractValues(std::unique_ptr<AbstractValue> datum)
: AbstractValues() {
data_.push_back(datum.get());
owned_data_.push_back(std::move(datum));
}
int AbstractValues::size() const { return static_cast<int>(data_.size()); }
const AbstractValue& AbstractValues::get_value(int index) const {
DRAKE_ASSERT(index >= 0 && index < size());
DRAKE_ASSERT(data_[index] != nullptr);
return *data_[index];
}
AbstractValue& AbstractValues::get_mutable_value(int index) {
DRAKE_ASSERT(index >= 0 && index < size());
DRAKE_ASSERT(data_[index] != nullptr);
return *data_[index];
}
void AbstractValues::SetFrom(const AbstractValues& other) {
DRAKE_ASSERT(size() == other.size());
for (int i = 0; i < size(); i++) {
DRAKE_ASSERT(data_[i] != nullptr);
data_[i]->SetFrom(other.get_value(i));
}
}
std::unique_ptr<AbstractValues> AbstractValues::Clone() const {
std::vector<std::unique_ptr<AbstractValue>> cloned_data;
cloned_data.reserve(data_.size());
for (const AbstractValue* datum : data_) {
cloned_data.push_back(datum->Clone());
}
return std::make_unique<AbstractValues>(std::move(cloned_data));
}
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/diagram_continuous_state.h | #pragma once
#include <functional>
#include <memory>
#include <vector>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_copyable.h"
#include "drake/systems/framework/continuous_state.h"
#include "drake/systems/framework/vector_base.h"
namespace drake {
namespace systems {
/// %DiagramContinuousState is a ContinuousState consisting of Supervectors
/// xc, q, v, z over the corresponding entries in a set of referenced
/// ContinuousState objects, which may or may not be owned by this
/// %DiagramContinuousState. This is done recursively since any of the
/// referenced ContinuousState objects could themselves be
/// %DiagramContinuousState objects. The actual numerical data is always
/// contained in the leaf ContinuousState objects at the bottom of the tree.
///
/// This object is used both for a Diagram's actual continuous state variables
/// xc (with partitions q, v, z) and for the time derivatives xdot (qdot, vdot,
/// zdot). Cloning a %DiagramContinuousState results in an object with identical
/// structure, but which owns the referenced ContinuousState objects, regardless
/// of whether the original had ownership.
///
/// @tparam_default_scalar
template <typename T>
class DiagramContinuousState final: public ContinuousState<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DiagramContinuousState)
/// Constructs a ContinuousState that is composed of other ContinuousStates,
/// which are not owned by this object and must outlive it.
///
/// The DiagramContinuousState vector xc = [q v z] will have the same
/// ordering as the `substates` parameter, which should be the order of
/// the Diagram itself. That is, the substates should be indexed by
/// SubsystemIndex in the same order as the subsystems are. */
explicit DiagramContinuousState(std::vector<ContinuousState<T>*> substates);
/// Constructs a ContinuousState that is composed (recursively) of other
/// ContinuousState objects, ownership of which is transferred here.
explicit DiagramContinuousState(
std::vector<std::unique_ptr<ContinuousState<T>>> substates);
~DiagramContinuousState() override;
/// Creates a deep copy of this %DiagramContinuousState, with the same
/// substructure but with new, owned data. Intentionally shadows the
/// ContinuousState::Clone() method but with a more-specific return type so
/// you don't have to downcast.
std::unique_ptr<DiagramContinuousState> Clone() const;
int num_substates() const { return static_cast<int>(substates_.size()); }
/// Returns the continuous state at the given `index`. Aborts if `index` is
/// out-of-bounds.
const ContinuousState<T>& get_substate(int index) const {
DRAKE_DEMAND(0 <= index && index < num_substates());
DRAKE_DEMAND(substates_[index] != nullptr);
return *substates_[index];
}
/// Returns the continuous state at the given `index`. Aborts if `index` is
/// out-of-bounds.
ContinuousState<T>& get_mutable_substate(int index) {
return const_cast<ContinuousState<T>&>(get_substate(index));
}
private:
// This completely replaces the base class default DoClone() so must
// take care of the base class members as well as the local ones.
// The returned concrete object is a DiagramContinuousState<T>.
std::unique_ptr<ContinuousState<T>> DoClone() const final;
// Returns a Supervector over the x, q, v, or z components of each
// substate in `substates`, as indicated by `selector`.
static std::unique_ptr<VectorBase<T>> Span(
const std::vector<ContinuousState<T>*>& substates,
std::function<VectorBase<T>&(ContinuousState<T>*)> selector);
// Returns the entire state vector in `xc`.
static VectorBase<T>& x_selector(ContinuousState<T>* xc) {
return xc->get_mutable_vector();
}
// Returns the generalized position vector in `xc`.
static VectorBase<T>& q_selector(ContinuousState<T>* xc) {
return xc->get_mutable_generalized_position();
}
// Returns the generalized velocity vector in `xc`.
static VectorBase<T>& v_selector(ContinuousState<T>* xc) {
return xc->get_mutable_generalized_velocity();
}
// Returns the misc continuous state vector in `xc`.
static VectorBase<T>& z_selector(ContinuousState<T>* xc) {
return xc->get_mutable_misc_continuous_state();
}
// Pointers to the underlying ContinuousStates that provide the actual
// values. If these are owned, the pointers are equal to the pointers in
// owned_substates_.
std::vector<ContinuousState<T>*> substates_;
// Owned pointers to ContinuousState objects that hold the actual values.
// The only purpose of these pointers is to maintain ownership. They may be
// populated at construction time, and are never accessed thereafter.
std::vector<std::unique_ptr<ContinuousState<T>>> owned_substates_;
};
} // namespace systems
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::DiagramContinuousState)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/system.h | #pragma once
#include <cmath>
#include <functional>
#include <limits>
#include <map>
#include <memory>
#include <optional>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_assert.h"
#include "drake/common/drake_bool.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/drake_throw.h"
#include "drake/common/nice_type_name.h"
#include "drake/common/pointer_cast.h"
#include "drake/common/random.h"
#include "drake/systems/framework/context.h"
#include "drake/systems/framework/event_collection.h"
#include "drake/systems/framework/input_port.h"
#include "drake/systems/framework/output_port.h"
#include "drake/systems/framework/system_base.h"
#include "drake/systems/framework/system_constraint.h"
#include "drake/systems/framework/system_output.h"
#include "drake/systems/framework/system_scalar_converter.h"
#include "drake/systems/framework/system_visitor.h"
#include "drake/systems/framework/witness_function.h"
namespace drake {
namespace systems {
/** Base class for all System functionality that is dependent on the templatized
scalar type T for input, state, parameters, and outputs.
@tparam_default_scalar */
template <typename T>
class System : public SystemBase {
public:
// System objects are neither copyable nor moveable.
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(System)
/// The scalar type with which this %System was instantiated.
using Scalar = T;
~System() override;
/// Implements a visitor pattern. @see SystemVisitor<T>.
virtual void Accept(SystemVisitor<T>* v) const;
//----------------------------------------------------------------------------
/** @name Cloning
These functions make a deep copy of a system. */
//@{
/** Creates a deep copy of this system.
Even though the cloned system is functionally identical, any contexts created
for this system are not compatible with the cloned system, and vice versa.
@see Context::SetTimeStateAndParametersFrom() for how to copy context data
between clones.
@warning This implementation is somewhat incomplete at the moment. Many
systems will not be able to be cloned, and will throw an exception instead.
To be cloned, at minimum a system must support scalar conversion.
See @ref system_scalar_conversion.
The result is never nullptr. */
std::unique_ptr<System<T>> Clone() const;
/** Creates a deep copy of this system.
In contrast with the instance member function `sys.Clone()`, this static
member function `Clone(sys)` is useful for C++ users to preserve the
<b>declared</b> type of the system being cloned in the returned pointer.
(For both clone overloads, the <b>runtime</b> type is always the same.)
Even though the cloned system is functionally identical, any contexts created
for this system are not compatible with the cloned system, and vice versa.
@warning This implementation is somewhat incomplete at the moment. Many
systems will not be able to be cloned, and will throw an exception instead.
To be cloned, at minimum a system must support scalar conversion.
See @ref system_scalar_conversion.
The result is never nullptr.
Usage: @code
MySystem<double> plant;
unique_ptr<MySystem<double>> copy = System<double>::Clone(plant);
@endcode
@tparam S The specific System type to accept and return. */
template <template <typename> class S = ::drake::systems::System>
static std::unique_ptr<S<T>> Clone(const S<T>& from) {
static_assert(std::is_base_of_v<System<T>, S<T>>);
return dynamic_pointer_cast_or_throw<S<T>>(from.Clone());
}
//@}
//----------------------------------------------------------------------------
/** @name Resource allocation and initialization
These methods are used to allocate and initialize Context resources. */
//@{
// This is just an intentional shadowing of the base class method to return
// a more convenient type.
/** Returns a Context<T> suitable for use with this System<T>. */
std::unique_ptr<Context<T>> AllocateContext() const;
/** Allocates a CompositeEventCollection for this system. The allocated
instance is used for populating collections of triggered events; for
example, Simulator passes this object to System::CalcNextUpdateTime() to
allow the system to identify and handle upcoming events. */
std::unique_ptr<CompositeEventCollection<T>>
AllocateCompositeEventCollection() const;
/** Given an input port, allocates the vector storage. The @p input_port
must match a port declared via DeclareInputPort. */
std::unique_ptr<BasicVector<T>> AllocateInputVector(
const InputPort<T>& input_port) const;
/** Given an input port, allocates the abstract storage. The @p input_port
must match a port declared via DeclareInputPort. */
std::unique_ptr<AbstractValue> AllocateInputAbstract(
const InputPort<T>& input_port) const;
/** Returns a container that can hold the values of all of this System's
output ports. It is sized with the number of output ports and uses each
output port's allocation method to provide an object of the right type
for that port. */
std::unique_ptr<SystemOutput<T>> AllocateOutput() const;
/** Returns a ContinuousState of the same size as the continuous_state
allocated in CreateDefaultContext. The simulator will provide this state
as the output argument to EvalTimeDerivatives. */
virtual std::unique_ptr<ContinuousState<T>> AllocateTimeDerivatives() const
= 0;
/** Returns an Eigen VectorX suitable for use as the output argument to
the CalcImplicitTimeDerivativesResidual() method. The returned VectorX
will have size implicit_time_derivatives_residual_size() with the
elements uninitialized. This is just a convenience method -- you are free
to use any properly-sized mutable Eigen object as the residual vector. */
VectorX<T> AllocateImplicitTimeDerivativesResidual() const {
return VectorX<T>(implicit_time_derivatives_residual_size());
}
/** Returns a DiscreteValues of the same dimensions as the discrete_state
allocated in CreateDefaultContext. The simulator will provide this state
as the output argument to Update. */
virtual std::unique_ptr<DiscreteValues<T>> AllocateDiscreteVariables() const
= 0;
/** This convenience method allocates a context using AllocateContext() and
sets its default values using SetDefaultContext(). */
std::unique_ptr<Context<T>> CreateDefaultContext() const;
/** Assigns default values to all parameters. Overrides must not
change the number of parameters.
@warning `parameters` *may be* a mutable view into `context`. Don't assume
that evaluating `context` will be independent of writing to `parameters`. */
virtual void SetDefaultParameters(const Context<T>& context,
Parameters<T>* parameters) const = 0;
/** Assigns default values to all elements of the state. Overrides must not
change the number of state variables. The context's default parameters will
have already been set.
@warning `state` *may be* a mutable view into `context`. Don't assume that
evaluating `context` will be independent of writing to `state`. */
virtual void SetDefaultState(const Context<T>& context,
State<T>* state) const = 0;
/** Sets Context fields to their default values. User code should not
override. */
void SetDefaultContext(Context<T>* context) const;
/** Assigns random values to all elements of the state.
This default implementation calls SetDefaultState; override this method to
provide random initial conditions using the stdc++ random library, e.g.:
@code
std::normal_distribution<T> gaussian();
state->get_mutable_continuous_state()->get_mutable_vector()
->SetAtIndex(0, gaussian(*generator));
@endcode
Overrides must not change the number of state variables.
@see @ref stochastic_systems */
virtual void SetRandomState(const Context<T>& context, State<T>* state,
RandomGenerator* generator) const;
/** Assigns random values to all parameters.
This default implementation calls SetDefaultParameters; override this
method to provide random parameters using the stdc++ random library, e.g.:
@code
std::uniform_real_distribution<T> uniform();
parameters->get_mutable_numeric_parameter(0)
->SetAtIndex(0, uniform(*generator));
@endcode
Overrides must not change the number of state variables.
@see @ref stochastic_systems */
virtual void SetRandomParameters(const Context<T>& context,
Parameters<T>* parameters,
RandomGenerator* generator) const;
/** Sets Context fields to random values. User code should not
override. */
void SetRandomContext(Context<T>* context, RandomGenerator* generator) const;
/** For each input port, allocates a fixed input of the concrete type
that this System requires, and binds it to the port, disconnecting any
prior input. Does not assign any values to the fixed inputs. */
void AllocateFixedInputs(Context<T>* context) const;
/** Returns `true` if any of the inputs to the system might be directly
fed through to any of its outputs and `false` otherwise. */
bool HasAnyDirectFeedthrough() const;
/** Returns true if there might be direct-feedthrough from any input port to
the given @p output_port, and false otherwise. */
bool HasDirectFeedthrough(int output_port) const;
/** Returns true if there might be direct-feedthrough from the given
@p input_port to the given @p output_port, and false otherwise. */
bool HasDirectFeedthrough(int input_port, int output_port) const;
using SystemBase::GetDirectFeedthroughs;
//@}
//----------------------------------------------------------------------------
/** @name Publishing
Publishing is the primary mechanism for a %System to communicate with
the world outside the %System abstraction during a simulation. Publishing
occurs at user-specified times or events and can generate side-effect
results such as terminal output, visualization, logging, plotting, and
network messages. Other than computational cost, publishing has no effect
on the progress of a simulation. */
//@{
/** This method is the public entry point for dispatching all publish event
handlers. It checks the validity of @p context, and directly calls
DispatchPublishHandler. @p events is a homogeneous collection of publish
events.
@note When publishing is triggered at particular times, those times likely
will not coincide with integrator step times. A Simulator may interpolate
to generate a suitable Context, or it may adjust the integrator step size
so that a step begins exactly at the next publication time. In the latter
case the change in step size may affect the numerical result somewhat
since a smaller integrator step produces a more accurate solution. */
[[nodiscard]] EventStatus Publish(
const Context<T>& context,
const EventCollection<PublishEvent<T>>& events) const;
/** (Advanced) Manually triggers any PublishEvent that has trigger
type kForced. Invokes the publish event dispatcher on this %System with the
given Context.
The default dispatcher will invoke the handlers (if any) associated with each
force-triggered event.
@note There will always be at least one force-triggered event, though with no
associated handler (so will do nothing when triggered).
The Simulator can be configured to call this in Simulator::Initialize() and at
the start of each continuous integration step. See the Simulator API for more
details.
@throws std::exception if it invokes an event handler that returns status
indicating failure.
@see Publish(), CalcForcedDiscreteVariableUpdate(),
CalcForcedUnrestrictedUpdate() */
void ForcedPublish(const Context<T>& context) const;
//@}
//----------------------------------------------------------------------------
/** @name Cached evaluations
Given the values in a Context, a Drake %System must be able to provide
the results of particular computations needed for analysis and simulation
of the %System. These results are maintained in a mutable cache within
the Context so that a result need be computed only once, the first time
it is requested after a change to one of its prerequisite values.
The `Eval` methods in this group return a reference to the
already-computed result in the given Context's cache. If the current value
is out of date, they first update the cache entry using the corresponding
`Calc` method from the "Calculations" group. Evaluations of input ports
instead delegate to the containing Diagram, which arranges to have the
appropriate subsystem evaluate the source output port.
Methods in this group that specify preconditions operate as follows:
The preconditions will be checked in Debug builds but some or all might
not be checked in Release builds for performance reasons. If we do check
and a precondition is violated, an std::logic_error will be thrown with
a helpful message. */
//@{
/** Returns a reference to the cached value of the continuous state variable
time derivatives, evaluating first if necessary using CalcTimeDerivatives().
This method returns the time derivatives ẋ꜀ of the continuous state
x꜀. The referenced return object will correspond elementwise with the
continuous state in the given Context. Thus, if the state in the Context
has second-order structure `x꜀ = [q v z]`, that same structure applies to
the derivatives so we will have `ẋ꜀ = [q̇ ̇v̇ ż]`.
@param context The Context whose time, input port, parameter, state, and
accuracy values may be used to evaluate the derivatives.
@retval xcdot Time derivatives ẋ꜀ of x꜀ returned as a reference to an object
of the same type and size as `context`'s continuous state.
@see BatchEvalTimeDerivatives() for a batch version of this method.
@see CalcTimeDerivatives(), CalcImplicitTimeDerivativesResidual(),
get_time_derivatives_cache_entry() */
const ContinuousState<T>& EvalTimeDerivatives(
const Context<T>& context) const {
ValidateContext(context);
const CacheEntry& entry = get_time_derivatives_cache_entry();
return entry.Eval<ContinuousState<T>>(context);
}
/** (Advanced) Returns the CacheEntry used to cache time derivatives for
EvalTimeDerivatives(). */
const CacheEntry& get_time_derivatives_cache_entry() const {
return this->get_cache_entry(time_derivatives_cache_index_);
}
/** Returns a reference to the cached value of the potential energy (PE),
evaluating first if necessary using CalcPotentialEnergy().
By definition here, potential energy depends only on "configuration"
(e.g. orientation and position), which includes a subset of the state
variables, and parameters that affect configuration or conservative
forces (such as lengths and masses). The calculated value may also be
affected by the accuracy value supplied in the Context. PE cannot depend
explicitly on time (∂PE/∂t = 0), velocities (∂PE/∂v = 0), or input port
values (∂PE/∂u = 0).
Non-physical systems where PE is not meaningful will return PE = 0.
@param context The Context whose configuration variables may be used to
evaluate potential energy.
@retval PE The potential energy in joules (J) represented by the
configuration given in `context`.
@see CalcPotentialEnergy() */
const T& EvalPotentialEnergy(const Context<T>& context) const;
/** Returns a reference to the cached value of the kinetic energy (KE),
evaluating first if necessary using CalcKineticEnergy().
By definition here, kinetic energy depends only on "configuration" and
"velocity" (e.g. angular and translational velocity) of moving masses
which includes a subset of the state variables, and parameters that affect
configuration, velocities, or mass properties. The calculated value may
also be affected by the accuracy value supplied in the Context. KE cannot
depend explicitly on time (∂KE/∂t = 0) or input port values (∂KE/∂u = 0).
Non-physical systems where KE is not meaningful will return KE = 0.
@param context The Context whose configuration and velocity variables may
be used to evaluate kinetic energy.
@retval KE The kinetic energy in joules (J) represented by the
configuration and velocity given in `context`.
@see CalcKineticEnergy() */
const T& EvalKineticEnergy(const Context<T>& context) const;
/** Returns a reference to the cached value of the conservative power (Pc),
evaluating first if necessary using CalcConservativePower().
The returned Pc represents the rate at which mechanical energy is being
converted _from_ potential energy (PE) _to_ kinetic energy (KE) by this
system in the given Context. This quantity will be _positive_ when PE
is _decreasing_. By definition here, conservative power may depend only
on quantities that explicitly contribute to PE and KE. See
EvalPotentialEnergy() and EvalKineticEnergy() for details.
Power due to non-conservative forces (e.g. dampers) can contribute to the
rate of change of KE. Therefore this method alone cannot be used to
determine whether KE is increasing or decreasing, only whether the
conservative power is adding or removing kinetic energy.
EvalNonConservativePower() can be used in conjunction with this method to
find the total rate of change of KE.
Non-physical systems where Pc is not meaningful will return Pc = 0.
@param context The Context whose contents may be used to evaluate
conservative power.
@retval Pc The conservative power in watts (W or J/s) represented by the
contents of the given `context`.
@see CalcConservativePower(), EvalNonConservativePower(),
EvalPotentialEnergy(), EvalKineticEnergy() */
const T& EvalConservativePower(const Context<T>& context) const;
/** Returns a reference to the cached value of the non-conservative power
(Pnc), evaluating first if necessary using CalcNonConservativePower().
The returned Pnc represents the rate at which work W is done on the system
by non-conservative forces. Pnc is _negative_ if the non-conservative
forces are _dissipative_, positive otherwise. Time integration of Pnc
yields work W, and the total mechanical energy `E = PE + KE − W` should be
conserved by any physically-correct model, to within integration accuracy
of W. Power is in watts (J/s). (Watts are abbreviated W but not to be
confused with work!) Any values in the supplied Context (including time
and input ports) may contribute to the computation of non-conservative
power.
Non-physical systems where Pnc is not meaningful will return Pnc = 0.
@param context The Context whose contents may be used to evaluate
non-conservative power.
@retval Pnc The non-conservative power in watts (W or J/s) represented by
the contents of the given `context`.
@see CalcNonConservativePower(), EvalConservativePower() */
const T& EvalNonConservativePower(const Context<T>& context) const;
// TODO(jwnimmer-tri) Deprecate me.
/** Returns the value of the vector-valued input port with the given
`port_index` as a BasicVector or a specific subclass `Vec` derived from
BasicVector. Causes the value to become up to date first if necessary. See
EvalAbstractInput() for more information.
The result is returned as a pointer to the input port's value of type
`Vec<T>` or nullptr if the port is not connected.
@pre `port_index` selects an existing input port of this System.
@pre the port must have been declared to be vector-valued.
@pre the port's value must be of type Vec<T>.
@tparam Vec The template type of the input vector, which must be a
subclass of BasicVector. */
template <template <typename> class Vec = BasicVector>
const Vec<T>* EvalVectorInput(const Context<T>& context,
int port_index) const {
static_assert(
std::is_base_of_v<BasicVector<T>, Vec<T>>,
"In EvalVectorInput<Vec>, Vec must be a subclass of BasicVector.");
ValidateContext(context);
// The API allows an int but we'll use InputPortIndex internally.
if (port_index < 0)
ThrowNegativePortIndex(__func__, port_index);
const InputPortIndex iport_index(port_index);
const BasicVector<T>* const basic_value =
EvalBasicVectorInputImpl(__func__, context, iport_index);
if (basic_value == nullptr)
return nullptr; // An unconnected port.
// It's a BasicVector, but we're fussy about the subtype here.
const Vec<T>* const value = dynamic_cast<const Vec<T>*>(basic_value);
if (value == nullptr) {
ThrowInputPortHasWrongType(__func__, iport_index,
NiceTypeName::Get<Vec<T>>(),
NiceTypeName::Get(*basic_value));
}
return value;
}
//----------------------------------------------------------------------------
/** @name Constraint-related functions */
//@{
/** Adds an "external" constraint to this System.
This method is intended for use by applications that are examining this
System to add additional constraints based on their particular situation
(e.g., that a velocity state element has an upper bound); it is not
intended for declaring intrinsic constraints that some particular System
subclass might always impose on itself (e.g., that a mass parameter is
non-negative). To that end, this method should not be called by
subclasses of `this` during their constructor.
The `constraint` will automatically persist across system scalar
conversion. */
SystemConstraintIndex AddExternalConstraint(
ExternalSystemConstraint constraint);
//@}
//----------------------------------------------------------------------------
/** @name Calculations
A Drake %System defines a set of common computations that are understood
by the framework. Most of these are embodied in a `Calc` method that
unconditionally performs the calculation into an output argument of the
appropriate type, using only values from the given Context. These are
paired with an `Eval` method that returns a reference to an
already-calculated result residing in the cache; if needed that result is
first obtained using the `Calc` method. See the "Evaluations" group for
more information.
This group also includes additional %System-specific operations that
depend on both Context and additional input arguments. */
//@{
/** Calculates the time derivatives ẋ꜀ of the continuous state x꜀ into
a given output argument. Prefer EvalTimeDerivatives() instead to avoid
unnecessary recomputation.
This method solves the %System equations in explicit form:
ẋ꜀ = fₑ(𝓒)
where `𝓒 = {a, p, t, x, u}` is the current value of the given Context from
which accuracy a, parameters p, time t, state x (`={x꜀ xd xₐ}`) and
input values u are obtained.
@param[in] context The source for time, state, inputs, etc. defining the
point at which the derivatives should be calculated.
@param[out] derivatives The time derivatives ẋ꜀. Must be the same size as
the continuous state vector in `context`.
@see EvalTimeDerivatives() for more information.
@see CalcImplicitTimeDerivativesResidual() for the implicit form of these
equations.*/
void CalcTimeDerivatives(const Context<T>& context,
ContinuousState<T>* derivatives) const;
/** Evaluates the implicit form of the %System equations and returns the
residual.
The explicit and implicit forms of the %System equations are
(1) ẋ꜀ = fₑ(𝓒) explicit
(2) 0 = fᵢ(𝓒; ẋ꜀) implicit
where `𝓒 = {a, p, t, x, u}` is the current value of the given Context from
which accuracy a, parameters p, time t, state x (`={x꜀ xd xₐ}`) and input
values u are obtained. Substituting (1) into (2) shows that the following
condition must always hold:
(3) fᵢ(𝓒; fₑ(𝓒)) = 0 always true
When `fᵢ(𝓒; ẋ꜀ₚ)` is evaluated with a proposed time derivative ẋ꜀ₚ that
differs from ẋ꜀ the result will be non-zero; we call that the _residual_ of
the implicit equation. Given a Context and proposed time derivative ẋ꜀ₚ, this
method returns the residual r such that
(4) r = fᵢ(𝓒; ẋ꜀ₚ).
The returned r will typically be the same length as x꜀ although that is not
required. And even if r and x꜀ are the same size, there will not necessarily
be any elementwise correspondence between them. (That is, you should not
assume that r[i] is the "residual" of ẋ꜀ₚ[i].) For a Diagram, r is the
concatenation of residuals from each of the subsystems, in order of subsystem
index within the Diagram.
A default implementation fᵢ⁽ᵈᵉᶠ⁾ for the implicit form is always provided and
makes use of the explicit form as follows:
(5) fᵢ⁽ᵈᵉᶠ⁾(𝓒; ẋ꜀ₚ) ≜ ẋ꜀ₚ − fₑ(𝓒)
which satisfies condition (3) by construction. (Note that the default
implementation requires the residual to have the same size as x꜀.) Substantial
efficiency gains can often be obtained by replacing the default function with
a customized implementation. Override DoCalcImplicitTimeDerivativesResidual()
to replace the default implementation with a better one.
@param[in] context The source for time, state, inputs, etc. to be used
in calculating the residual.
@param[in] proposed_derivatives The proposed value ẋ꜀ₚ for the time
derivatives of x꜀.
@param[out] residual The result r of evaluating the implicit function.
Can be any mutable Eigen vector object of size
implicit_time_derivatives_residual_size().
@pre `proposed_derivatives` is compatible with this System.
@pre `residual` is of size implicit_time_derivatives_residual_size().
@see SystemBase::implicit_time_derivatives_residual_size()
@see LeafSystem::DeclareImplicitTimeDerivativesResidualSize()
@see DoCalcImplicitTimeDerivativesResidual()
@see CalcTimeDerivatives() */
void CalcImplicitTimeDerivativesResidual(
const Context<T>& context, const ContinuousState<T>& proposed_derivatives,
EigenPtr<VectorX<T>> residual) const;
/** This method is the public entry point for dispatching all discrete
variable update event handlers. Using all the discrete update handlers in
@p events, the method calculates the update `xd(n+1)` to discrete
variables `xd(n)` in @p context and outputs the results to @p
discrete_state. See documentation for
DispatchDiscreteVariableUpdateHandler() for more details. */
[[nodiscard]] EventStatus CalcDiscreteVariableUpdate(
const Context<T>& context,
const EventCollection<DiscreteUpdateEvent<T>>& events,
DiscreteValues<T>* discrete_state) const;
/** Given the @p discrete_state results of a previous call to
CalcDiscreteVariableUpdate() that dispatched the given collection of
events, modifies the @p context to reflect the updated @p discrete_state.
@param[in] events
The Event collection that resulted in the given @p discrete_state.
@param[in,out] discrete_state
The updated discrete state from a CalcDiscreteVariableUpdate()
call. This is mutable to permit its contents to be swapped with the
corresponding @p context contents (rather than copied).
@param[in,out] context
The Context whose discrete state is modified to match
@p discrete_state. Note that swapping contents with @p discrete_state
may cause addresses of individual discrete state group vectors in
@p context to be different on return than they were on entry.
@pre @p discrete_state is the result of a previous
CalcDiscreteVariableUpdate() call that dispatched this @p events
collection. */
void ApplyDiscreteVariableUpdate(
const EventCollection<DiscreteUpdateEvent<T>>& events,
DiscreteValues<T>* discrete_state, Context<T>* context) const;
/** (Advanced) Manually triggers any DiscreteUpdateEvent that has trigger
type kForced. Invokes the discrete event dispatcher on this %System with the
given Context providing the initial values for the discrete variables. The
updated values of the discrete variables are written to the `discrete_state`
output argument; no change is made to the %Context.
The default dispatcher will invoke the handlers (if any) associated with each
force-triggered event.
@note There will always be at least one force-triggered event, though with no
associated handler. By default that will do nothing when triggered, but that
behavior can be changed by overriding the dispatcher (not recommended).
@throws std::exception if it invokes an event handler that returns status
indicating failure.
@see CalcDiscreteVariableUpdate(), CalcForcedUnrestrictedUpdate() */
void CalcForcedDiscreteVariableUpdate(
const Context<T>& context, DiscreteValues<T>* discrete_state) const;
/** This method is the public entry point for dispatching all unrestricted
update event handlers. Using all the unrestricted update handlers in
@p events, it updates *any* state variables in the @p context, and
outputs the results to @p state. It does not allow the dimensionality
of the state variables to change. See the documentation for
DispatchUnrestrictedUpdateHandler() for more details.
@throws std::exception if the dimensionality of the state variables
changes in the callback. */
[[nodiscard]] EventStatus CalcUnrestrictedUpdate(
const Context<T>& context,
const EventCollection<UnrestrictedUpdateEvent<T>>& events,
State<T>* state) const;
/** Given the @p state results of a previous call to CalcUnrestrictedUpdate()
that dispatched the given collection of events, modifies the @p context to
reflect the updated @p state.
@param[in] events
The Event collection that resulted in the given @p state.
@param[in,out] state
The updated State from a CalcUnrestrictedUpdate() call. This is
mutable to permit its contents to be swapped with the corresponding
@p context contents (rather than copied).
@param[in,out] context
The Context whose State is modified to match @p state. Note that
swapping contents with the @p state may cause addresses of
continuous, discrete, and abstract state containers in @p context
to be different on return than they were on entry.
@pre @p state is the result of a previous CalcUnrestrictedUpdate() call
that dispatched this @p events collection. */
void ApplyUnrestrictedUpdate(
const EventCollection<UnrestrictedUpdateEvent<T>>& events,
State<T>* state, Context<T>* context) const;
/** (Advanced) Manually triggers any UnrestrictedUpdateEvent that has trigger
type kForced. Invokes the unrestricted event dispatcher on this %System with
the given Context providing the initial values for the state variables. The
updated values of the state variables are written to the `state`
output argument; no change is made to the %Context.
The default dispatcher will invoke the handlers (if any) associated with each
force-triggered event.
@note There will always be at least one force-triggered event, though with no
associated handler. By default that will do nothing when triggered, but that
behavior can be changed by overriding the dispatcher (not recommended).
@throws std::exception if it invokes an event handler that returns status
indicating failure.
@see CalcUnrestrictedUpdate() */
void CalcForcedUnrestrictedUpdate(const Context<T>& context,
State<T>* state) const;
/** This method is called by a Simulator during its calculation of the size of
the next continuous step to attempt. The System returns the next time at
which some discrete action must be taken, and records what those actions
ought to be in @p events. Upon reaching that time, the simulator will
merge @p events with the other CompositeEventCollection instances
triggered through other mechanisms (e.g. GetPerStepEvents()), and the
merged CompositeEventCollection will be passed to all event handling
mechanisms.
Despite the name, the returned events includes both state-updating events
and publish events.
If there is no timed event coming, the return value is Infinity. If
a finite update time is returned, there will be at least one Event object
in the returned event collection.
@p events cannot be null. @p events will be cleared on entry. */
T CalcNextUpdateTime(const Context<T>& context,
CompositeEventCollection<T>* events) const;
/** Returns all periodic events in this %System. This includes publish,
discrete update, and unrestricted update events.
@p events cannot be null. @p events will be cleared on entry.
@see GetPerStepEvents(), GetInitializationEvents() */
void GetPeriodicEvents(const Context<T>& context,
CompositeEventCollection<T>* events) const;
/** This method is called by Simulator::Initialize() to gather all update
and publish events that are to be handled in AdvanceTo() at the point
before Simulator integrates continuous state. It is assumed that these
events remain constant throughout the simulation. The "step" here refers
to the major time step taken by the Simulator. During every simulation
step, the simulator will merge @p events with the event collections
populated by other types of event triggering mechanism (e.g.,
CalcNextUpdateTime()), and the merged CompositeEventCollection objects
will be passed to the appropriate handlers before Simulator integrates the
continuous state.
@p events cannot be null. @p events will be cleared on entry.
@see GetPeriodicEvents(), GetInitializationEvents() */
void GetPerStepEvents(const Context<T>& context,
CompositeEventCollection<T>* events) const;
/** This method is called by Simulator::Initialize() to gather all
update and publish events that need to be handled at initialization
before the simulator starts integration.
@p events cannot be null. @p events will be cleared on entry.
@see GetPeriodicEvents(), GetPerStepEvents() */
void GetInitializationEvents(const Context<T>& context,
CompositeEventCollection<T>* events) const;
/** This method triggers all of the initialization events returned by
GetInitializationEvents(). The method allocates temporary storage to perform
the updates, and is intended only as a convenience method for callers who do
not want to use the full Simulator workflow.
Note that this is not fully equivalent to Simulator::Initialize() because
_only_ initialization events are handled here, while Simulator::Initialize()
also processes other events associated with time zero. Also, "reached
termination" returns are ignored here.
@throws std::exception if it invokes an event handler that returns status
indicating failure. */
void ExecuteInitializationEvents(Context<T>* context) const;
/** Determines whether there exists a unique periodic timing (offset and
period) that triggers one or more discrete update events (and, if so, returns
that unique periodic timing). Thus, this method can be used (1) as a test to
determine whether a system's dynamics are at least partially governed by
difference equations, and (2) to obtain the difference equation update times.
Use EvalUniquePeriodicDiscreteUpdate() if you want to determine the actual
effects of triggering these events.
@warning Even if we find a unique discrete update timing as described above,
there may also be unrestricted updates performed with that timing or other
timings. (Unrestricted updates can modify any state variables _including_
discrete variables.) Also, there may be trigger types other than periodic that
can modify discrete variables. This function does not attempt to look for any
of those; they are simply ignored. If you are concerned with those, you can
use GetPerStepEvents(), GetInitializationEvents(), and GetPeriodicEvents() to
get a more comprehensive picture of the event landscape.
@returns optional<PeriodicEventData> Contains the unique periodic trigger
timing if it exists, otherwise `nullopt`.
@see EvalUniquePeriodicDiscreteUpdate(), IsDifferenceEquationSystem() */
std::optional<PeriodicEventData>
GetUniquePeriodicDiscreteUpdateAttribute() const;
/** If this %System contains a unique periodic timing for discrete update
events, this function executes the handlers for those periodic events to
determine what their effect would be. Returns a reference to the discrete
variable cache entry containing what values the discrete variables would have
if these periodic events were triggered.
Note that this function _does not_ change the value of the discrete variables
in the supplied Context. However, you can apply the result to the %Context
like this: @code
const DiscreteValues<T>& updated =
system.EvalUniquePeriodicDiscreteUpdate(context);
context.SetDiscreteState(updated);
@endcode
You can write the updated values to a different %Context than the one you
used to calculate the update; the requirement is only that the discrete state
in the destination has the same structure (number of groups and size of each
group).
You can use GetUniquePeriodicDiscreteUpdateAttribute() to check whether you
can call %EvalUniquePeriodicDiscreteUpdate() safely, and to find the unique
periodic timing information (offset and period).
@warning Even if we find a unique discrete update timing as described above,
there may also be unrestricted updates performed with that timing or other
timings. (Unrestricted updates can modify any state variables _including_
discrete variables.) Also, there may be trigger types other than periodic
that can modify discrete variables. This function does not attempt to look
for any of those; they are simply ignored. If you are concerned with those,
you can use GetPerStepEvents(), GetInitializationEvents(), and
GetPeriodicEvents() to get a more comprehensive picture of the event
landscape.
@param[in] context The Context containing the current %System state and the
mutable cache space into which the result is written. The current state
is _not_ modified, though the cache entry may be updated.
@returns
A reference to the DiscreteValues cache space in `context` containing
the result of applying the discrete update event handlers to the current
discrete variable values.
@note The referenced cache entry is recalculated if anything in the given
Context has changed since last calculation. Subsequent calls just return
the already-calculated value.
@throws std::exception if there is not exactly one periodic timing in this
%System (which may be a Diagram) that triggers discrete update events.
@throws std::exception if it invokes an event handler that returns status
indicating failure.
@par Implementation If recalculation is needed, copies the current discrete
state values into preallocated `context` cache space. Applies the discrete
update event handlers (in an unspecified order) to the cache copy, possibly
updating it. Returns a reference to the possibly-updated cache space.
@see BatchEvalUniquePeriodicDiscreteUpdate() for a batch version of this
method.
@see GetUniquePeriodicDiscreteUpdateAttribute(), GetPeriodicEvents() */
const DiscreteValues<T>& EvalUniquePeriodicDiscreteUpdate(
const Context<T>& context) const;
/** Returns true iff the state dynamics of this system are governed
exclusively by a difference equation on a single discrete state group and
with a unique periodic update (having zero offset). E.g., it is amenable to
analysis of the form:
x[n+1] = f(n, x[n], u[n], w[n]; p)
where t is time, x is (discrete) state, u is a vector input, w is random
(disturbance) input, and p are parameters. Note that we do NOT consider the
number of input ports here, because in practice many systems of interest (e.g.
MultibodyPlant) have input ports that are safely treated as constant during
the analysis. Consider using get_input_port_selection() to choose one.
@warning In determining whether this system is governed as above, we do not
consider unrestricted updates nor any update events that have trigger types
other than periodic. See GetUniquePeriodicDiscreteUpdateAttribute() for more
information.
@param[out] time_period if non-null, then iff the function returns `true`,
then time_period is set to the period data returned from
GetUniquePeriodicDiscreteUpdateAttribute(). If the function returns `false`
(the system is not a difference equation system), then `time_period` does not
receive a value.
@see GetUniquePeriodicDiscreteUpdateAttribute()
@see EvalUniquePeriodicDiscreteUpdate() */
bool IsDifferenceEquationSystem(double* time_period = nullptr) const;
/** Returns true iff the state dynamics of this system are governed
exclusively by a differential equation. E.g., it is amenable to analysis of
the form:
ẋ = f(t, x(t), u(t), w(t); p),
where t is time, x is (continuous) state, u is a vector input, w is random
(disturbance) input, and p are parameters. This requires that it has no
discrete nor abstract states, and no abstract input ports.
@warning In determining whether this system is governed as above, we do not
consider unrestricted updates which could potentially update the state.
*/
bool IsDifferentialEquationSystem() const;
/** Maps all periodic triggered events for a %System, organized by timing.
Each unique periodic timing attribute (offset and period) is
mapped to the set of Event objects that are triggered with that timing.
Those may include a mix of Publish, DiscreteUpdate, and UnrestrictedUpdate
events.
@param context Optional Context to pass on to Event selection functions;
not commonly needed. */
std::map<PeriodicEventData, std::vector<const Event<T>*>,
PeriodicEventDataComparator>
MapPeriodicEventsByTiming(const Context<T>* context = nullptr) const;
/** Utility method that computes for _every_ output port i the value y(i) that
should result from the current contents of the given Context. Note that
individual output port values can be calculated using
`get_output_port(i).Calc()`; this method invokes that for each output port
in index order. The result may depend on time and the current values of
input ports, parameters, and state variables. The result is written to
`outputs` which must already have been allocated to have the right number
of entries of the right types. */
void CalcOutput(const Context<T>& context, SystemOutput<T>* outputs) const;
/** Calculates and returns the potential energy represented by the current
configuration provided in `context`. Prefer EvalPotentialEnergy() to
avoid unnecessary recalculation.
@see EvalPotentialEnergy() for more information. */
T CalcPotentialEnergy(const Context<T>& context) const;
/** Calculates and returns the kinetic energy represented by the current
configuration and velocity provided in `context`. Prefer
EvalKineticEnergy() to avoid unnecessary recalculation.
@see EvalKineticEnergy() for more information. */
T CalcKineticEnergy(const Context<T>& context) const;
/** Calculates and returns the conservative power represented by the current
contents of the given `context`. Prefer EvalConservativePower() to avoid
unnecessary recalculation.
@see EvalConservativePower() for more information. */
T CalcConservativePower(const Context<T>& context) const;
/** Calculates and returns the non-conservative power represented by the
current contents of the given `context`. Prefer EvalNonConservativePower()
to avoid unnecessary recalculation.
@see EvalNonConservativePower() for more information. */
T CalcNonConservativePower(const Context<T>& context) const;
/** Transforms a given generalized velocity `v` to the time derivative `qdot`
of the generalized configuration `q` taken from the supplied Context.
`v` and `qdot` are related linearly by `qdot = N(q) * v`, where `N` is a
block diagonal matrix. For example, in a multibody system there will be
one block of `N` per tree joint. This computation requires only `O(nq)`
time where `nq` is the size of `qdot`. Note that `v` is *not* taken from
the Context; it is given as an argument here.
See the alternate signature if you already have the generalized
velocity in an Eigen VectorX object; this signature will copy the
VectorBase into an Eigen object before performing the computation.
@see MapQDotToVelocity() */
void MapVelocityToQDot(const Context<T>& context,
const VectorBase<T>& generalized_velocity,
VectorBase<T>* qdot) const;
/** Transforms the given generalized velocity to the time derivative of
generalized configuration. See the other signature of MapVelocityToQDot()
for more information. */
void MapVelocityToQDot(
const Context<T>& context,
const Eigen::Ref<const VectorX<T>>& generalized_velocity,
VectorBase<T>* qdot) const;
/** Transforms the time derivative `qdot` of the generalized configuration `q`
to generalized velocities `v`. `v` and `qdot` are related linearly by
`qdot = N(q) * v`, where `N` is a block diagonal matrix. For example, in a
multibody system there will be one block of `N` per tree joint. Although
`N` is not necessarily square, its left pseudo-inverse `N+` can be used to
invert that relationship without residual error, provided that `qdot` is
in the range space of `N` (that is, if it *could* have been produced as
`qdot=N*v` for some `v`). Using the configuration `q` from the given
Context this method calculates `v = N+ * qdot` (where `N+=N+(q)`) for
a given `qdot`. This computation requires only `O(nq)` time where `nq` is
the size of `qdot`. Note that this method does not take `qdot` from the
Context.
See the alternate signature if you already have `qdot` in an %Eigen
VectorX object; this signature will copy the VectorBase into an %Eigen
object before performing the computation.
@see MapVelocityToQDot() */
void MapQDotToVelocity(const Context<T>& context, const VectorBase<T>& qdot,
VectorBase<T>* generalized_velocity) const;
/** Transforms the given time derivative `qdot` of generalized configuration
`q` to generalized velocity `v`. This signature takes `qdot` as an %Eigen
VectorX object for faster speed. See the other signature of
MapQDotToVelocity() for additional information. */
void MapQDotToVelocity(const Context<T>& context,
const Eigen::Ref<const VectorX<T>>& qdot,
VectorBase<T>* generalized_velocity) const;
//@}
//----------------------------------------------------------------------------
/** @name Subcontext access
Methods in this section locate the Context belonging to a particular
subsystem, from within the Context for a containing System (typically a
Diagram). There are two common circumstances where this is needed:
1. You are given a Diagram and its Context, and have a reference to a
particular subsystem contained somewhere in that Diagram (that is,
an immediate child or deeper descendent). You can ask the Diagram to
find the subcontext of that subsystem, using GetSubsystemContext()
or GetMutableSubsystemContext().
2. You are given the root Context for a complete Diagram (typically by
the Simulator as part of a generated trajectory). You don't have a
reference to the Diagram, but you do have a reference to a subsystem
of interest. You want to find its subcontext from within the root
Context. Use GetMyContextFromRoot() or GetMyMutableContextFromRoot().
The second case is particularly useful in monitor functions for the
Drake Simulator. */
//@{
/** Returns a const reference to the subcontext that corresponds to the
contained %System `subsystem`.
@throws std::exception if `subsystem` not contained in `this` %System.
@pre The given `context` is valid for use with `this` %System. */
const Context<T>& GetSubsystemContext(const System<T>& subsystem,
const Context<T>& context) const;
/** Returns a mutable reference to the subcontext that corresponds to the
contained %System `subsystem`.
@throws std::exception if `subsystem` not contained in `this` %System.
@pre The given `context` is valid for use with `this` %System. */
Context<T>& GetMutableSubsystemContext(const System<T>& subsystem,
Context<T>* context) const;
/** Returns the const Context for `this` subsystem, given a root context. If
`this` %System is already the top level (root) %System, just returns
`root_context`. (A root Context is one that does not have a parent
Context.)
@throws std::exception if the given `root_context` is not actually
a root context.
@see GetSubsystemContext() */
const Context<T>& GetMyContextFromRoot(const Context<T>& root_context) const;
/** Returns the mutable subsystem context for `this` system, given a root
context.
@see GetMyContextFromRoot() */
Context<T>& GetMyMutableContextFromRoot(Context<T>* root_context) const;
//@}
//----------------------------------------------------------------------------
/** @cond */
// Functions to avoid RTTI in Diagram. Conceptually, these should be protected
// and should not be directly called, so they are hidden from doxygen.
// TODO(siyuan): change all target_system to reference.
// Returns @p context if @p target_system equals `this`, nullptr otherwise.
// Should not be directly called.
virtual const Context<T>* DoGetTargetSystemContext(
const System<T>& target_system, const Context<T>* context) const;
// Returns @p state if @p target_system equals `this`, nullptr otherwise.
// Should not be directly called.
virtual State<T>* DoGetMutableTargetSystemState(
const System<T>& target_system, State<T>* state) const;
// Returns @p state if @p target_system equals `this`, nullptr otherwise.
// Should not be directly called.
virtual const State<T>* DoGetTargetSystemState(const System<T>& target_system,
const State<T>* state) const;
// Returns x꜀ if @p target_system equals `this`, nullptr otherwise.
// Should not be directly called.
virtual const ContinuousState<T>* DoGetTargetSystemContinuousState(
const System<T>& target_system,
const ContinuousState<T>* xc) const;
// Returns @p events if @p target_system equals `this`, nullptr otherwise.
// Should not be directly called.
virtual CompositeEventCollection<T>*
DoGetMutableTargetSystemCompositeEventCollection(
const System<T>& target_system,
CompositeEventCollection<T>* events) const;
// Returns @p events if @p target_system equals `this`, nullptr otherwise.
// Should not be directly called.
virtual const CompositeEventCollection<T>*
DoGetTargetSystemCompositeEventCollection(
const System<T>& target_system,
const CompositeEventCollection<T>* events) const;
// The derived class implementation shall create the appropriate collection
// for each of these three methods.
//
// Consumers of this class should never need to call the three methods below.
// These three methods would ideally be designated as "protected", but
// Diagram::AllocateForcedXEventCollection() needs to call these methods and,
// perhaps surprisingly, is not able to access these methods when they are
// protected. See:
// https://stackoverflow.com/questions/16785069/why-cant-a-derived-class-call-protected-member-function-in-this-code.
// To address this problem, we keep the methods "public" and
// (1) Make the overriding methods in LeafSystem and Diagram "final" and
// (2) Use the doxygen cond/endcond tags so that these methods are hidden
// from the user (in the doxygen documentation).
virtual std::unique_ptr<EventCollection<PublishEvent<T>>>
AllocateForcedPublishEventCollection() const = 0;
virtual std::unique_ptr<EventCollection<DiscreteUpdateEvent<T>>>
AllocateForcedDiscreteUpdateEventCollection() const = 0;
virtual std::unique_ptr<EventCollection<UnrestrictedUpdateEvent<T>>>
AllocateForcedUnrestrictedUpdateEventCollection() const = 0;
/** @endcond */
//----------------------------------------------------------------------------
/** @name Utility methods */
//@{
// Avoid `this->` boilerplate for these member functions.
using SystemBase::GetMemoryObjectName;
using SystemBase::num_input_ports;
using SystemBase::num_output_ports;
// TODO(sherm1) Make this an InputPortIndex.
/** Returns the typed input port at index @p port_index. */
const InputPort<T>& get_input_port(int port_index) const {
// Profiling revealed that it is too expensive to do a dynamic_cast here.
// A static_cast is safe as long as GetInputPortBaseOrThrow always returns
// a satisfactory type. As of this writing, it only ever returns values
// supplied via SystemBase::AddInputPort, which atop its implementation
// has a check that port.get_system_interface() matches `this` which is a
// System<T>, so we are safe.
return static_cast<const InputPort<T>&>(
this->GetInputPortBaseOrThrow(__func__, port_index,
/* warn_deprecated = */ true));
}
/** Convenience method for the case of exactly one input port.
This function ignores deprecated ports, unless there is only one port in which
case it will return the deprecated port. */
const InputPort<T>& get_input_port() const {
// Fast path for common case.
if (num_input_ports() == 1) {
return get_input_port(0);
}
// Fallback for deprecation and/or error handling case.
return GetSoleInputPort();
}
/** Returns the typed input port specified by the InputPortSelection or by
the InputPortIndex. Returns nullptr if no port is selected. This is
provided as a convenience method since many algorithms provide the same
common default or optional port semantics. */
const InputPort<T>* get_input_port_selection(
std::variant<InputPortSelection, InputPortIndex> port_index) const;
/** Returns the typed input port with the unique name @p port_name.
The current implementation performs a linear search over strings; prefer
get_input_port() when performance is a concern.
@throws std::exception if port_name is not found. */
const InputPort<T>& GetInputPort(const std::string& port_name) const;
/** Returns true iff the system has an InputPort of the given @p
port_name. */
bool HasInputPort(const std::string& port_name) const;
// TODO(sherm1) Make this an OutputPortIndex.
/** Returns the typed output port at index @p port_index. */
const OutputPort<T>& get_output_port(int port_index) const {
// Profiling revealed that it is too expensive to do a dynamic_cast here.
// A static_cast is safe as long as GetInputPortBaseOrThrow always returns
// a satisfactory type. As of this writing, it only ever returns values
// supplied via SystemBase::AddInputPort, which atop its implementation
// has a check that port.get_system_interface() matches `this` which is a
// System<T>, so we are safe.
return static_cast<const OutputPort<T>&>(
this->GetOutputPortBaseOrThrow(__func__, port_index,
/* warn_deprecated = */ true));
}
/** Convenience method for the case of exactly one output port.
This function ignores deprecated ports, unless there is only one port in which
case it will return the deprecated port. */
const OutputPort<T>& get_output_port() const {
// Fast path for common case.
if (num_output_ports() == 1) {
return get_output_port(0);
}
// Fallback for deprecation and/or error handling case.
return GetSoleOutputPort();
}
/** Returns the typed output port specified by the OutputPortSelection or by
the OutputPortIndex. Returns nullptr if no port is selected. This is
provided as a convenience method since many algorithms provide the same
common default or optional port semantics. */
const OutputPort<T>* get_output_port_selection(
std::variant<OutputPortSelection, OutputPortIndex> port_index) const;
/** Returns the typed output port with the unique name @p port_name.
The current implementation performs a linear search over strings; prefer
get_output_port() when performance is a concern.
@throws std::exception if port_name is not found. */
const OutputPort<T>& GetOutputPort(const std::string& port_name) const;
/** Returns true iff the system has an OutputPort of the given @p
port_name. */
bool HasOutputPort(const std::string& port_name) const;
/** Returns the number of constraints specified for the system. */
int num_constraints() const;
/** Returns the constraint at index @p constraint_index.
@throws std::exception for an invalid constraint_index. */
const SystemConstraint<T>& get_constraint(
SystemConstraintIndex constraint_index) const;
/** Returns true if @p context satisfies all of the registered
SystemConstraints with tolerance @p tol. @see
SystemConstraint::CheckSatisfied. */
boolean<T> CheckSystemConstraintsSatisfied(
const Context<T>& context, double tol) const;
/** Returns a copy of the continuous state vector x꜀ into an Eigen
vector. */
VectorX<T> CopyContinuousStateVector(const Context<T>& context) const;
//@}
//----------------------------------------------------------------------------
/** @name Graphviz methods */
//@{
// Add this base class function into this Doxygen section.
using SystemBase::GetGraphvizString;
//@}
//----------------------------------------------------------------------------
/** @name Automatic differentiation
From a %System templatized by `double`, you can obtain an identical system
templatized by an automatic differentiation scalar providing
machine-precision computation of partial derivatives of any numerical
result of the %System with respect to any of the numerical values that
can be contained in a Context (time, inputs, parameters, and state). */
// This group appears as a top-level heading in Doxygen because it contains
// both static and non-static member functions.
//@{
/** Creates a deep copy of this System, transmogrified to use the autodiff
scalar type, with a dynamic-sized vector of partial derivatives. The
result is never nullptr.
@throws std::exception if this System does not support autodiff
See @ref system_scalar_conversion for detailed background and examples
related to scalar-type conversion support. */
std::unique_ptr<System<AutoDiffXd>> ToAutoDiffXd() const;
/** Creates a deep copy of `from`, transmogrified to use the autodiff scalar
type, with a dynamic-sized vector of partial derivatives. The result is
never nullptr.
@throws std::exception if `from` does not support autodiff
Usage: @code
MySystem<double> plant;
std::unique_ptr<MySystem<AutoDiffXd>> ad_plant =
systems::System<double>::ToAutoDiffXd(plant);
@endcode
@tparam S The specific System type to accept and return.
See @ref system_scalar_conversion for detailed background and examples
related to scalar-type conversion support. */
template <template <typename> class S = ::drake::systems::System>
static std::unique_ptr<S<AutoDiffXd>> ToAutoDiffXd(const S<T>& from) {
return System<T>::ToScalarType<AutoDiffXd>(from);
}
/** Creates a deep copy of this system exactly like ToAutoDiffXd(), but
returns nullptr if this System does not support autodiff, instead of
throwing an exception. */
std::unique_ptr<System<AutoDiffXd>> ToAutoDiffXdMaybe() const;
//@}
//----------------------------------------------------------------------------
/** @name Symbolics
From a %System templatized by `double`, you can obtain an identical system
templatized by a symbolic expression scalar. */
// This group appears as a top-level heading in Doxygen because it contains
// both static and non-static member functions.
//@{
/** Creates a deep copy of this System, transmogrified to use the symbolic
scalar type. The result is never nullptr.
@throws std::exception if this System does not support symbolic
See @ref system_scalar_conversion for detailed background and examples
related to scalar-type conversion support. */
std::unique_ptr<System<symbolic::Expression>> ToSymbolic() const;
/** Creates a deep copy of `from`, transmogrified to use the symbolic scalar
type. The result is never nullptr.
@throws std::exception if `from` does not support symbolic
Usage: @code
MySystem<double> plant;
std::unique_ptr<MySystem<symbolic::Expression>> sym_plant =
systems::System<double>::ToSymbolic(plant);
@endcode
@tparam S The specific System pointer type to return.
See @ref system_scalar_conversion for detailed background and examples
related to scalar-type conversion support. */
template <template <typename> class S = ::drake::systems::System>
static std::unique_ptr<S<symbolic::Expression>> ToSymbolic(const S<T>& from) {
return System<T>::ToScalarType<symbolic::Expression>(from);
}
/** Creates a deep copy of this system exactly like ToSymbolic(), but returns
nullptr if this System does not support symbolic, instead of throwing an
exception. */
std::unique_ptr<System<symbolic::Expression>> ToSymbolicMaybe() const;
//@}
//----------------------------------------------------------------------------
/** @name Scalar type conversion utilities */
//@{
/** Fixes all of the input ports in @p target_context to their current values
in @p other_context, as evaluated by @p other_system.
@throws std::exception unless `other_context` and `target_context` both
have the same shape as this System, and the `other_system`. Ignores
disconnected inputs.
@throws std::exception if `this` system's scalar type T != double and
`other_system` has any abstract input ports whose contained type depends on
scalar type. */
void FixInputPortsFrom(const System<double>& other_system,
const Context<double>& other_context,
Context<T>* target_context) const;
/** (Advanced) Returns the SystemScalarConverter for this object. This is an
expert-level API intended for framework authors. Most users should
prefer the convenience helpers such as System::ToAutoDiffXd. */
const SystemScalarConverter& get_system_scalar_converter() const;
//@}
//----------------------------------------------------------------------------
/** @name Scalar type conversion by template parameter
These routines allow arbitrary scalar type conversion to be attempted. Not
all conversions will be supported, for various reasons.
- "Self conversions" (T=U) are not supported because the definitions would
be ambiguous with the (deleted) copy constructor.
- Derived systems may decline to support some scalar types.
*/
//@{
/** Creates a deep copy of this System, transmogrified to use the
scalar type selected by a template parameter. The result is never nullptr.
@throws std::exception if this System does not support the destination type.
@tparam U The destination scalar type. For a list of supported types, see the
@ref default_scalars "default scalars".
See @ref system_scalar_conversion for detailed background and examples
related to scalar-type conversion support. */
template <typename U>
std::unique_ptr<System<U>> ToScalarType() const {
return System<T>::ToScalarType<U>(*this);
}
/** Creates a deep copy of `from`, transmogrified to use the scalar
type selected by a template parameter. The result is never nullptr.
@throws std::exception if `from` does not support the destination type.
Usage: @code
MySystem<double> plant;
auto sym_plant =
systems::System<double>::ToScalarType<symbolic::Expression>(plant);
@endcode
@tparam U The destination scalar type. For a list of supported types, see the
@ref default_scalars "default scalars".
@tparam S The specific System pointer type to return.
See @ref system_scalar_conversion for detailed background and examples
related to scalar-type conversion support. */
template <typename U, template <typename> class S = ::drake::systems::System>
static std::unique_ptr<S<U>> ToScalarType(const S<T>& from) {
static_assert(std::is_base_of_v<System<T>, S<T>>);
auto base_result = from.template ToScalarTypeMaybe<U>();
if (!base_result) {
const System<T>& upcast_from = from;
throw std::logic_error(upcast_from.GetUnsupportedScalarConversionMessage(
typeid(T), typeid(U)));
}
return dynamic_pointer_cast_or_throw<S<U>>(std::move(base_result));
}
/** Creates a deep copy of this system exactly like ToScalarType(), but
returns nullptr if this System does not support the destination type, instead
of throwing an exception.
@tparam U The destination scalar type. For a list of supported types, see the
@ref default_scalars "default scalars".
*/
template <typename U>
std::unique_ptr<System<U>> ToScalarTypeMaybe() const {
auto result = system_scalar_converter_.Convert<U, T>(*this);
if (result) { result->AddExternalConstraints(external_constraints_); }
return result;
}
//@}
/** Gets the witness functions active for the given state.
DoGetWitnessFunctions() does the actual work. The vector of active witness
functions are expected to change only upon an unrestricted update.
@param context a valid context for the System (aborts if not true).
@param[out] w a valid pointer to an empty vector that will store
pointers to the witness functions active for the current
state. The method aborts if witnesses is null or non-empty. */
void GetWitnessFunctions(const Context<T>& context,
std::vector<const WitnessFunction<T>*>* w) const;
/** Evaluates a witness function at the given context. */
T CalcWitnessValue(const Context<T>& context,
const WitnessFunction<T>& witness_func) const;
/** Add `event` to `events` due to a witness function triggering. `events`
should be allocated with this system's AllocateCompositeEventCollection.
Neither `event` nor `events` can be nullptr. Additionally, `event` must
contain event data (event->get_event_data() must not be nullptr) and
the type of that data must be WitnessTriggeredEventData. */
virtual void AddTriggeredWitnessFunctionToCompositeEventCollection(
Event<T>* event,
CompositeEventCollection<T>* events) const = 0;
// Promote these frequently-used methods so users (and tutorial examples)
// don't need "this->" everywhere when in templated derived classes.
// All pre-defined ticket methods should be listed here. They are ordered as
// they appear in SystemBase to make it easy to check that none are missing.
using SystemBase::nothing_ticket;
using SystemBase::time_ticket;
using SystemBase::accuracy_ticket;
using SystemBase::q_ticket;
using SystemBase::v_ticket;
using SystemBase::z_ticket;
using SystemBase::xc_ticket;
using SystemBase::discrete_state_ticket;
using SystemBase::xd_ticket;
using SystemBase::abstract_state_ticket;
using SystemBase::xa_ticket;
using SystemBase::all_state_ticket;
using SystemBase::numeric_parameter_ticket;
using SystemBase::pn_ticket;
using SystemBase::abstract_parameter_ticket;
using SystemBase::pa_ticket;
using SystemBase::all_parameters_ticket;
using SystemBase::input_port_ticket;
using SystemBase::all_input_ports_ticket;
using SystemBase::all_sources_ticket;
using SystemBase::cache_entry_ticket;
using SystemBase::configuration_ticket;
using SystemBase::kinematics_ticket;
using SystemBase::xcdot_ticket;
using SystemBase::pe_ticket;
using SystemBase::ke_ticket;
using SystemBase::pc_ticket;
using SystemBase::pnc_ticket;
// Don't promote output_port_ticket() since it is for internal use only.
#ifndef DRAKE_DOXYGEN_CXX
// For unfortunate historical reasons the Drake Simulator needs access to
// forced publish events to implement its optional publish_every_time_step
// feature. Now we have PerStep events that serve the same purpose.
// Move this to protected with the other forced events when the Simulator
// feature is removed.
const EventCollection<PublishEvent<T>>&
get_forced_publish_events() const {
DRAKE_DEMAND(forced_publish_events_ != nullptr);
return *forced_publish_events_;
}
#endif
protected:
// Promote these frequently-used methods so users (and tutorial examples)
// don't need "this->" everywhere when in templated derived classes.
using SystemBase::DeclareCacheEntry;
/** (Internal use only) Static interface to
DoFindUniquePeriodicDiscreteUpdatesOrThrow() to allow a Diagram to invoke that
private method on its subsystems. */
static void FindUniquePeriodicDiscreteUpdatesOrThrow(
const char* api_name, const System<T>& system, const Context<T>& context,
std::optional<PeriodicEventData>* timing,
EventCollection<DiscreteUpdateEvent<T>>* events) {
DRAKE_DEMAND(timing != nullptr && events != nullptr);
system.ValidateContext(context);
system.DoFindUniquePeriodicDiscreteUpdatesOrThrow(api_name, context, timing,
events);
}
/** Derived classes will implement this method to evaluate a witness function
at the given context. */
virtual T DoCalcWitnessValue(
const Context<T>& context,
const WitnessFunction<T>& witness_func) const = 0;
/** Derived classes can override this method to provide witness functions
active for the given state. The default implementation does nothing. On
entry to this function, the context will have already been validated and
the vector of witness functions will have been validated to be both empty
and non-null. */
virtual void DoGetWitnessFunctions(const Context<T>&,
std::vector<const WitnessFunction<T>*>*) const;
//----------------------------------------------------------------------------
/** @name (Internal use only) Event handler dispatch mechanism
The pure virtuals declared here are intended to be implemented only by
Drake's LeafSystem and Diagram (plus a few unit tests) and those
implementations must be `final`.
For a LeafSystem, these functions need to call each event's handler callback,
For a LeafSystem, the pseudo code of the complete default publish event
handler dispatching is roughly:
<pre>
leaf_sys.Publish(context, event_collection)
-> leaf_sys.DispatchPublishHandler(context, event_collection)
for (event : event_collection_events):
if (event.has_handler)
event.handler(context)
</pre>
Discrete update events and unrestricted update events are dispatched
similarly for a LeafSystem. EventStatus is propagated upwards from the
individual event handlers with the first worst retained.
For a Diagram, these functions must iterate through all subsystems, extract
their corresponding subcontext and subevent collections from `context` and
`events`, and pass those to the subsystems' public non-virtual event
dispatchers if the subevent collection is nonempty (e.g. System::Publish()
for publish events).
All of these functions are only called from their corresponding public
non-virtual event dispatchers, where `context` is error checked. The
derived implementations can assume that `context` is valid. See, e.g.,
LeafSystem::DispatchPublishHandler() and Diagram::DispatchPublishHandler()
for more details. */
//@{
/** (Internal use only) This function dispatches all publish events to the
appropriate handlers. Only LeafSystem and Diagram (and some unit test code)
provide implementations and those must be `final`. */
[[nodiscard]] virtual EventStatus DispatchPublishHandler(
const Context<T>& context,
const EventCollection<PublishEvent<T>>& events) const = 0;
/** (Internal use only) This function dispatches all discrete update events to
the appropriate handlers. @p discrete_state cannot be null. Only LeafSystem
and Diagram (and some unit test code) provide implementations and those
must be `final`. */
[[nodiscard]] virtual EventStatus DispatchDiscreteVariableUpdateHandler(
const Context<T>& context,
const EventCollection<DiscreteUpdateEvent<T>>& events,
DiscreteValues<T>* discrete_state) const = 0;
/** (Internal use only) Updates the given `context` with the results returned
from a previous call to DispatchDiscreteVariableUpdateHandler() that handled
the given `events`. */
virtual void DoApplyDiscreteVariableUpdate(
const EventCollection<DiscreteUpdateEvent<T>>& events,
DiscreteValues<T>* discrete_state, Context<T>* context) const = 0;
/** (Internal use only) This function dispatches all unrestricted update
events to the appropriate handlers. @p state cannot be null. Only LeafSystem
and Diagram (and some unit test code) provide implementations and those must
be `final`. */
[[nodiscard]] virtual EventStatus DispatchUnrestrictedUpdateHandler(
const Context<T>& context,
const EventCollection<UnrestrictedUpdateEvent<T>>& events,
State<T>* state) const = 0;
/** (Internal use only) Updates the given `context` with the results returned
from a previous call to DispatchUnrestrictedUpdateHandler() that handled
the given `events`. */
virtual void DoApplyUnrestrictedUpdate(
const EventCollection<UnrestrictedUpdateEvent<T>>& events,
State<T>* state, Context<T>* context) const = 0;
//@}
//----------------------------------------------------------------------------
/** @name System construction
Authors of derived %Systems can use these methods in the constructor
for those %Systems. */
//@{
/** Constructs an empty %System base class object and allocates base class
resources, possibly supporting scalar-type conversion support (AutoDiff,
etc.) using @p converter.
See @ref system_scalar_conversion for detailed background and examples
related to scalar-type conversion support. */
explicit System(SystemScalarConverter converter);
/** Adds a port with the specified @p type and @p size to the input topology.
Input port names must be unique for this system (passing in a duplicate
@p name will throw std::exception). If @p name is given as
kUseDefaultName, then a default value of e.g. "u2", where 2
is the input number will be provided. An empty @p name is not permitted.
If the port is intended to model a random noise or disturbance input,
@p random_type can (optionally) be used to label it as such; doing so
enables algorithms for design and analysis (e.g. state estimation) to
reason explicitly about randomness at the system level. All random input
ports are assumed to be statistically independent.
@pre @p name must not be empty.
@throws std::exception for a duplicate port name.
@returns the declared port. */
InputPort<T>& DeclareInputPort(
std::variant<std::string, UseDefaultName> name, PortDataType type,
int size, std::optional<RandomDistribution> random_type = std::nullopt);
//@}
/** Adds an already-created constraint to the list of constraints for this
System. Ownership of the SystemConstraint is transferred to this system. */
SystemConstraintIndex AddConstraint(
std::unique_ptr<SystemConstraint<T>> constraint);
//----------------------------------------------------------------------------
/** @name Virtual methods for calculations
These virtuals allow concrete systems to implement the calculations
defined by the `Calc` methods in the public interface. Most have default
implementations that are usable for simple systems, but you are likely
to need to override some or all of these in your concrete system to
produce meaningful calculations.
These methods are invoked by the corresponding method in the public
interface that has the same name with `Do` removed. The public method
performs error checking on the arguments so you do not need to do so in
your implementation. Users cannot invoke these directly since they are
protected. You should place your overrides in the protected or private
sections of your concrete class. */
//@{
/** Override this if you have any continuous state variables x꜀ in your
concrete %System to calculate their time derivatives. The `derivatives`
vector will correspond elementwise with the state vector
`Context.state.continuous_state.get_state()`. Thus, if the state in the
Context has second-order structure `x꜀=[q v z]`, that same structure
applies to the derivatives.
This method is called only from the public non-virtual
CalcTimeDerivatives() which will already have error-checked the parameters
so you don't have to. In particular, implementations may assume that the
given Context is valid for this %System; that the `derivatives` pointer is
non-null, and that the referenced object has the same constituent
structure as was produced by AllocateTimeDerivatives().
The default implementation does nothing if the `derivatives` vector is
size zero and aborts otherwise. */
virtual void DoCalcTimeDerivatives(const Context<T>& context,
ContinuousState<T>* derivatives) const;
/** Override this if you have an efficient way to evaluate the implicit
time derivatives residual for this System. Otherwise the default
implementation is
`residual = proposed_derivatives − EvalTimeDerivatives(context)`. Note that
you cannot use the default implementation if you have changed the declared
residual size.
@note The public method has already verified that `proposed_derivatives`
is compatible with this System and that `residual` is non-null and of the
declared size (as reported by
SystemBase::implicit_time_derivatives_residual_size()). You do not have to
check those two conditions in your implementation, but if you have additional
restrictions you should validate that they are also met. */
virtual void DoCalcImplicitTimeDerivativesResidual(
const Context<T>& context, const ContinuousState<T>& proposed_derivatives,
EigenPtr<VectorX<T>> residual) const;
/** Computes the next time at which this System must perform a discrete
action.
Override this method if your System has any discrete actions which must
interrupt the continuous simulation. This method is called only from the
public non-virtual CalcNextUpdateTime() which will already have
error-checked the parameters so you don't have to. You may assume that
@p context has already been validated and @p events pointer is not
null.
If you override this method, you _must_ set the returned @p time. Set it to
Infinity if there are no upcoming timed events. If you return a finite update
time, you _must_ put at least one Event object in the @p events collection.
These requirements are enforced by the public CalcNextUpdateTime() method.
@note Despite the name, you must include publish events along with
state-updating events.
The default implementation returns with the next sample time being
Infinity and no events added to @p events. */
virtual void DoCalcNextUpdateTime(const Context<T>& context,
CompositeEventCollection<T>* events,
T* time) const;
/** Implement this method to return all periodic triggered events organized
by timing.
@see MapPeriodicEventsByTiming() for a detailed description of the returned
variable. */
virtual std::map<PeriodicEventData, std::vector<const Event<T>*>,
PeriodicEventDataComparator>
DoMapPeriodicEventsByTiming(const Context<T>& context) const = 0;
// TODO(sherm1) Move these three functions adjacent to the event
// dispatching functions and note that they are to be implemented only
// in Diagram and LeafSystem with `final` implementations. Make corresponding
// changes in Diagram and LeafSystem.
/** Implement this method to return any periodic events. @p events is cleared
in the public non-virtual GetPeriodicEvents(). You may assume that
@p context has already been validated and that @p events is not null.
@p events can be changed freely by the overriding implementation.
The default implementation returns without changing @p events.
@sa GetPeriodicEvents() */
virtual void DoGetPeriodicEvents(
const Context<T>& context,
CompositeEventCollection<T>* events) const;
/** Implement this method to return any events to be handled before the
simulator integrates the system's continuous state at each time step.
@p events is cleared in the public non-virtual GetPerStepEvents()
before that method calls this function. You may assume that @p context
has already been validated and that @p events is not null. @p events
can be changed freely by the overriding implementation.
The default implementation returns without changing @p events.
@sa GetPerStepEvents() */
virtual void DoGetPerStepEvents(
const Context<T>& context,
CompositeEventCollection<T>* events) const;
/** Implement this method to return any events to be handled at the
simulator's initialization step. @p events is cleared in the public
non-virtual GetInitializationEvents(). You may assume that @p context has
already been validated and that @p events is not null. @p events can be
changed freely by the overriding implementation.
The default implementation returns without changing @p events.
@sa GetInitializationEvents() */
virtual void DoGetInitializationEvents(
const Context<T>& context,
CompositeEventCollection<T>* events) const;
/** Override this method for physical systems to calculate the potential
energy PE currently stored in the configuration provided in the given
Context. The default implementation returns 0 which is correct for
non-physical systems. You may assume that `context` has already
been validated before it is passed to you here.
See EvalPotentialEnergy() for details on what you must compute here. In
particular, your potential energy method must _not_ depend explicitly on
time, velocities, or any input port values. */
virtual T DoCalcPotentialEnergy(const Context<T>& context) const;
/** Override this method for physical systems to calculate the kinetic
energy KE currently present in the motion provided in the given
Context. The default implementation returns 0 which is correct for
non-physical systems. You may assume that `context` has already
been validated before it is passed to you here.
See EvalKineticEnergy() for details on what you must compute here. In
particular, your kinetic energy method must _not_ depend explicitly on
time or any input port values. */
virtual T DoCalcKineticEnergy(const Context<T>& context) const;
/** Override this method to return the rate Pc at which mechanical energy is
being converted _from_ potential energy _to_ kinetic energy by this system
in the given Context. By default, returns zero. Physical systems should
override. You may assume that `context` has already been validated before
it is passed to you here.
See EvalConservativePower() for details on what you must compute here. In
particular, this quantity must be _positive_ when potential energy
is _decreasing_, and your conservative power method must _not_ depend
explicitly on time or any input port values. */
virtual T DoCalcConservativePower(const Context<T>& context) const;
/** Override this method to return the rate Pnc at which work W is done on the
system by non-conservative forces. By default, returns zero. Physical
systems should override. You may assume that `context` has already been
validated before it is passed to you here.
See EvalNonConservativePower() for details on what you must compute here.
In particular, this quantity must be _negative_ if the non-conservative
forces are _dissipative_, positive otherwise. Your non-conservative power
method can depend on anything you find in the given Context, including
time and input ports. */
virtual T DoCalcNonConservativePower(const Context<T>& context) const;
/** Provides the substantive implementation of MapQDotToVelocity().
The default implementation uses the identity mapping, and correctly does
nothing if the %System does not have second-order state variables. It
throws std::exception if the `generalized_velocity` and
`qdot` are not the same size, but that is not enough to guarantee that
the default implementation is adequate. Child classes must
override this function if qdot != v (even if they are the same size).
This occurs, for example, if a joint uses roll-pitch-yaw rotation angles
for orientation but angular velocity for rotational rate rather than
rotation angle derivatives.
If you implement this method you are required to use no more than `O(nq)`
time where `nq` is the size of `qdot`, so that the %System can meet the
performance guarantee made for the public interface, and you must also
implement DoMapVelocityToQDot(). Implementations may assume that `qdot`
has already been validated to be the same size as `q` in the given
Context, and that `generalized_velocity` is non-null. */
virtual void DoMapQDotToVelocity(const Context<T>& context,
const Eigen::Ref<const VectorX<T>>& qdot,
VectorBase<T>* generalized_velocity) const;
/** Provides the substantive implementation of MapVelocityToQDot().
The default implementation uses the identity mapping, and correctly does
nothing if the %System does not have second-order state variables. It
throws std::exception if the `generalized_velocity` (`v`) and
`qdot` are not the same size, but that is not enough to guarantee that
the default implementation is adequate. Child classes must
override this function if `qdot != v` (even if they are the same size).
This occurs, for example, if a joint uses roll-pitch-yaw rotation angles
for orientation but angular velocity for rotational rate rather than
rotation angle derivatives.
If you implement this method you are required to use no more than `O(nq)`
time where `nq` is the size of `qdot`, so that the %System can meet the
performance guarantee made for the public interface, and you must also
implement DoMapQDotToVelocity(). Implementations may assume that
`generalized_velocity` has already been validated to be the same size as
`v` in the given Context, and that `qdot` is non-null. */
virtual void DoMapVelocityToQDot(
const Context<T>& context,
const Eigen::Ref<const VectorX<T>>& generalized_velocity,
VectorBase<T>* qdot) const;
//@}
//----------------------------------------------------------------------------
/** @name Utility methods (protected) */
//@{
/** Returns a mutable Eigen expression for a vector valued output port with
index @p port_index in this system. All input ports that directly depend
on this output port will be notified that upstream data has changed, and
may invalidate cache entries as a result. */
Eigen::VectorBlock<VectorX<T>> GetMutableOutputVector(SystemOutput<T>* output,
int port_index) const;
//@}
bool forced_publish_events_exist() const {
return forced_publish_events_ != nullptr;
}
bool forced_discrete_update_events_exist() const {
return forced_discrete_update_events_ != nullptr;
}
bool forced_unrestricted_update_events_exist() const {
return forced_unrestricted_update_events_ != nullptr;
}
EventCollection<PublishEvent<T>>& get_mutable_forced_publish_events() {
DRAKE_DEMAND(forced_publish_events_ != nullptr);
return *forced_publish_events_;
}
EventCollection<DiscreteUpdateEvent<T>>&
get_mutable_forced_discrete_update_events() {
DRAKE_DEMAND(forced_discrete_update_events_ != nullptr);
return *forced_discrete_update_events_;
}
EventCollection<UnrestrictedUpdateEvent<T>>&
get_mutable_forced_unrestricted_update_events() {
DRAKE_DEMAND(forced_unrestricted_update_events_ != nullptr);
return *forced_unrestricted_update_events_;
}
const EventCollection<DiscreteUpdateEvent<T>>&
get_forced_discrete_update_events() const {
DRAKE_DEMAND(forced_discrete_update_events_ != nullptr);
return *forced_discrete_update_events_;
}
const EventCollection<UnrestrictedUpdateEvent<T>>&
get_forced_unrestricted_update_events() const {
DRAKE_DEMAND(forced_unrestricted_update_events_ != nullptr);
return *forced_unrestricted_update_events_;
}
void set_forced_publish_events(
std::unique_ptr<EventCollection<PublishEvent<T>>> forced) {
forced_publish_events_ = std::move(forced);
}
void set_forced_discrete_update_events(
std::unique_ptr<EventCollection<DiscreteUpdateEvent<T>>> forced) {
forced_discrete_update_events_ = std::move(forced);
}
void set_forced_unrestricted_update_events(
std::unique_ptr<EventCollection<UnrestrictedUpdateEvent<T>>> forced) {
forced_unrestricted_update_events_ = std::move(forced);
}
/** Returns the SystemScalarConverter for `this` system. */
SystemScalarConverter& get_mutable_system_scalar_converter() {
return system_scalar_converter_;
}
private:
// For any T1 & T2, System<T1> considers System<T2> a friend, so that System
// can safely and efficiently convert scalar types. See for example
// System<T>::ToScalarTypeMaybe.
template <typename> friend class System;
// Allocates an input of the leaf type that the System requires on the port
// specified by @p input_port. This is final in LeafSystem and Diagram.
virtual std::unique_ptr<AbstractValue> DoAllocateInput(
const InputPort<T>& input_port) const = 0;
// Allocates a composite event collection for use with this system.
// Implementers should not set system_id; that is done by the wrapping
// AllocateCompositeEventCollection method. This method is final in
// LeafSystem and Diagram.
virtual std::unique_ptr<CompositeEventCollection<T>>
DoAllocateCompositeEventCollection() const = 0;
/* Diagram and LeafSystem must provide `final` implementations of this that
return the set of all periodic discrete update events in this %System,
provided that they share a unique periodic timing. If PeriodicEventData is
provided by the caller, then that is the required timing. If not, then any
unique timing will do and you should set PeriodicEventData to that timing on
return. If there are no periodic discrete update events in this %System,
return quietly without touching `timing` or `events`.
@note This is a protected helper function for the Leaf and Diagram
implementations of CalcUniquePeriodicDiscreteUpdate() which will apply the
event handlers for the event collection returned here.
@note The definition of "unique periodic discrete update events" used here
should match the definition used by the public API
GetUniquePeriodicDiscreteUpdateAttribute(). However, the implementations are
necessarily independent.
@param[in] system The subsystem to be examined.
@param[in] context Compatible Context in case that's needed.
@param[in,out] timing If provided, the required timing. Otherwise set to
the discovered timing on return (if any).
@param[in,out] events A pre-allocated EventCollection of the appropriate
type for this %System. The set of periodic discrete events (if any) should
be _appended_ here on return.
@throws std::exception if PeriodicEventData is supplied and this %System
contains a periodic discrete event with different timing.
@throws std::exception if PeriodicEventData is not supplied and this %System
contains multiple periodic discrete update events with different timing.
@pre `timing` and `events` are non-null.
@see FindUniquePeriodicDiscreteUpdatesOrThrow() (static interface) */
virtual void DoFindUniquePeriodicDiscreteUpdatesOrThrow(
const char* api_name, const Context<T>& context,
std::optional<PeriodicEventData>* timing,
EventCollection<DiscreteUpdateEvent<T>>* events) const = 0;
std::function<void(const AbstractValue&)> MakeFixInputPortTypeChecker(
InputPortIndex port_index) const final;
// Shared code for updating a vector input port and returning a pointer to its
// value as a BasicVector<T>, or nullptr if the port is not connected. Throws
// a logic_error if the port_index is out of range or if the input port is not
// declared to be a vector-valued port. `func` should be the user-visible API
// function name obtained with __func__.
const BasicVector<T>* EvalBasicVectorInputImpl(
const char* func, const Context<T>& context,
InputPortIndex port_index) const;
// Adds "external" constraints to this System. This is a helper function to
// minimize inline bloat in scalar conversion; it is marked private since the
// signature matches the private data field type for efficiency.
void AddExternalConstraints(
const std::vector<ExternalSystemConstraint>& constraints);
// This is the computation function for EvalUniquePeriodicDiscreteUpdate()'s
// cache entry. Throws if an event handler fails.
void CalcUniquePeriodicDiscreteUpdate(
const Context<T>& context, DiscreteValues<T>* updated) const;
// The non-inline implementation of get_input_port().
const InputPort<T>& GetSoleInputPort() const;
// The non-inline implementation of get_output_port().
const OutputPort<T>& GetSoleOutputPort() const;
// The constraints_ vector encompass all constraints on this system, whether
// they were declared by a concrete subclass during construction (e.g., by
// calling DeclareInequalityConstraint), or added after construction (e.g.,
// by AddExternalConstraint). The constraints are listed in the order they
// were added, which means that the construction-time constraints will always
// appear earlier in the vector than the post-construction constraints.
std::vector<std::unique_ptr<SystemConstraint<T>>> constraints_;
// The external_constraints_ vector only contains constraints added after
// construction (e.g., by AddExternalConstraint), in the order they were
// added. The contents of this vector is only used during scalar conversion
// (so that the external constraints are preserved); for runtime calculations,
// only the constraints_ vector is used.
std::vector<ExternalSystemConstraint> external_constraints_;
// TODO(sherm1) Unify force-triggered events with publish, per-step, and
// initialization events (see leaf_system.h). These should be stored in
// a CompositeEventCollection, likely in LeafSystem. But consider instead
// moving the other collections up here so that the Diagram collections
// don't have to be reconstructed on the fly when accessed.
// These are only used to dispatch forced event handling. For a LeafSystem,
// these contain at least one kForced triggered event. For a Diagram, they
// are DiagramEventCollection, whose leafs are LeafEventCollection with
// one or more kForced triggered events.
std::unique_ptr<EventCollection<PublishEvent<T>>>
forced_publish_events_{nullptr};
std::unique_ptr<EventCollection<DiscreteUpdateEvent<T>>>
forced_discrete_update_events_{nullptr};
std::unique_ptr<EventCollection<UnrestrictedUpdateEvent<T>>>
forced_unrestricted_update_events_{nullptr};
// Functions to convert this system to use alternative scalar types.
SystemScalarConverter system_scalar_converter_;
CacheIndex time_derivatives_cache_index_;
CacheIndex potential_energy_cache_index_;
CacheIndex kinetic_energy_cache_index_;
CacheIndex conservative_power_cache_index_;
CacheIndex nonconservative_power_cache_index_;
CacheIndex unique_periodic_discrete_update_cache_index_;
};
} // namespace systems
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::System)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/diagram_builder.cc | #include "drake/systems/framework/diagram_builder.h"
#include <algorithm>
#include <sstream>
#include <stdexcept>
#include <tuple>
#include <unordered_map>
#include "drake/common/drake_assert.h"
#include "drake/common/drake_throw.h"
namespace drake {
namespace systems {
namespace {
/* Erases the i'th element of vec, shifting everything after it over by one. */
template <typename StdVector>
void VectorErase(StdVector* vec, size_t i) {
DRAKE_DEMAND(vec != nullptr);
const size_t size = vec->size();
DRAKE_DEMAND(i < size);
for (size_t hole = i; (hole + 1) < size; ++hole) {
(*vec)[hole] = std::move((*vec)[hole + 1]);
}
vec->pop_back();
}
} // namespace
template <typename T>
DiagramBuilder<T>::DiagramBuilder() {}
template <typename T>
DiagramBuilder<T>::~DiagramBuilder() {}
template <typename T>
void DiagramBuilder<T>::RemoveSystem(const System<T>& system) {
ThrowIfAlreadyBuilt();
if (!systems_.contains(&system)) {
throw std::logic_error(fmt::format(
"Cannot RemoveSystem on {} because it has not been added to this "
"DiagramBuilder",
system.GetSystemPathname()));
}
const size_t system_index = std::distance(
registered_systems_.begin(),
std::find_if(registered_systems_.begin(), registered_systems_.end(),
[&system](const std::unique_ptr<System<T>>& item) {
return item.get() == &system;
}));
DRAKE_DEMAND(system_index < registered_systems_.size());
// Un-export any input ports associated with this system.
// First, undo the ConnectInput.
std::set<std::string> disconnected_diagram_input_port_names;
for (size_t i = 0; i < input_port_ids_.size();) {
const InputPortLocator& locator = input_port_ids_[i];
if (locator.first == &system) {
const size_t num_erased = diagram_input_set_.erase(locator);
DRAKE_DEMAND(num_erased == 1);
disconnected_diagram_input_port_names.insert(
std::move(input_port_names_[i]));
VectorErase(&input_port_ids_, i);
VectorErase(&input_port_names_, i);
} else {
++i;
}
}
// Second, undo the DeclareInput (iff it was the last connected system).
for (const auto& name : disconnected_diagram_input_port_names) {
const bool num_connections =
std::count(input_port_names_.begin(), input_port_names_.end(), name);
if (num_connections == 0) {
const auto iter = diagram_input_indices_.find(name);
DRAKE_DEMAND(iter != diagram_input_indices_.end());
const InputPortIndex removed_index = iter->second;
VectorErase(&diagram_input_data_, removed_index);
diagram_input_indices_.erase(iter);
for (auto& [_, index] : diagram_input_indices_) {
if (index > removed_index) {
--index;
}
}
}
}
// Un-export any output ports associated with this system.
for (OutputPortIndex i{0}; i < output_port_ids_.size();) {
const OutputPortLocator& locator = output_port_ids_[i];
if (locator.first == &system) {
VectorErase(&output_port_ids_, i);
VectorErase(&output_port_names_, i);
} else {
++i;
}
}
// Disconnect any internal connections associated with this system.
for (auto iter = connection_map_.begin(); iter != connection_map_.end();) {
const auto& [input_locator, output_locator] = *iter;
if ((input_locator.first == &system) || (output_locator.first == &system)) {
iter = connection_map_.erase(iter);
} else {
++iter;
}
}
// Delete the system.
systems_.erase(&system);
VectorErase(®istered_systems_, system_index);
DRAKE_ASSERT_VOID(CheckInvariants());
}
template <typename T>
std::vector<const System<T>*> DiagramBuilder<T>::GetSystems() const {
ThrowIfAlreadyBuilt();
std::vector<const System<T>*> result;
result.reserve(registered_systems_.size());
for (const auto& system : registered_systems_) {
result.push_back(system.get());
}
return result;
}
template <typename T>
std::vector<System<T>*> DiagramBuilder<T>::GetMutableSystems() {
ThrowIfAlreadyBuilt();
std::vector<System<T>*> result;
result.reserve(registered_systems_.size());
for (const auto& system : registered_systems_) {
result.push_back(system.get());
}
return result;
}
template <typename T>
bool DiagramBuilder<T>::HasSubsystemNamed(std::string_view name) const {
for (const auto& child : registered_systems_) {
if (child->get_name() == name) {
return true;
}
}
return false;
}
template <typename T>
const System<T>& DiagramBuilder<T>::GetSubsystemByName(
std::string_view name) const {
ThrowIfAlreadyBuilt();
const System<T>* result = nullptr;
for (const auto& child : registered_systems_) {
if (child->get_name() == name) {
if (result != nullptr) {
throw std::logic_error(fmt::format(
"DiagramBuilder contains multiple subsystems named {} so cannot "
"provide a unique answer to a lookup by name",
name));
}
result = child.get();
// We can't return early here because we need to check the whole list
// for duplicate names.
}
}
if (result != nullptr) {
return *result;
}
throw std::logic_error(fmt::format(
"DiagramBuilder does not contain a subsystem named {}",
name));
}
template <typename T>
System<T>& DiagramBuilder<T>::GetMutableSubsystemByName(
std::string_view name) {
ThrowIfAlreadyBuilt();
return const_cast<System<T>&>(GetSubsystemByName(name));
}
template <typename T>
const std::map<typename DiagramBuilder<T>::InputPortLocator,
typename DiagramBuilder<T>::OutputPortLocator>&
DiagramBuilder<T>::connection_map() const {
ThrowIfAlreadyBuilt();
return connection_map_;
}
template <typename T>
void DiagramBuilder<T>::Connect(
const OutputPort<T>& src,
const InputPort<T>& dest) {
ThrowIfAlreadyBuilt();
InputPortLocator dest_id{&dest.get_system(), dest.get_index()};
OutputPortLocator src_id{&src.get_system(), src.get_index()};
ThrowIfSystemNotRegistered(&src.get_system());
ThrowIfSystemNotRegistered(&dest.get_system());
ThrowIfInputAlreadyWired(dest_id);
if (src.get_data_type() != dest.get_data_type()) {
throw std::logic_error(fmt::format(
"DiagramBuilder::Connect: Cannot mix vector-valued and abstract-"
"valued ports while connecting output port {} of System {} to "
"input port {} of System {}",
src.get_name(), src.get_system().get_name(),
dest.get_name(), dest.get_system().get_name()));
}
if ((src.get_data_type() != kAbstractValued) &&
(src.size() != dest.size())) {
throw std::logic_error(fmt::format(
"DiagramBuilder::Connect: Mismatched vector sizes while connecting "
"output port {} of System {} (size {}) to "
"input port {} of System {} (size {})",
src.get_name(), src.get_system().get_name(), src.size(),
dest.get_name(), dest.get_system().get_name(), dest.size()));
}
if (src.get_data_type() == kAbstractValued) {
auto model_output = src.Allocate();
auto model_input = dest.get_system().AllocateInputAbstract(dest);
const std::type_info& output_type = model_output->static_type_info();
const std::type_info& input_type = model_input->static_type_info();
if (output_type != input_type) {
throw std::logic_error(fmt::format(
"DiagramBuilder::Connect: Mismatched value types while connecting "
"output port {} of System {} (type {}) to "
"input port {} of System {} (type {})",
src.get_name(), src.get_system().get_name(),
NiceTypeName::Get(output_type),
dest.get_name(), dest.get_system().get_name(),
NiceTypeName::Get(input_type)));
}
}
connection_map_[dest_id] = src_id;
}
template <typename T>
void DiagramBuilder<T>::Connect(const System<T>& src, const System<T>& dest) {
ThrowIfAlreadyBuilt();
Connect(src.get_output_port(), dest.get_input_port());
}
template <typename T>
void DiagramBuilder<T>::Cascade(const System<T>& src, const System<T>& dest) {
ThrowIfAlreadyBuilt();
Connect(src, dest);
}
template <typename T>
InputPortIndex DiagramBuilder<T>::ExportInput(
const InputPort<T>& input,
std::variant<std::string, UseDefaultName> name) {
ThrowIfAlreadyBuilt();
const InputPortIndex diagram_port_index = DeclareInput(input, name);
ConnectInput(diagram_port_index, input);
return diagram_port_index;
}
template <typename T>
InputPortIndex DiagramBuilder<T>::DeclareInput(
const InputPort<T>& input,
std::variant<std::string, UseDefaultName> name) {
InputPortLocator id{&input.get_system(), input.get_index()};
ThrowIfSystemNotRegistered(&input.get_system());
// The requirement that subsystem names are unique guarantees uniqueness
// of the port names.
std::string port_name =
name == kUseDefaultName
? input.get_system().get_name() + "_" + input.get_name()
: std::get<std::string>(std::move(name));
DRAKE_DEMAND(!port_name.empty());
// Reject duplicate declarations.
if (diagram_input_indices_.contains(port_name)) {
throw std::logic_error(
fmt::format("Diagram already has an input port named {}", port_name));
}
// Save bookkeeping data.
const auto return_id = InputPortIndex(diagram_input_data_.size());
diagram_input_indices_[port_name] = return_id;
diagram_input_data_.push_back({id, std::move(port_name)});
return return_id;
}
template <typename T>
void DiagramBuilder<T>::ConnectInput(
std::string_view diagram_port_name, const InputPort<T>& input) {
ThrowIfAlreadyBuilt();
DRAKE_THROW_UNLESS(diagram_input_indices_.count(diagram_port_name));
const InputPortIndex diagram_port_index =
diagram_input_indices_.find(diagram_port_name)->second;
ConnectInput(diagram_port_index, input);
}
template <typename T>
void DiagramBuilder<T>::ConnectInput(
InputPortIndex diagram_port_index, const InputPort<T>& input) {
ThrowIfAlreadyBuilt();
InputPortLocator id{&input.get_system(), input.get_index()};
ThrowIfInputAlreadyWired(id);
ThrowIfSystemNotRegistered(&input.get_system());
DRAKE_THROW_UNLESS(
diagram_port_index < InputPortIndex(diagram_input_data_.size()));
// Check that port types match.
const ExportedInputData& data = diagram_input_data_[diagram_port_index];
const InputPortLocator& model_id = data.model_input;
const std::string& port_name = data.name;
const InputPort<T>& model = model_id.first->get_input_port(model_id.second);
if (model.get_data_type() != input.get_data_type()) {
throw std::logic_error(fmt::format(
"DiagramBuilder::ConnectInput: Cannot mix vector-valued and abstract-"
"valued ports while connecting input port {} of System {} to "
"input port {} of Diagram",
input.get_name(), input.get_system().get_name(), port_name));
}
if ((model.get_data_type() != kAbstractValued) &&
(model.size() != input.size())) {
throw std::logic_error(fmt::format(
"DiagramBuilder::ConnectInput: Mismatched vector sizes while "
"connecting input port {} of System {} (size {}) to "
"input port {} of Diagram (size {})",
input.get_name(), input.get_system().get_name(), input.size(),
port_name, model.size()));
}
if (model.get_data_type() == kAbstractValued) {
auto model_model = model.get_system().AllocateInputAbstract(model);
auto model_input = input.get_system().AllocateInputAbstract(input);
const std::type_info& model_type = model_model->static_type_info();
const std::type_info& input_type = model_input->static_type_info();
if (model_type != input_type) {
throw std::logic_error(fmt::format(
"DiagramBuilder::ConnectInput: Mismatched value types while "
"connecting input port {} of System {} (type {}) to "
"input port {} of Diagram (type {})",
input.get_name(), input.get_system().get_name(),
NiceTypeName::Get(input_type),
port_name, NiceTypeName::Get(model_type)));
}
}
// Write down connection information.
input_port_ids_.push_back(id);
input_port_names_.push_back(port_name);
diagram_input_set_.insert(id);
}
template <typename T>
bool DiagramBuilder<T>::ConnectToSame(
const InputPort<T>& exemplar, const InputPort<T>& dest) {
ThrowIfAlreadyBuilt();
ThrowIfSystemNotRegistered(&exemplar.get_system());
ThrowIfSystemNotRegistered(&dest.get_system());
InputPortLocator dest_id{&dest.get_system(), dest.get_index()};
ThrowIfInputAlreadyWired(dest_id);
// Check if `exemplar` was connected.
InputPortLocator exemplar_id{&exemplar.get_system(), exemplar.get_index()};
const auto iter = connection_map_.find(exemplar_id);
if (iter != connection_map_.end()) {
const OutputPortLocator& exemplar_loc = iter->second;
const OutputPort<T>& exemplar_port =
exemplar_loc.first->get_output_port(exemplar_loc.second);
Connect(exemplar_port, dest);
return true;
}
// Check if `exemplar` was exported.
if (diagram_input_set_.contains(exemplar_id)) {
for (size_t i = 0; i < input_port_ids_.size(); ++i) {
if (input_port_ids_[i] == exemplar_id) {
ConnectInput(input_port_names_[i], dest);
return true;
}
}
DRAKE_UNREACHABLE();
}
// The `exemplar` input was neither connected nor exported.
return false;
}
template <typename T>
OutputPortIndex DiagramBuilder<T>::ExportOutput(
const OutputPort<T>& output,
std::variant<std::string, UseDefaultName> name) {
ThrowIfAlreadyBuilt();
ThrowIfSystemNotRegistered(&output.get_system());
OutputPortIndex return_id(output_port_ids_.size());
output_port_ids_.push_back(
OutputPortLocator{&output.get_system(), output.get_index()});
// The requirement that subsystem names are unique guarantees uniqueness
// of the port names.
std::string port_name =
name == kUseDefaultName
? output.get_system().get_name() + "_" + output.get_name()
: std::get<std::string>(std::move(name));
DRAKE_DEMAND(!port_name.empty());
output_port_names_.emplace_back(std::move(port_name));
return return_id;
}
template <typename T>
std::unique_ptr<Diagram<T>> DiagramBuilder<T>::Build() {
ThrowIfAlreadyBuilt();
return std::unique_ptr<Diagram<T>>(new Diagram<T>(Compile()));
}
template <typename T>
void DiagramBuilder<T>::BuildInto(Diagram<T>* target) {
ThrowIfAlreadyBuilt();
target->Initialize(Compile());
}
template <typename T>
bool DiagramBuilder<T>::IsConnectedOrExported(const InputPort<T>& port) const {
ThrowIfAlreadyBuilt();
InputPortLocator id{&port.get_system(), port.get_index()};
if (this->connection_map_.contains(id) ||
this->diagram_input_set_.contains(id)) {
return true;
}
return false;
}
template <typename T>
int DiagramBuilder<T>::num_input_ports() const {
return input_port_names_.size();
}
template <typename T>
int DiagramBuilder<T>::num_output_ports() const {
return output_port_names_.size();
}
template <typename T>
void DiagramBuilder<T>::ThrowIfAlreadyBuilt() const {
if (already_built_) {
throw std::logic_error(
"DiagramBuilder: Build() or BuildInto() has already been called to "
"create a Diagram; this DiagramBuilder may no longer be used.");
}
}
template <typename T>
void DiagramBuilder<T>::ThrowIfInputAlreadyWired(
const InputPortLocator& id) const {
if (connection_map_.find(id) != connection_map_.end() ||
diagram_input_set_.find(id) != diagram_input_set_.end()) {
// Extract the name of the input port.
auto iter = std::find(input_port_ids_.begin(), input_port_ids_.end(), id);
DRAKE_DEMAND(iter != input_port_ids_.end()); // it should always be found.
int index = std::distance(input_port_ids_.begin(), iter);
throw std::logic_error(fmt::format("Input port {} is already connected.",
input_port_names_[index]));
}
}
template <typename T>
void DiagramBuilder<T>::ThrowIfSystemNotRegistered(
const System<T>* system) const {
DRAKE_DEMAND(system != nullptr);
if (!systems_.contains(system)) {
std::string registered_system_names{};
for (const auto& sys : registered_systems_) {
if (!registered_system_names.empty()) {
registered_system_names += ", ";
}
registered_system_names += '\'' + sys->get_name() + '\'';
}
if (registered_system_names.empty()) {
registered_system_names = "NONE";
}
throw std::logic_error(fmt::format(
"DiagramBuilder: System '{}' has not been registered to this "
"DiagramBuilder using AddSystem nor AddNamedSystem.\n\nThe systems "
"currently registered to this builder are: {}.\n\nIf '{}' was "
"registered as a subsystem to one of these, you must export the input "
"or output port using ExportInput/ExportOutput and then connect to the "
"exported port.",
system->get_name(), registered_system_names, system->get_name()));
}
}
namespace {
using EitherPortIndex = std::variant<InputPortIndex, OutputPortIndex>;
// The PortIdentifier must be appropriate to use in a sorted collection. Thus,
// we place its two integer indices first, because they form a unique key on
// their own (the variant disambiguates input vs output indices, even though
// their integer values overlap). The SystemBase* field is supplementary (and
// only used during error reporting).
using PortIdentifier = std::tuple<
SubsystemIndex, EitherPortIndex, const SystemBase*>;
bool is_input_port(const PortIdentifier& node) {
const EitherPortIndex& either = std::get<1>(node);
return either.index() == 0;
}
std::string to_string(const PortIdentifier& port_id) {
const SystemBase* const system = std::get<2>(port_id);
const EitherPortIndex& index = std::get<1>(port_id);
return is_input_port(port_id) ?
system->get_input_port_base(std::get<0>(index)).GetFullDescription() :
system->get_output_port_base(std::get<1>(index)).GetFullDescription();
}
// Helper to do the algebraic loop test. It recursively performs the
// depth-first search on the graph to find cycles.
bool HasCycleRecurse(
const PortIdentifier& n,
const std::map<PortIdentifier, std::set<PortIdentifier>>& edges,
std::set<PortIdentifier>* visited,
std::vector<PortIdentifier>* stack) {
DRAKE_ASSERT(!visited->contains(n));
visited->insert(n);
auto edge_iter = edges.find(n);
if (edge_iter != edges.end()) {
DRAKE_ASSERT(std::find(stack->begin(), stack->end(), n) == stack->end());
stack->push_back(n);
for (const auto& target : edge_iter->second) {
if (!visited->contains(target) &&
HasCycleRecurse(target, edges, visited, stack)) {
return true;
} else if (std::find(stack->begin(), stack->end(), target) !=
stack->end()) {
return true;
}
}
stack->pop_back();
}
return false;
}
} // namespace
template <typename T>
void DiagramBuilder<T>::ThrowIfAlgebraicLoopsExist() const {
// To discover loops, we will construct a digraph and check it for cycles.
// The nodes in the digraph are the input and output ports mentioned by the
// diagram's internal connections. Ports that are not internally connected
// cannot participate in a cycle, so we don't include them in the nodes set.
std::set<PortIdentifier> nodes;
// The edges in the digraph are a directed "influences" relation: for each
// `value` in `edges[key]`, the `key` influences `value`. (This is the
// opposite of the "depends-on" relation.)
std::map<PortIdentifier, std::set<PortIdentifier>> edges;
// Create a lookup table from system pointer to subsystem index.
std::unordered_map<const SystemBase*, SubsystemIndex> system_to_index;
for (SubsystemIndex i{0}; i < registered_systems_.size(); ++i) {
system_to_index.emplace(registered_systems_[i].get(), i);
}
// Add the diagram's internal connections to the digraph nodes *and* edges.
// The output port influences the input port.
for (const auto& item : connection_map_) {
const SystemBase* const input_system = item.first.first;
const InputPortIndex input_index = item.first.second;
const SystemBase* const output_system = item.second.first;
const OutputPortIndex output_index = item.second.second;
const PortIdentifier input{
system_to_index.at(input_system), input_index, input_system};
const PortIdentifier output{
system_to_index.at(output_system), output_index, output_system};
nodes.insert(input);
nodes.insert(output);
edges[output].insert(input);
}
// Add more edges (*not* nodes) based on each System's direct feedthrough.
// An input port influences an output port iff there is direct feedthrough
// from that input to that output. If a feedthrough edge refers to a port
// not in `nodes`, we omit it because ports that are not connected inside the
// diagram cannot participate in a cycle.
for (const auto& system_ptr : registered_systems_) {
const SystemBase* const system = system_ptr.get();
for (const auto& item : system->GetDirectFeedthroughs()) {
const SubsystemIndex subsystem_index = system_to_index.at(system);
const PortIdentifier input{
subsystem_index, InputPortIndex{item.first}, system};
const PortIdentifier output{
subsystem_index, OutputPortIndex{item.second}, system};
if (nodes.contains(input) && nodes.contains(output)) {
edges[input].insert(output);
}
}
}
static constexpr char kAdvice[] =
"A System may have conservatively reported that one of its output ports "
"depends on an input port, making one of the 'is direct-feedthrough to' "
"lines above spurious. If that is the case, remove the spurious "
"dependency per the Drake API documentation for declaring output ports. "
// NOLINTNEXTLINE(whitespace/line_length)
"https://drake.mit.edu/doxygen_cxx/classdrake_1_1systems_1_1_leaf_system.html#DeclareLeafOutputPort_feedthrough";
// Evaluate the graph for cycles.
std::set<PortIdentifier> visited;
std::vector<PortIdentifier> stack;
for (const auto& node : nodes) {
if (visited.contains(node)) {
continue;
}
if (HasCycleRecurse(node, edges, &visited, &stack)) {
std::stringstream message;
message << "Reported algebraic loop detected in DiagramBuilder:\n";
for (const auto& item : stack) {
message << " " << to_string(item);
if (is_input_port(item)) {
message << " is direct-feedthrough to\n";
} else {
message << " is connected to\n";
}
}
message << " " << to_string(stack.front()) << "\n";
message << kAdvice;
throw std::runtime_error(message.str());
}
}
}
template <typename T>
void DiagramBuilder<T>::CheckInvariants() const {
auto has_system = [this](const System<T>* system) {
return systems_.contains(system);
};
// The systems_ and registered_systems_ are identical sets.
DRAKE_DEMAND(systems_.size() == registered_systems_.size());
for (const auto& item : registered_systems_) {
DRAKE_DEMAND(has_system(item.get()));
}
// The connection_map_ only refers to registered systems.
for (const auto& [input, output] : connection_map_) {
DRAKE_DEMAND(has_system(input.first));
DRAKE_DEMAND(has_system(output.first));
}
// The input_port_ids_ and output_port_ids_ only refer to registered systems.
for (const auto& [system, _] : input_port_ids_) {
DRAKE_DEMAND(has_system(system));
}
for (const auto& [system, _] : output_port_ids_) {
DRAKE_DEMAND(has_system(system));
}
// The input_port_ids_ and diagram_input_set_ are identical sets.
DRAKE_DEMAND(input_port_ids_.size() == diagram_input_set_.size());
for (const auto& item : input_port_ids_) {
DRAKE_DEMAND(diagram_input_set_.find(item) != diagram_input_set_.end());
}
// The diagram_input_indices_ is the inverse of diagram_input_data_.
DRAKE_DEMAND(diagram_input_data_.size() == diagram_input_indices_.size());
for (const auto& [name, index] : diagram_input_indices_) {
DRAKE_DEMAND(diagram_input_data_.at(index).name == name);
}
}
template <typename T>
std::unique_ptr<typename Diagram<T>::Blueprint> DiagramBuilder<T>::Compile() {
if (registered_systems_.size() == 0) {
throw std::logic_error("Cannot Compile an empty DiagramBuilder.");
}
DRAKE_ASSERT_VOID(CheckInvariants());
ThrowIfAlgebraicLoopsExist();
auto blueprint = std::make_unique<typename Diagram<T>::Blueprint>();
blueprint->input_port_ids = input_port_ids_;
blueprint->input_port_names = input_port_names_;
blueprint->output_port_ids = output_port_ids_;
blueprint->output_port_names = output_port_names_;
blueprint->connection_map = connection_map_;
blueprint->systems = std::move(registered_systems_);
already_built_ = true;
return blueprint;
}
} // namespace systems
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::DiagramBuilder)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/continuous_state.h | #pragma once
#include <memory>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/drake_throw.h"
#include "drake/systems/framework/framework_common.h"
#include "drake/systems/framework/scalar_conversion_traits.h"
#include "drake/systems/framework/vector_base.h"
namespace drake {
namespace systems {
// TODO(sherm1) The ordering of the composite xc is useless and prevents us
// from describing every xc as a sequence [q v z]. Consider
// reimplementing so that xc=[q₁q₂ v₁v₂ z₁z₂].
/// %ContinuousState is a view of, and optionally a container for, all the
/// continuous state variables `xc` of a Drake System. Continuous state
/// variables are those whose values are defined by differential equations,
/// so we expect there to be a well-defined time derivative `xcdot` ≜ `d/dt xc`.
///
/// The contents of `xc` are conceptually partitioned into three groups:
///
/// - `q` is generalized position
/// - `v` is generalized velocity
/// - `z` is other continuous state
///
/// For a Drake LeafSystem these partitions are stored contiguously in memory
/// in this sequence: xc=[q v z]. But because a Drake System may be a Diagram
/// composed from subsystems, each with its own continuous state variables
/// ("substates"), the composite continuous state will not generally be stored
/// in contiguous memory. In that case the most we can say is that xc={q,v,z},
/// that is, it consists of all the q's, v's, and z's, in some order.
///
/// Nevertheless, this %ContinuousState class provides a vector
/// view of the data that groups together all the q partitions, v
/// partitions, and z partitions. For example, if there are three subsystems
/// (possibly Diagrams) whose continuous state variables are respectively
/// xc₁={q₁,v₁,z₁}, xc₂={q₂,v₂,z₂}, and xc₃={q₃,v₃,z₃} the composite xc includes
/// all the partitions in an undefined order. However, composite q, v, and z
/// appear ordered as q=[q₁ q₂ q₃], v=[v₁ v₂ v₃], z=[z₁ z₂ z₃]. Note that the
/// element ordering of the composite xc is _not_ a concatenation of the
/// composite subgroups. Do not index elements of the full state xc unless you
/// know it is the continuous state of a LeafSystem (a LeafSystem looking at its
/// own Context can depend on that).
///
/// Any of the groups may be empty. However, groups q and v must be either both
/// present or both empty, because the time derivative `qdot` of the
/// second-order state variables `q` must be computable using a linear mapping
/// `qdot=N(q)*v`.
///
/// The time derivative `xcdot` has the identical substructure to `xc`, with the
/// partitions interpreted as `qdot`, `vdot`, and `zdot`. We use identical
/// %ContinuousState objects for both.
///
/// <h4>Memory ownership</h4>
/// When a %ContinuousState represents the state of a LeafSystem, it always
/// owns the memory that is used for the state variables and is responsible
/// for destruction. For a Diagram, %ContinuousState can instead be a _view_
/// of the underlying LeafSystem substates, so that modifying the Diagram's
/// continuous state affects the LeafSystems appropriately. In that case, the
/// memory is owned by the underlying LeafSystems. However, when a
/// %ContinuousState object of any structure is cloned, the resulting object
/// _always_ owns all its underlying memory, which is initialized with a copy
/// of the original state variable values but is otherwise independent. The
/// cloned object retains the structure and ordering of the elements and does
/// not guarantee contiguous storage.
/// @see DiagramContinuousState for more information.
///
/// @tparam_default_scalar
template <typename T>
class ContinuousState {
public:
// ContinuousState is not copyable or moveable, but can be cloned with some
// caveats.
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ContinuousState)
/// Constructs a ContinuousState for a system that does not have second-order
/// structure. The `q` and `v` partitions are empty; all of the state `xc` is
/// miscellaneous continuous state `z`.
explicit ContinuousState(std::unique_ptr<VectorBase<T>> state);
/// Constructs a ContinuousState that exposes second-order structure.
///
/// @param state The source xc of continuous state information.
/// @param num_q The number of position variables q.
/// @param num_v The number of velocity variables v.
/// @param num_z The number of other continuous variables z.
///
/// We require that `num_q ≥ num_v` and that the sum of the partition sizes
/// adds up to the size of `state`.
ContinuousState(std::unique_ptr<VectorBase<T>> state, int num_q, int num_v,
int num_z);
/// Constructs a zero-length ContinuousState.
ContinuousState();
virtual ~ContinuousState();
/// Creates a deep copy of this object with the same substructure but with all
/// data owned by the copy. That is, if the original was a Diagram continuous
/// state that merely referenced substates, the clone will not include any
/// references to the original substates and is thus decoupled from the
/// Context containing the original. The concrete type of the BasicVector
/// underlying each leaf ContinuousState is preserved. See the class comments
/// above for more information.
std::unique_ptr<ContinuousState<T>> Clone() const;
/// Returns the size of the entire continuous state vector, which is
/// necessarily `num_q + num_v + num_z`.
int size() const { return get_vector().size(); }
/// Returns the number of generalized positions q in this state vector.
int num_q() const { return get_generalized_position().size(); }
/// Returns the number of generalized velocities v in this state vector.
int num_v() const { return get_generalized_velocity().size(); }
/// Returns the number of miscellaneous continuous state variables z
/// in this state vector.
int num_z() const { return get_misc_continuous_state().size(); }
T& operator[](std::size_t idx) { return (*state_)[idx]; }
const T& operator[](std::size_t idx) const { return (*state_)[idx]; }
/// Returns a reference to the entire continuous state vector.
const VectorBase<T>& get_vector() const {
DRAKE_ASSERT(state_ != nullptr);
return *state_;
}
/// Returns a mutable reference to the entire continuous state vector.
VectorBase<T>& get_mutable_vector() {
DRAKE_ASSERT(state_ != nullptr);
return *state_.get();
}
/// Returns a const reference to the subset of the state vector that is
/// generalized position `q`. May be zero length.
const VectorBase<T>& get_generalized_position() const {
return *generalized_position_;
}
/// Returns a mutable reference to the subset of the state vector that is
/// generalized position `q`. May be zero length.
VectorBase<T>& get_mutable_generalized_position() {
return *generalized_position_.get();
}
/// Returns a const reference to the subset of the continuous state vector
/// that is generalized velocity `v`. May be zero length.
const VectorBase<T>& get_generalized_velocity() const {
return *generalized_velocity_;
}
/// Returns a mutable reference to the subset of the continuous state vector
/// that is generalized velocity `v`. May be zero length.
VectorBase<T>& get_mutable_generalized_velocity() {
return *generalized_velocity_.get();
}
/// Returns a const reference to the subset of the continuous state vector
/// that is other continuous state `z`. May be zero length.
const VectorBase<T>& get_misc_continuous_state() const {
return *misc_continuous_state_;
}
/// Returns a mutable reference to the subset of the continuous state vector
/// that is other continuous state `z`. May be zero length.
VectorBase<T>& get_mutable_misc_continuous_state() {
return *misc_continuous_state_.get();
}
/// Copies the values from `other` into `this`, converting the scalar type as
/// necessary.
template <typename U>
void SetFrom(const ContinuousState<U>& other) {
DRAKE_THROW_UNLESS(size() == other.size());
DRAKE_THROW_UNLESS(num_q() == other.num_q());
DRAKE_THROW_UNLESS(num_v() == other.num_v());
DRAKE_THROW_UNLESS(num_z() == other.num_z());
SetFromVector(other.CopyToVector().unaryExpr(
scalar_conversion::ValueConverter<T, U>{}));
}
/// Sets the entire continuous state vector from an Eigen expression.
void SetFromVector(const Eigen::Ref<const VectorX<T>>& value) {
DRAKE_ASSERT(value.size() == state_->size());
this->get_mutable_vector().SetFromVector(value);
}
/// Returns a copy of the entire continuous state vector into an Eigen vector.
VectorX<T> CopyToVector() const { return this->get_vector().CopyToVector(); }
/** @name System compatibility
See @ref system_compatibility. */
//@{
/** (Internal) Gets the id of the subsystem that created this state. */
internal::SystemId get_system_id() const { return system_id_; }
/** (Internal) Records the id of the subsystem that created this state. */
void set_system_id(internal::SystemId id) { system_id_ = id; }
//@}
protected:
/// Constructs a continuous state that exposes second-order structure, with
/// no particular constraints on the layout.
///
/// @pre The q, v, z are all views into the same storage as @p state.
///
/// @param state The entire continuous state.
/// @param q The subset of state that is generalized position.
/// @param v The subset of state that is generalized velocity.
/// @param z The subset of state that is neither position nor velocity.
ContinuousState(std::unique_ptr<VectorBase<T>> state,
std::unique_ptr<VectorBase<T>> q,
std::unique_ptr<VectorBase<T>> v,
std::unique_ptr<VectorBase<T>> z);
/// DiagramContinuousState must override this to maintain the necessary
/// internal substructure, and to perform a deep copy so that the result
/// owns all its own data. The default implementation here requires that the
/// full state is a BasicVector (that is, this is a leaf continuous state).
/// The BasicVector is cloned to preserve its concrete type and contents,
/// then the q, v, z Subvectors are created referencing it.
/// The implementation should not set_system_id on the result, the caller
/// will set an id on the state after this method returns.
virtual std::unique_ptr<ContinuousState> DoClone() const;
private:
// Demand that the representation invariants hold.
void DemandInvariants() const;
// The entire continuous state vector. May or may not own the underlying
// data.
std::unique_ptr<VectorBase<T>> state_;
// Generalized coordinates representing System configuration, conventionally
// denoted `q`. These are second-order state variables.
// This is a subset of state_ and does not own the underlying data.
std::unique_ptr<VectorBase<T>> generalized_position_;
// Generalized speeds representing System velocity. Conventionally denoted
// `v`. These are first-order state variables that the System can linearly
// map to time derivatives `qdot` of `q` above.
// This is a subset of state_ and does not own the underlying data.
std::unique_ptr<VectorBase<T>> generalized_velocity_;
// Additional continuous, first-order state variables not representing
// multibody system motion. Conventionally denoted `z`.
// This is a subset of state_ and does not own the underlying data.
std::unique_ptr<VectorBase<T>> misc_continuous_state_;
// Unique id of the subsystem that created this state.
internal::SystemId system_id_;
};
} // namespace systems
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::ContinuousState)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/leaf_system.h | #pragma once
#include <functional>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/common/unused.h"
#include "drake/common/value.h"
#include "drake/systems/framework/abstract_value_cloner.h"
#include "drake/systems/framework/abstract_values.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/continuous_state.h"
#include "drake/systems/framework/discrete_values.h"
#include "drake/systems/framework/leaf_context.h"
#include "drake/systems/framework/leaf_output_port.h"
#include "drake/systems/framework/model_values.h"
#include "drake/systems/framework/system.h"
#include "drake/systems/framework/system_constraint.h"
#include "drake/systems/framework/system_output.h"
#include "drake/systems/framework/system_scalar_converter.h"
#include "drake/systems/framework/value_producer.h"
namespace drake {
namespace systems {
/** A superclass template that extends System with some convenience utilities
that are not applicable to Diagrams.
@tparam_default_scalar */
template <typename T>
class LeafSystem : public System<T> {
public:
// LeafSystem objects are neither copyable nor moveable.
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LeafSystem)
~LeafSystem() override;
/** Shadows System<T>::AllocateContext to provide a more concrete return
type LeafContext<T>. */
std::unique_ptr<LeafContext<T>> AllocateContext() const;
// =========================================================================
// Implementations of System<T> methods.
#ifndef DRAKE_DOXYGEN_CXX
// The three methods below are hidden from doxygen, as described in
// documentation for their corresponding methods in System.
std::unique_ptr<EventCollection<PublishEvent<T>>>
AllocateForcedPublishEventCollection() const override;
std::unique_ptr<EventCollection<DiscreteUpdateEvent<T>>>
AllocateForcedDiscreteUpdateEventCollection() const override;
std::unique_ptr<EventCollection<UnrestrictedUpdateEvent<T>>>
AllocateForcedUnrestrictedUpdateEventCollection() const override;
#endif
std::unique_ptr<ContextBase> DoAllocateContext() const final;
/** Default implementation: sets all numeric parameters to the model vector
given to DeclareNumericParameter, or else if no model was provided sets
the numeric parameter to one. It sets all abstract parameters to the
model value given to DeclareAbstractParameter. Overrides must not change
the number of parameters. */
void SetDefaultParameters(const Context<T>& context,
Parameters<T>* parameters) const override;
/** Default implementation: sets all continuous state to the model vector
given in DeclareContinuousState (or zero if no model vector was given) and
discrete states to zero. Overrides must not change the number of state
variables. */
void SetDefaultState(const Context<T>& context,
State<T>* state) const override;
std::unique_ptr<ContinuousState<T>> AllocateTimeDerivatives() const final;
std::unique_ptr<DiscreteValues<T>> AllocateDiscreteVariables() const final;
std::multimap<int, int> GetDirectFeedthroughs() const final;
protected:
// Promote so we don't need "this->" in defaults which show up in Doxygen.
using SystemBase::all_sources_ticket;
/** Default constructor that declares no inputs, outputs, state, parameters,
events, nor scalar-type conversion support (AutoDiff, etc.). To enable
AutoDiff support, use the SystemScalarConverter-based constructor. */
LeafSystem();
/** Constructor that declares no inputs, outputs, state, parameters, or
events, but allows subclasses to declare scalar-type conversion support
(AutoDiff, etc.).
The scalar-type conversion support will use @p converter.
To enable scalar-type conversion support, pass a `SystemTypeTag<S>{}`
where `S` must be the exact class of `this` being constructed.
See @ref system_scalar_conversion for detailed background and examples
related to scalar-type conversion support. */
explicit LeafSystem(SystemScalarConverter converter);
/** Provides a new instance of the leaf context for this system. Derived
leaf systems with custom derived leaf system contexts should override this
to provide a context of the appropriate type. The returned context should
be "empty"; invoked by AllocateContext(), the caller will take the
responsibility to initialize the core LeafContext data. The default
implementation provides a default-constructed `LeafContext<T>`. */
virtual std::unique_ptr<LeafContext<T>> DoMakeLeafContext() const;
/** Derived classes that impose restrictions on what resources are permitted
should check those restrictions by implementing this. For example, a
derived class might require a single input and single output. Note that
the supplied Context will be complete except that input and output
dependencies on peer and parent subcontexts will not yet have been set up,
so you may not consider them for validation.
The default implementation does nothing. */
virtual void DoValidateAllocatedLeafContext(
const LeafContext<T>& context) const {
unused(context);
}
// =========================================================================
// Implementations of System<T> methods.
T DoCalcWitnessValue(const Context<T>& context,
const WitnessFunction<T>& witness_func) const final;
void AddTriggeredWitnessFunctionToCompositeEventCollection(
Event<T>* event,
CompositeEventCollection<T>* events) const final;
/** Computes the next update time based on the configured periodic events, for
scalar types that are arithmetic, or aborts for scalar types that are not
arithmetic. Subclasses that require aperiodic events should override, but
be sure to invoke the parent class implementation at the start of the
override if you want periodic events to continue to be handled.
@post `time` is set to a value greater than or equal to
`context.get_time()` on return.
@warning If you override this method, think carefully before setting
`time` to `context.get_time()` on return, which can inadvertently
cause simulations of systems derived from %LeafSystem to loop
interminably. Such a loop will occur if, for example, the
event(s) does not modify the state. */
void DoCalcNextUpdateTime(const Context<T>& context,
CompositeEventCollection<T>* events,
T* time) const override;
// =========================================================================
// Allocation helper utilities.
/** Returns a copy of the state declared in the most recent
DeclareContinuousState() call, or else a zero-sized state if that method
has never been called. */
std::unique_ptr<ContinuousState<T>> AllocateContinuousState() const;
/** Returns a copy of the states declared in DeclareDiscreteState() calls. */
std::unique_ptr<DiscreteValues<T>> AllocateDiscreteState() const;
/** Returns a copy of the states declared in DeclareAbstractState() calls. */
std::unique_ptr<AbstractValues> AllocateAbstractState() const;
/** Returns a copy of the parameters declared in DeclareNumericParameter()
and DeclareAbstractParameter() calls. */
std::unique_ptr<Parameters<T>> AllocateParameters() const;
// =========================================================================
// New methods for subclasses to use
/** Declares a numeric parameter using the given @p model_vector.
LeafSystem's default implementation of SetDefaultParameters() will reset
parameters to their model vectors. If the @p model_vector declares any
VectorBase::GetElementBounds() constraints, they will be re-declared as
inequality constraints on this system (see
DeclareInequalityConstraint()). Returns the index of the new parameter. */
int DeclareNumericParameter(const BasicVector<T>& model_vector);
/** Extracts the numeric parameters of type U from the @p context at @p index.
Asserts if the context is not a LeafContext, or if it does not have a
vector-valued parameter of type U at @p index. */
template <template <typename> class U = BasicVector>
const U<T>& GetNumericParameter(const Context<T>& context, int index) const {
this->ValidateContext(context);
static_assert(std::is_base_of_v<BasicVector<T>, U<T>>,
"U must be a subclass of BasicVector.");
const auto& leaf_context =
dynamic_cast<const systems::LeafContext<T>&>(context);
const auto* const params =
dynamic_cast<const U<T>*>(&leaf_context.get_numeric_parameter(index));
DRAKE_ASSERT(params != nullptr);
return *params;
}
/** Extracts the numeric parameters of type U from the @p context at @p index.
Asserts if the context is not a LeafContext, or if it does not have a
vector-valued parameter of type U at @p index. */
template <template <typename> class U = BasicVector>
U<T>& GetMutableNumericParameter(Context<T>* context, int index) const {
this->ValidateContext(context);
static_assert(std::is_base_of_v<BasicVector<T>, U<T>>,
"U must be a subclass of BasicVector.");
auto* leaf_context = dynamic_cast<systems::LeafContext<T>*>(context);
DRAKE_ASSERT(leaf_context != nullptr);
auto* const params = dynamic_cast<U<T>*>(
&leaf_context->get_mutable_numeric_parameter(index));
DRAKE_ASSERT(params != nullptr);
return *params;
}
/** Declares an abstract parameter using the given @p model_value.
LeafSystem's default implementation of SetDefaultParameters() will reset
parameters to their model values. Returns the index of the new
parameter. */
int DeclareAbstractParameter(const AbstractValue& model_value);
// =========================================================================
/** @anchor declare_periodic_events
@name Declare periodic events
Methods in this group declare that this System has an event that
is triggered periodically. The first periodic trigger will occur at
t = `offset_sec`, and it will recur at every `period_sec` thereafter.
Several signatures are provided to allow for a general Event object to be
triggered or for simpler class member functions to be invoked instead.
Reaching a designated time causes a periodic event to be dispatched
to one of the three available types of event dispatcher: publish (read
only), discrete update, and unrestricted update.
@note If you want to handle timed events that are _not_ periodic
(timers, alarms, etc.), overload DoCalcNextUpdateTime() rather than using
the methods in this section.
Template arguments to these methods are inferred from the argument lists
and need not be specified explicitly.
@pre `period_sec` > 0 and `offset_sec` ≥ 0. */
//@{
/** Declares that a Publish event should occur periodically and that it should
invoke the given event handler method. The handler should be a class
member function (method) with this signature:
@code
EventStatus MySystem::MyPublish(const Context<T>&) const;
@endcode
where `MySystem` is a class derived from `LeafSystem<T>` and the method
name is arbitrary.
See @ref declare_periodic_events "Declare periodic events" for more
information.
@pre `this` must be dynamic_cast-able to MySystem.
@pre `publish` must not be null.
@see DeclarePeriodicDiscreteUpdateEvent()
@see DeclarePeriodicUnrestrictedUpdateEvent()
@see DeclarePeriodicEvent() */
template <class MySystem>
void DeclarePeriodicPublishEvent(
double period_sec, double offset_sec,
EventStatus (MySystem::*publish)(const Context<T>&) const) {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived System.");
DRAKE_DEMAND(publish != nullptr);
DeclarePeriodicEvent(
period_sec, offset_sec,
PublishEvent<T>(TriggerType::kPeriodic, [publish](
const System<T>& system,
const Context<T>& context,
const PublishEvent<T>&) {
const auto& sys = dynamic_cast<const MySystem&>(system);
return (sys.*publish)(context);
}));
}
/** This variant accepts a handler that is assumed to succeed rather than
one that returns an EventStatus result. The handler signature is:
@code
void MySystem::MyPublish(const Context<T>&) const;
@endcode
See the other signature for more information.
@exclude_from_pydrake_mkdoc{This overload is not bound.} */
template <class MySystem>
void DeclarePeriodicPublishEvent(double period_sec, double offset_sec,
void (MySystem::*publish)(const Context<T>&)
const) {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived System.");
DRAKE_DEMAND(publish != nullptr);
DeclarePeriodicEvent(
period_sec, offset_sec,
PublishEvent<T>(
TriggerType::kPeriodic,
[publish](const System<T>& system,
const Context<T>& context,
const PublishEvent<T>&) {
const auto& sys = dynamic_cast<const MySystem&>(system);
(sys.*publish)(context);
return EventStatus::Succeeded();
}));
}
/** Declares that a DiscreteUpdate event should occur periodically and that it
should invoke the given event handler method. The handler should be a
class member function (method) with this signature:
@code
EventStatus MySystem::MyUpdate(const Context<T>&,
DiscreteValues<T>*) const;
@endcode
where `MySystem` is a class derived from `LeafSystem<T>` and the method
name is arbitrary.
See @ref declare_periodic_events "Declare periodic events" for more
information.
@pre `this` must be dynamic_cast-able to MySystem.
@pre `update` must not be null.
@see DeclarePeriodicPublishEvent()
@see DeclarePeriodicUnrestrictedUpdateEvent()
@see DeclarePeriodicEvent() */
template <class MySystem>
void DeclarePeriodicDiscreteUpdateEvent(
double period_sec, double offset_sec,
EventStatus (MySystem::*update)(const Context<T>&, DiscreteValues<T>*)
const) {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived System.");
DRAKE_DEMAND(update != nullptr);
DeclarePeriodicEvent(
period_sec, offset_sec,
DiscreteUpdateEvent<T>(
TriggerType::kPeriodic,
[update](const System<T>& system,
const Context<T>& context,
const DiscreteUpdateEvent<T>&,
DiscreteValues<T>* xd) {
const auto& sys = dynamic_cast<const MySystem&>(system);
return (sys.*update)(context, &*xd);
}));
}
/** This variant accepts a handler that is assumed to succeed rather than
one that returns an EventStatus result. The handler signature is:
@code
void MySystem::MyUpdate(const Context<T>&,
DiscreteValues<T>*) const;
@endcode
See the other signature for more information.
@exclude_from_pydrake_mkdoc{This overload is not bound.} */
template <class MySystem>
void DeclarePeriodicDiscreteUpdateEvent(
double period_sec, double offset_sec,
void (MySystem::*update)(const Context<T>&, DiscreteValues<T>*) const) {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived System.");
DRAKE_DEMAND(update != nullptr);
DeclarePeriodicEvent(
period_sec, offset_sec,
DiscreteUpdateEvent<T>(
TriggerType::kPeriodic,
[update](const System<T>& system,
const Context<T>& context,
const DiscreteUpdateEvent<T>&,
DiscreteValues<T>* xd) {
const auto& sys = dynamic_cast<const MySystem&>(system);
(sys.*update)(context, &*xd);
return EventStatus::Succeeded();
}));
}
/** Declares that an UnrestrictedUpdate event should occur periodically and
that it should invoke the given event handler method. The handler should
be a class member function (method) with this signature:
@code
EventStatus MySystem::MyUpdate(const Context<T>&, State<T>*) const;
@endcode
where `MySystem` is a class derived from `LeafSystem<T>` and the method
name is arbitrary.
See @ref declare_periodic_events "Declare periodic events" for more
information.
@pre `this` must be dynamic_cast-able to MySystem.
@pre `update` must not be null.
@see DeclarePeriodicPublishEvent()
@see DeclarePeriodicDiscreteUpdateEvent()
@see DeclarePeriodicEvent() */
template <class MySystem>
void DeclarePeriodicUnrestrictedUpdateEvent(
double period_sec, double offset_sec,
EventStatus (MySystem::*update)(const Context<T>&, State<T>*) const) {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived System.");
DRAKE_DEMAND(update != nullptr);
DeclarePeriodicEvent(
period_sec, offset_sec,
UnrestrictedUpdateEvent<T>(
TriggerType::kPeriodic,
[update](const System<T>& system,
const Context<T>& context,
const UnrestrictedUpdateEvent<T>&, State<T>* x) {
const auto& sys = dynamic_cast<const MySystem&>(system);
return (sys.*update)(context, &*x);
}));
}
/** This variant accepts a handler that is assumed to succeed rather than
one that returns an EventStatus result. The handler signature is:
@code
void MySystem::MyUpdate(const Context<T>&, State<T>*) const;
@endcode
See the other signature for more information.
@exclude_from_pydrake_mkdoc{This overload is not bound.} */
template <class MySystem>
void DeclarePeriodicUnrestrictedUpdateEvent(
double period_sec, double offset_sec,
void (MySystem::*update)(const Context<T>&, State<T>*) const) {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived System.");
DRAKE_DEMAND(update != nullptr);
DeclarePeriodicEvent(
period_sec, offset_sec,
UnrestrictedUpdateEvent<T>(
TriggerType::kPeriodic,
[update](const System<T>& system, const Context<T>& context,
const UnrestrictedUpdateEvent<T>&, State<T>* x) {
const auto& sys = dynamic_cast<const MySystem&>(system);
(sys.*update)(context, &*x);
return EventStatus::Succeeded();
}));
}
/** (Advanced) Declares that a particular Event object should be dispatched
periodically. This is the most general form for declaring periodic events
and most users should use one of the other methods in this group instead.
@see DeclarePeriodicPublishEvent()
@see DeclarePeriodicDiscreteUpdateEvent()
@see DeclarePeriodicUnrestrictedUpdateEvent()
See @ref declare_periodic_events "Declare periodic events" for more
information.
Depending on the type of `event`, when triggered it will be passed to
the Publish, DiscreteUpdate, or UnrestrictedUpdate event dispatcher. If
the `event` object contains a handler function, Drake's default
dispatchers will invoke that handler. If not, then no further action is
taken. Thus an `event` with no handler has no effect unless its dispatcher
has been overridden. We strongly recommend that you _do not_ override the
dispatcher and instead _do_ supply a handler.
The given `event` object is deep-copied (cloned), and the copy is stored
internally so you do not need to keep the object around after this call.
@pre `event`'s associated trigger type must be TriggerType::kUnknown or
already set to TriggerType::kPeriodic. */
template <typename EventType>
void DeclarePeriodicEvent(double period_sec, double offset_sec,
const EventType& event) {
DRAKE_DEMAND(event.get_trigger_type() == TriggerType::kUnknown ||
event.get_trigger_type() == TriggerType::kPeriodic);
PeriodicEventData periodic_data;
periodic_data.set_period_sec(period_sec);
periodic_data.set_offset_sec(offset_sec);
auto event_copy = event.Clone();
event_copy->set_trigger_type(TriggerType::kPeriodic);
event_copy->set_event_data(periodic_data);
event_copy->AddToComposite(TriggerType::kPeriodic, &periodic_events_);
}
//@}
// =========================================================================
/** @anchor declare_per-step_events
@name Declare per-step events
These methods are used to declare events that are triggered whenever the
Drake Simulator advances the simulated trajectory. Note that each call to
Simulator::AdvanceTo() typically generates many trajectory-advancing
steps of varying time intervals; per-step events are triggered for each
of those steps.
Per-step events are useful for taking discrete action at every point of a
simulated trajectory (generally spaced irregularly in time) without
missing anything. For example, per-step events can be used to implement
a high-accuracy signal delay by maintaining a buffer of past signal
values, updated at each step. Because the steps are smaller in regions
of rapid change, the interpolated signal retains the accuracy provided
by the denser sampling. A periodic sampling would produce less-accurate
interpolations.
As with any Drake event trigger type, a per-step event is dispatched to
one of the three available types of event dispatcher: publish (read only),
discrete state update, and unrestricted state update. Several signatures
are provided below to allow for a general Event object to be triggered, or
simpler class member functions to be invoked instead.
Per-step events are issued as follows: First, the Simulator::Initialize()
method queries and records the set of declared per-step events. That set
does not change during a simulation. Any per-step publish events are
dispatched at the end of Initialize() to publish the initial value of the
trajectory. Then every AdvanceTo() internal step dispatches unrestricted
and discrete update events at the start of the step, and dispatches
publish events at the end of the step (that is, after time advances).
This means that a per-step event at fixed step size h behaves
identically to a periodic event of period h, offset 0.
Template arguments to these methods are inferred from the argument lists
and need not be specified explicitly. */
//@{
/** Declares that a Publish event should occur at initialization and at the
end of every trajectory-advancing step and that it should invoke the
given event handler method. The handler should be a class member function
(method) with this signature:
@code
EventStatus MySystem::MyPublish(const Context<T>&) const;
@endcode
where `MySystem` is a class derived from `LeafSystem<T>` and the method
name is arbitrary.
@warning These per-step publish events are independent of the Simulator's
optional "publish every time step" and "publish at initialization"
features. Generally if you are declaring per-step publish events yourself
you should turn off those Simulation options.
See @ref declare_per-step_events "Declare per-step events" for more
information.
@pre `this` must be dynamic_cast-able to MySystem.
@pre `publish` must not be null.
@see DeclarePerStepDiscreteUpdateEvent()
@see DeclarePerStepUnrestrictedUpdateEvent()
@see DeclarePerStepEvent()
@see Simulator::set_publish_at_initialization()
@see Simulator::set_publish_every_time_step() */
template <class MySystem>
void DeclarePerStepPublishEvent(
EventStatus (MySystem::*publish)(const Context<T>&) const) {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived System.");
DRAKE_DEMAND(publish != nullptr);
DeclarePerStepEvent<PublishEvent<T>>(PublishEvent<T>(
TriggerType::kPerStep,
[publish](const System<T>& system, const Context<T>& context,
const PublishEvent<T>&) {
const auto& sys = dynamic_cast<const MySystem&>(system);
return (sys.*publish)(context);
}));
}
/** Declares that a DiscreteUpdate event should occur at the start of every
trajectory-advancing step and that it should invoke the given event
handler method. The handler should be a class member function (method)
with this signature:
@code
EventStatus MySystem::MyUpdate(const Context<T>&,
DiscreteValues<T>*) const;
@endcode
where `MySystem` is a class derived from `LeafSystem<T>` and the method
name is arbitrary.
See @ref declare_per-step_events "Declare per-step events" for more
information.
@pre `this` must be dynamic_cast-able to MySystem.
@pre `update` must not be null.
@see DeclarePerStepPublishEvent()
@see DeclarePerStepUnrestrictedUpdateEvent()
@see DeclarePerStepEvent() */
template <class MySystem>
void DeclarePerStepDiscreteUpdateEvent(EventStatus (MySystem::*update)(
const Context<T>&, DiscreteValues<T>*) const) {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived System.");
DRAKE_DEMAND(update != nullptr);
DeclarePerStepEvent(
DiscreteUpdateEvent<T>(
TriggerType::kPerStep,
[update](const System<T>& system, const Context<T>& context,
const DiscreteUpdateEvent<T>&, DiscreteValues<T>* xd) {
const auto& sys = dynamic_cast<const MySystem&>(system);
return (sys.*update)(context, &*xd);
}));
}
/** Declares that an UnrestrictedUpdate event should occur at the start of
every trajectory-advancing step and that it should invoke the given
event handler method. The handler should be a class member function
(method) with this signature:
@code
EventStatus MySystem::MyUpdate(const Context<T>&,
State<T>*) const;
@endcode
where `MySystem` is a class derived from `LeafSystem<T>` and the method
name is arbitrary.
See @ref declare_per-step_events "Declare per-step events" for more
information.
@pre `this` must be dynamic_cast-able to MySystem.
@pre `update` must not be null.
@see DeclarePerStepPublishEvent()
@see DeclarePerStepDiscreteUpdateEvent()
@see DeclarePerStepEvent() */
template <class MySystem>
void DeclarePerStepUnrestrictedUpdateEvent(
EventStatus (MySystem::*update)(const Context<T>&, State<T>*) const) {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived System.");
DRAKE_DEMAND(update != nullptr);
DeclarePerStepEvent(UnrestrictedUpdateEvent<T>(
TriggerType::kPerStep,
[update](const System<T>& system, const Context<T>& context,
const UnrestrictedUpdateEvent<T>&, State<T>* x) {
const auto& sys = dynamic_cast<const MySystem&>(system);
return (sys.*update)(context, &*x);
}));
}
/** (Advanced) Declares that a particular Event object should be dispatched at
every trajectory-advancing step. Publish events are dispatched at
the end of initialization and at the end of each step. Discrete- and
unrestricted update events are dispatched at the start of each step.
This is the most general form for declaring per-step events and most users
should use one of the other methods in this group instead.
@see DeclarePerStepPublishEvent()
@see DeclarePerStepDiscreteUpdateEvent()
@see DeclarePerStepUnrestrictedUpdateEvent()
See @ref declare_per-step_events "Declare per-step events" for more
information.
Depending on the type of `event`, at each step it will be passed to
the Publish, DiscreteUpdate, or UnrestrictedUpdate event dispatcher. If
the `event` object contains a handler function, Drake's default
dispatchers will invoke that handler. If not, then no further action is
taken. Thus an `event` with no handler has no effect unless its dispatcher
has been overridden. We strongly recommend that you _do not_ override the
dispatcher and instead _do_ supply a handler.
The given `event` object is deep-copied (cloned), and the copy is stored
internally so you do not need to keep the object around after this call.
@pre `event`'s associated trigger type must be TriggerType::kUnknown or
already set to TriggerType::kPerStep. */
template <typename EventType>
void DeclarePerStepEvent(const EventType& event) {
DRAKE_DEMAND(event.get_trigger_type() == TriggerType::kUnknown ||
event.get_trigger_type() == TriggerType::kPerStep);
event.AddToComposite(TriggerType::kPerStep, &per_step_events_);
}
//@}
// =========================================================================
/** @anchor declare_initialization_events
@name Declare initialization events
These methods are used to declare events that occur when the Drake
Simulator::Initialize() method is invoked.
During Initialize(), initialization-triggered unrestricted update events
are dispatched first for the whole Diagram, then initialization-triggered
discrete update events are dispatched for the whole Diagram. No other
_update_ events occur during initialization. On the other hand, any
_publish_ events, including initialization-triggered, per-step,
and time-triggered publish events that trigger at the initial time, are
dispatched together during initialization.
Template arguments to these methods are inferred from the argument lists
and need not be specified explicitly. */
//@{
/** Declares that a Publish event should occur at initialization and that it
should invoke the given event handler method. The handler should be a
class member function (method) with this signature:
@code
EventStatus MySystem::MyPublish(const Context<T>&) const;
@endcode
where `MySystem` is a class derived from `LeafSystem<T>` and the method
name is arbitrary.
See @ref declare_initialization_events "Declare initialization events" for
more information.
@pre `this` must be dynamic_cast-able to MySystem.
@pre `publish` must not be null.
@see DeclareInitializationDiscreteUpdateEvent()
@see DeclareInitializationUnrestrictedUpdateEvent()
@see DeclareInitializationEvent() */
template <class MySystem>
void DeclareInitializationPublishEvent(
EventStatus(MySystem::*publish)(const Context<T>&) const) {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived System.");
auto this_ptr = dynamic_cast<const MySystem*>(this);
DRAKE_DEMAND(this_ptr != nullptr);
DRAKE_DEMAND(publish != nullptr);
DeclareInitializationEvent<PublishEvent<T>>(PublishEvent<T>(
TriggerType::kInitialization,
[publish](const System<T>& system, const Context<T>& context,
const PublishEvent<T>&) {
const auto& sys = dynamic_cast<const MySystem&>(system);
return (sys.*publish)(context);
}));
}
/** Declares that a DiscreteUpdate event should occur at initialization
and that it should invoke the given event handler method. The handler
should be a class member function (method) with this signature:
@code
EventStatus MySystem::MyUpdate(const Context<T>&,
DiscreteValues<T>*) const;
@endcode
where `MySystem` is a class derived from `LeafSystem<T>` and the method
name is arbitrary.
See @ref declare_initialization_events "Declare initialization events" for
more information.
@pre `this` must be dynamic_cast-able to MySystem.
@pre `update` must not be null.
@see DeclareInitializationPublishEvent()
@see DeclareInitializationUnrestrictedUpdateEvent()
@see DeclareInitializationEvent() */
template <class MySystem>
void DeclareInitializationDiscreteUpdateEvent(
EventStatus(MySystem::*update)
(const Context<T>&, DiscreteValues<T>*) const) {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived System.");
auto this_ptr = dynamic_cast<const MySystem*>(this);
DRAKE_DEMAND(this_ptr != nullptr);
DRAKE_DEMAND(update != nullptr);
DeclareInitializationEvent(DiscreteUpdateEvent<T>(
TriggerType::kInitialization,
[update](const System<T>& system, const Context<T>& context,
const DiscreteUpdateEvent<T>&, DiscreteValues<T>* xd) {
const auto& sys = dynamic_cast<const MySystem&>(system);
return (sys.*update)(context, &*xd);
}));
}
/** Declares that an UnrestrictedUpdate event should occur at initialization
and that it should invoke the given event handler method. The handler
should be a class member function (method) with this signature:
@code
EventStatus MySystem::MyUpdate(const Context<T>&,
State<T>*) const;
@endcode
where `MySystem` is a class derived from `LeafSystem<T>` and the method
name is arbitrary.
See @ref declare_initialization_events "Declare initialization events" for
more information.
@pre `this` must be dynamic_cast-able to MySystem.
@pre `update` must not be null.
@see DeclareInitializationPublishEvent()
@see DeclareInitializationDiscreteUpdateEvent()
@see DeclareInitializationEvent() */
template <class MySystem>
void DeclareInitializationUnrestrictedUpdateEvent(
EventStatus(MySystem::*update)
(const Context<T>&, State<T>*) const) {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived System.");
auto this_ptr = dynamic_cast<const MySystem*>(this);
DRAKE_DEMAND(this_ptr != nullptr);
DRAKE_DEMAND(update != nullptr);
DeclareInitializationEvent(UnrestrictedUpdateEvent<T>(
TriggerType::kInitialization,
[update](const System<T>& system, const Context<T>& context,
const UnrestrictedUpdateEvent<T>&, State<T>* x) {
const auto& sys = dynamic_cast<const MySystem&>(system);
return (sys.*update)(context, &*x);
}));
}
/** (Advanced) Declares that a particular Event object should be dispatched at
initialization. This is the most general form for declaring initialization
events and most users should use one of the other methods in this group
instead.
@see DeclareInitializationPublishEvent()
@see DeclareInitializationDiscreteUpdateEvent()
@see DeclareInitializationUnrestrictedUpdateEvent()
See @ref declare_initialization_events "Declare initialization events" for
more information.
Depending on the type of `event`, on initialization it will be passed to
the Publish, DiscreteUpdate, or UnrestrictedUpdate event dispatcher. If
the `event` object contains a handler function, Drake's default
dispatchers will invoke that handler. If not, then no further action is
taken. Thus an `event` with no handler has no effect unless its dispatcher
has been overridden. We strongly recommend that you _do not_ override the
dispatcher and instead _do_ supply a handler.
The given `event` object is deep-copied (cloned), and the copy is stored
internally so you do not need to keep the object around after this call.
@pre `event`'s associated trigger type must be TriggerType::kUnknown or
already set to TriggerType::kInitialization. */
template <typename EventType>
void DeclareInitializationEvent(const EventType& event) {
DRAKE_DEMAND(event.get_trigger_type() == TriggerType::kUnknown ||
event.get_trigger_type() == TriggerType::kInitialization);
event.AddToComposite(TriggerType::kInitialization, &initialization_events_);
}
//@}
// =========================================================================
/** @anchor declare_forced_events
@name Declare forced events
Forced events are those that are triggered through invocation of
System::ForcedPublish(const Context&),
System::CalcForcedDiscreteVariableUpdate(const Context&, DiscreteValues<T>*),
or System::CalcForcedUnrestrictedUpdate(const Context&, State<T>*),
rather than as a response to some computation-related event (e.g.,
the beginning of a period of time was reached, a trajectory-advancing
step was performed, etc.) One useful application of a forced publish:
a process receives a network message and wants to trigger message
emissions in various systems embedded within a Diagram in response.
Template arguments to these methods are inferred from the argument lists.
and need not be specified explicitly.
@note It's rare that an event needs to be triggered by force. Please
consider per-step and periodic triggered events first.
@warning Simulator handles forced publish events at initialization
and on a per-step basis when its "publish at initialization" and
"publish every time step" options are set (not recommended).
@see Simulator::set_publish_at_initialization()
@see Simulator::set_publish_every_time_step() */
//@{
/** Declares a function that is called whenever a user directly calls
ForcedPublish(const Context&). Multiple calls to
DeclareForcedPublishEvent() will cause multiple handlers to be called
upon a call to ForcedPublish(); these handlers which will be called with the
same const Context in arbitrary order. The handler should be a class
member function (method) with this signature:
@code
EventStatus MySystem::MyPublish(const Context<T>&) const;
@endcode
where `MySystem` is a class derived from `LeafSystem<T>` and the method
name is arbitrary.
See @ref declare_forced_events "Declare forced events" for more
information.
@pre `this` must be dynamic_cast-able to MySystem.
@pre `publish` must not be null. */
template <class MySystem>
void DeclareForcedPublishEvent(
EventStatus (MySystem::*publish)(const Context<T>&) const) {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived System.");
auto this_ptr = dynamic_cast<const MySystem*>(this);
DRAKE_DEMAND(this_ptr != nullptr);
DRAKE_DEMAND(publish != nullptr);
// Instantiate the event.
PublishEvent<T> forced(
TriggerType::kForced,
[publish](const System<T>& system, const Context<T>& context,
const PublishEvent<T>&) {
const auto& sys = dynamic_cast<const MySystem&>(system);
return (sys.*publish)(context);
});
// Add the event to the collection of forced publish events.
this->get_mutable_forced_publish_events().AddEvent(std::move(forced));
}
/** Declares a function that is called whenever a user directly calls
CalcForcedDiscreteVariableUpdate(const Context&, DiscreteValues<T>*). Multiple
calls to DeclareForcedDiscreteUpdateEvent() will cause multiple handlers
to be called upon a call to CalcForcedDiscreteVariableUpdate(); these handlers
will be called with the same const Context in arbitrary order. The
handler should be a class member function (method) with this signature:
@code
EventStatus MySystem::MyDiscreteVariableUpdates(const Context<T>&,
DiscreteValues<T>*);
@endcode
where `MySystem` is a class derived from `LeafSystem<T>` and the method
name is arbitrary.
See @ref declare_forced_events "Declare forced events" for more
information.
@pre `this` must be dynamic_cast-able to MySystem.
@pre `update` must not be null. */
template <class MySystem>
void DeclareForcedDiscreteUpdateEvent(EventStatus
(MySystem::*update)(const Context<T>&, DiscreteValues<T>*) const) {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived System.");
auto this_ptr = dynamic_cast<const MySystem*>(this);
DRAKE_DEMAND(this_ptr != nullptr);
DRAKE_DEMAND(update != nullptr);
// Instantiate the event.
DiscreteUpdateEvent<T> forced(
TriggerType::kForced,
[update](const System<T>& system, const Context<T>& context,
const DiscreteUpdateEvent<T>&,
DiscreteValues<T>* discrete_state) {
const auto& sys = dynamic_cast<const MySystem&>(system);
return (sys.*update)(context, discrete_state);
});
// Add the event to the collection of forced discrete update events.
this->get_mutable_forced_discrete_update_events().AddEvent(
std::move(forced));
}
/** Declares a function that is called whenever a user directly calls
CalcForcedUnrestrictedUpdate(const Context&, State<T>*). Multiple calls to
DeclareForcedUnrestrictedUpdateEvent() will cause multiple handlers to be
called upon a call to CalcForcedUnrestrictedUpdate(); these handlers which
will be called with the same const Context in arbitrary order.The handler
should be a class member function (method) with this signature:
@code
EventStatus MySystem::MyUnrestrictedUpdates(const Context<T>&,
State<T>*);
@endcode
where `MySystem` is a class derived from `LeafSystem<T>` and the method
name is arbitrary.
See @ref declare_forced_events "Declare forced events" for more
information.
@pre `this` must be dynamic_cast-able to MySystem.
@pre `update` must not be null. */
template <class MySystem>
void DeclareForcedUnrestrictedUpdateEvent(
EventStatus (MySystem::*update)(const Context<T>&, State<T>*) const) {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived System.");
auto this_ptr = dynamic_cast<const MySystem*>(this);
DRAKE_DEMAND(this_ptr != nullptr);
DRAKE_DEMAND(update != nullptr);
// Instantiate the event.
UnrestrictedUpdateEvent<T> forced(
TriggerType::kForced,
[update](const System<T>& system, const Context<T>& context,
const UnrestrictedUpdateEvent<T>&, State<T>* state) {
const auto& sys = dynamic_cast<const MySystem&>(system);
return (sys.*update)(context, state);
});
// Add the event to the collection of forced unrestricted update events.
this->get_mutable_forced_unrestricted_update_events().AddEvent(
std::move(forced));
}
//@}
/** @name Declare continuous state variables
Continuous state consists of up to three kinds of variables: generalized
coordinates q, generalized velocities v, and miscellaneous continuous
variables z. Methods in this section provide different ways to declare
these, and offer the ability to provide a `model_vector` to specify the
initial values for these variables. Model values are useful when you want
the values of these variables in a default Context to be something other
than zero.
If multiple calls are made to DeclareContinuousState() methods, only the
last call has any effect. */
//@{
/** Declares that this System should reserve continuous state with
@p num_state_variables state variables, which have no second-order
structure.
@return index of the declared state (currently always zero). */
ContinuousStateIndex DeclareContinuousState(int num_state_variables);
/** Declares that this System should reserve continuous state with @p num_q
generalized positions, @p num_v generalized velocities, and @p num_z
miscellaneous state variables.
@return index of the declared state (currently always zero). */
ContinuousStateIndex DeclareContinuousState(int num_q, int num_v, int num_z);
/** Declares that this System should reserve continuous state with
@p model_vector.size() miscellaneous state variables, stored in a
vector cloned from @p model_vector.
@return index of the declared state (currently always zero). */
ContinuousStateIndex DeclareContinuousState(
const BasicVector<T>& model_vector);
/** Declares that this System should reserve continuous state with @p num_q
generalized positions, @p num_v generalized velocities, and @p num_z
miscellaneous state variables, stored in a vector cloned from
@p model_vector. Aborts if @p model_vector has the wrong size. If the
@p model_vector declares any VectorBase::GetElementBounds()
constraints, they will be re-declared as inequality constraints on this
system (see DeclareInequalityConstraint()).
@return index of the declared state (currently always zero). */
ContinuousStateIndex DeclareContinuousState(
const BasicVector<T>& model_vector, int num_q, int num_v, int num_z);
//@}
/** @name Declare discrete state variables
Discrete state consists of any number of discrete state "groups", each
of which is a vector of discrete state variables. Methods in this section
provide different ways to declare these, and offer the ability to provide
a `model_vector` to specify the initial values for each group of
variables. Model values are useful when you want the values of
these variables in a default Context to be something other than zero.
Each call to a DeclareDiscreteState() method produces another
discrete state group, and the group index is returned. */
//@{
/** Declares a discrete state group with @p model_vector.size() state
variables, stored in a vector cloned from @p model_vector (preserving the
concrete type and value). */
DiscreteStateIndex DeclareDiscreteState(const BasicVector<T>& model_vector);
/** Declares a discrete state group with @p vector.size() state variables,
stored in a BasicVector initialized with the contents of @p vector. */
DiscreteStateIndex DeclareDiscreteState(
const Eigen::Ref<const VectorX<T>>& vector);
/** Declares a discrete state group with @p num_state_variables state
variables, stored in a BasicVector initialized to be all-zero. If you want
non-zero initial values, use an alternate DeclareDiscreteState() signature
that accepts a `model_vector` parameter.
@pre `num_state_variables` must be non-negative. */
DiscreteStateIndex DeclareDiscreteState(int num_state_variables);
//@}
/** @name Declare abstract state variables
Abstract state consists of any number of arbitrarily-typed variables, each
represented by an AbstractValue. Each call to the DeclareAbstractState()
method produces another abstract state variable, and the abstract state
variable index is returned. */
//@{
/** Declares an abstract state variable and provides a model value
for it. A Context obtained with CreateDefaultContext() will contain this
abstract state variable initially set to a clone of the `model_value`
given here. The actual concrete type is always preserved.
@param model_value The abstract state model value to be cloned as needed.
@returns index of the declared abstract state variable. */
AbstractStateIndex DeclareAbstractState(
const AbstractValue& model_value);
//@}
/** @name (Advanced) Declare size of implicit time derivatives residual
for use with System::CalcImplicitTimeDerivativeResidual(). Most commonly
the default value, same as num_continuous_states(), will be the correct
size for the residual. */
//@{
/** (Advanced) Overrides the default size for the implicit time
derivatives residual. If no value is set, the default size is
n=num_continuous_states().
@param[in] n The size of the residual vector output argument of
System::CalcImplicitTimeDerivativesResidual(). If n <= 0
restore to the default, num_continuous_states().
@see implicit_time_derivatives_residual_size()
@see System::CalcImplicitTimeDerivativesResidual() */
void DeclareImplicitTimeDerivativesResidualSize(int n) {
this->set_implicit_time_derivatives_residual_size(n);
}
//@}
// =========================================================================
/** @name Declare input ports
Methods in this section are used by derived classes to declare their
input ports, which may be vector valued or abstract valued.
You should normally provide a meaningful name for any input port you
create. Names must be unique for this system (passing in a duplicate
name will throw std::exception). However, if you specify
kUseDefaultName as the name, then a default name of e.g. "u2", where 2
is the input port number will be provided. An empty name is not
permitted. */
//@{
/** Declares a vector-valued input port using the given @p model_vector.
This is the best way to declare LeafSystem input ports that require
subclasses of BasicVector. The port's size and type will be the same as
model_vector. If the port is intended to model a random noise or
disturbance input, @p random_type can (optionally) be used to label it
as such. If the @p model_vector declares any
VectorBase::GetElementBounds() constraints, they will be
re-declared as inequality constraints on this system (see
DeclareInequalityConstraint()).
@see System::DeclareInputPort() for more information.
@pydrake_mkdoc_identifier{3args_model_vector} */
InputPort<T>& DeclareVectorInputPort(
std::variant<std::string, UseDefaultName> name,
const BasicVector<T>& model_vector,
std::optional<RandomDistribution> random_type = std::nullopt);
/** Declares a vector-valued input port with type BasicVector and size @p
size. If the port is intended to model a random noise or disturbance input,
@p random_type can (optionally) be used to label it as such.
@see System::DeclareInputPort() for more information.
@pydrake_mkdoc_identifier{3args_size} */
InputPort<T>& DeclareVectorInputPort(
std::variant<std::string, UseDefaultName> name,
int size,
std::optional<RandomDistribution> random_type = std::nullopt);
/** Declares an abstract-valued input port using the given @p model_value.
This is the best way to declare LeafSystem abstract input ports.
Any port connected to this input, and any call to FixValue for this
input, must provide for values whose type matches this @p model_value.
@see System::DeclareInputPort() for more information. */
InputPort<T>& DeclareAbstractInputPort(
std::variant<std::string, UseDefaultName> name,
const AbstractValue& model_value);
/** Flags an already-declared input port as deprecated. The first attempt to
use the port in a program will log a warning message. This function may be
called at most once for any given port. */
void DeprecateInputPort(const InputPort<T>& port, std::string message);
//@}
// =========================================================================
/** @name Declare output ports
@anchor DeclareLeafOutputPort_documentation
Methods in this section are used by derived classes to declare their
output ports, which may be vector valued or abstract valued. Every output
port must have an _allocator_ function and
a _calculator_ function. The allocator returns an object suitable for
holding a value of the output port. The calculator uses the contents of
a given Context to produce the output port's value, which is placed in
an object of the type returned by the allocator.
Although the allocator and calculator functions ultimately satisfy generic
function signatures defined in LeafOutputPort, we provide a variety
of `DeclareVectorOutputPort()` and `DeclareAbstractOutputPort()`
signatures here for convenient specification, with mapping to the generic
form handled invisibly. In particular, allocators are most easily defined
by providing a model value that can be used to construct an
allocator that copies the model when a new value object is needed.
Alternatively a method can be provided that constructs a value object when
invoked (those methods are conventionally, but not necessarily, named
`MakeSomething()` where `Something` is replaced by the output port value
type).
Because output port values are ultimately stored in AbstractValue objects,
the underlying types must be suitable. For vector ports, that means the
type must be BasicVector or a class derived from BasicVector. For abstract
ports, the type must be copy constructible or cloneable. For
methods below that are not given an explicit model value or construction
("make") method, the underlying type must be default constructible.
@see drake::Value for more about abstract values.
A list of prerequisites may be provided for the calculator function to
avoid unnecessary recomputation. If no prerequisites are provided, the
default is to assume the output port value is dependent on all possible
sources. See @ref DeclareCacheEntry_documentation "DeclareCacheEntry"
for more information about prerequisites.
Output ports must have a name that is unique within the owning subsystem.
Users can provide meaningful names or specify the name as
`kUseDefaultName` in which case a name like "y3" is
automatically provided, where the number is the output port index. An
empty name is not permitted.
@anchor DeclareLeafOutputPort_feedthrough
<em><u>Direct feedthrough</u></em>
By default, %LeafSystem assumes there is direct feedthrough of values
from every input to every output. This is a conservative assumption that
ensures we detect and can prevent the formation of algebraic loops
(implicit computations) in system Diagrams. Systems which do not have
direct feedthrough may override that assumption in either of two ways:
(1) When declaring an output port (e.g., DeclareVectorOutputPort()),
provide a non-default value for the `prerequisites_of_calc` argument.
In that case the dependency path from each input port to that output port is
probed via the fast cache invalidation mechanism to see if it has a direct or
indirect dependence that input port. For example:
@code
PendulumPlant<T>::PendulumPlant() {
// No feedthrough because the output port depends only on state,
// and state has no dependencies.
this->DeclareVectorOutputPort(
"state", &PendulumPlant::CopyStateOut,
{this->all_state_ticket()});
// Has feedthrough from input port 0 but not from any others.
this->DeclareVectorOutputPort(
"tau", &PendulumPlant::CopyTauOut,
{this->input_port_ticket(InputPortIndex(0))});
// Doesn't specify prerequisites. We'll assume feedthrough from all
// inputs unless we can apply symbolic analysis (see below).
this->DeclareVectorOutputPort(
"result", &PendulumPlant::CalcResult);
}
@endcode
See @ref DependencyTicket_documentation "Dependency tickets" for more
information about tickets, including a list of possible ticket options.
(2) Add support for the symbolic::Expression scalar type, per
@ref system_scalar_conversion_how_to_write_a_system
"How to write a System that supports scalar conversion".
This allows the %LeafSystem to infer the sparsity from the symbolic
equations for any of the output ports that don't specify an explicit
list of prerequisites.
Option 2 is a convenient default for simple systems that already support
symbolic::Expression, but option 1 should be preferred as the most direct
mechanism to control feedthrough reporting.
Normally the direct-feedthrough relations are checked automatically to
detect algebraic loops. If you want to examine the computed feedthrough
status for all ports or a particular port, see
System::GetDirectFeedthroughs(), System::HasDirectFeedthrough(), and
related methods. */
//@{
/** Declares a vector-valued output port by specifying (1) a model vector of
type BasicVectorSubtype derived from BasicVector and initialized to the
correct size and desired initial value, and (2) a calculator function that
is a class member function (method) with signature:
@code
void MySystem::CalcOutputVector(const Context<T>&,
BasicVectorSubtype*) const;
@endcode
where `MySystem` is a class derived from `LeafSystem<T>`. Template
arguments will be deduced and do not need to be specified.
@exclude_from_pydrake_mkdoc{Not bound in pydrake.} */
template <class MySystem, typename BasicVectorSubtype>
LeafOutputPort<T>& DeclareVectorOutputPort(
std::variant<std::string, UseDefaultName> name,
const BasicVectorSubtype& model_vector,
void (MySystem::*calc)(const Context<T>&, BasicVectorSubtype*) const,
std::set<DependencyTicket> prerequisites_of_calc = {
all_sources_ticket()}) {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived System.");
static_assert(std::is_base_of_v<BasicVector<T>, BasicVectorSubtype>,
"Expected vector type derived from BasicVector.");
// We need to obtain a `this` pointer of the right derived type to capture
// in the calculator functor, so that it will be able to invoke the given
// mmember function `calc()`.
auto this_ptr = dynamic_cast<const MySystem*>(this);
DRAKE_DEMAND(this_ptr != nullptr);
// Currently all vector ports in Drake require a fixed size that is known
// at the time the port is declared.
auto& port = CreateVectorLeafOutputPort(
NextOutputPortName(std::move(name)), model_vector.size(),
// Allocator function just clones the given model vector.
MakeAllocateCallback<BasicVector<T>>(model_vector),
// Calculator function downcasts to specific vector type and invokes
// the given member function.
[this_ptr, calc](const Context<T>& context, BasicVector<T>* result) {
auto typed_result = dynamic_cast<BasicVectorSubtype*>(result);
DRAKE_DEMAND(typed_result != nullptr);
(this_ptr->*calc)(context, typed_result);
},
std::move(prerequisites_of_calc));
// Caution: "name" is empty now.
MaybeDeclareVectorBaseInequalityConstraint(
"output " + std::to_string(int{port.get_index()}), model_vector,
[&port](const Context<T>& context) -> const VectorBase<T>& {
return port.template Eval<BasicVector<T>>(context);
});
return port;
}
/** Declares a vector-valued output port with type BasicVector and size @p
size, using the drake::dummy_value<T>, which is NaN when T = double. @p calc
is a calculator function that is a class member function (method) with
signature:
@code
void MySystem::CalcOutputVector(const Context<T>&,
BasicVector<T>*) const;
@endcode
where `MySystem` is a class derived from `LeafSystem<T>`. Template
arguments will be deduced and do not need to be specified.
@exclude_from_pydrake_mkdoc{Not bound in pydrake.} */
template <class MySystem>
LeafOutputPort<T>& DeclareVectorOutputPort(
std::variant<std::string, UseDefaultName> name, int size,
void (MySystem::*calc)(const Context<T>&, BasicVector<T>*) const,
std::set<DependencyTicket> prerequisites_of_calc = {
all_sources_ticket()}) {
return DeclareVectorOutputPort(std::move(name), BasicVector<T>(size),
std::move(calc),
std::move(prerequisites_of_calc));
}
/** Declares a vector-valued output port by specifying _only_ a calculator
function that is a class member function (method) with signature:
@code
void MySystem::CalcOutputVector(const Context<T>&,
BasicVectorSubtype*) const;
@endcode
where `MySystem` is a class derived from `LeafSystem<T>` and
`BasicVectorSubtype` is derived from `BasicVector<T>` and has a suitable
default constructor that allocates a vector of the expected size. This
will use `BasicVectorSubtype{}` (that is, the default constructor) to
produce a model vector for the output port's value.
Template arguments will be deduced and do not need to be specified.
@note The default constructor will be called once immediately, and
subsequent allocations will just copy the model value without invoking the
constructor again. If you want the constructor invoked again at each
allocation (not common), use one of the other signatures to explicitly
provide a method for the allocator to call; that method can then invoke
the `BasicVectorSubtype` default constructor.
@exclude_from_pydrake_mkdoc{Not bound in pydrake.} */
template <class MySystem, typename BasicVectorSubtype>
LeafOutputPort<T>& DeclareVectorOutputPort(
std::variant<std::string, UseDefaultName> name,
void (MySystem::*calc)(const Context<T>&, BasicVectorSubtype*) const,
std::set<DependencyTicket> prerequisites_of_calc = {
all_sources_ticket()}) {
static_assert(
std::is_default_constructible_v<BasicVectorSubtype>,
"LeafSystem::DeclareVectorOutputPort(calc): the one-argument form of "
"this method requires that the output type has a default constructor");
// Invokes the previous method.
return DeclareVectorOutputPort(NextOutputPortName(std::move(name)),
BasicVectorSubtype{}, calc,
std::move(prerequisites_of_calc));
}
/** (Advanced) Declares a vector-valued output port using the given
`model_vector` and a function for calculating the port's value at runtime.
The port's size will be model_vector.size(), and the default allocator for
the port will be model_vector.Clone(). Note that this takes the calculator
function in its most generic form; if you have a member function available
use one of the other signatures.
@see LeafOutputPort::CalcVectorCallback
@pydrake_mkdoc_identifier{4args_model_vector} */
LeafOutputPort<T>& DeclareVectorOutputPort(
std::variant<std::string, UseDefaultName> name,
const BasicVector<T>& model_vector,
typename LeafOutputPort<T>::CalcVectorCallback vector_calc_function,
std::set<DependencyTicket> prerequisites_of_calc = {
all_sources_ticket()});
/** (Advanced) Declares a vector-valued output port with type BasicVector<T>
and size @p size, using the drake::dummy_value<T>, which is NaN when T =
double. @p vector_calc_function is a function for calculating the port's
value at runtime. Note that this takes the calculator function in its most
generic form; if you have a member function available use one of the other
signatures.
@see LeafOutputPort::CalcVectorCallback
@pydrake_mkdoc_identifier{4args_size} */
LeafOutputPort<T>& DeclareVectorOutputPort(
std::variant<std::string, UseDefaultName> name, int size,
typename LeafOutputPort<T>::CalcVectorCallback vector_calc_function,
std::set<DependencyTicket> prerequisites_of_calc = {
all_sources_ticket()}) {
return DeclareVectorOutputPort(std::move(name), BasicVector<T>(size),
std::move(vector_calc_function),
std::move(prerequisites_of_calc));
}
/** Declares an abstract-valued output port by specifying a model value of
concrete type `OutputType` and a calculator function that is a class
member function (method) with signature:
@code
void MySystem::CalcOutputValue(const Context<T>&, OutputType*) const;
@endcode
where `MySystem` must be a class derived from `LeafSystem<T>`.
`OutputType` must be such that `Value<OutputType>` is permitted.
Template arguments will be deduced and do not need to be specified.
@see drake::Value */
template <class MySystem, typename OutputType>
LeafOutputPort<T>& DeclareAbstractOutputPort(
std::variant<std::string, UseDefaultName> name,
const OutputType& model_value,
void (MySystem::*calc)(const Context<T>&, OutputType*) const,
std::set<DependencyTicket> prerequisites_of_calc = {
all_sources_ticket()}) {
auto& port = CreateAbstractLeafOutputPort(
NextOutputPortName(std::move(name)),
ValueProducer(this, model_value, calc),
std::move(prerequisites_of_calc));
return port;
}
/** Declares an abstract-valued output port by specifying only a calculator
function that is a class member function (method) with signature:
@code
void MySystem::CalcOutputValue(const Context<T>&, OutputType*) const;
@endcode
where `MySystem` is a class derived from `LeafSystem<T>`. `OutputType`
is a concrete type such that `Value<OutputType>` is permitted, and
must be default constructible, so that we can create a model value using
`Value<OutputType>{}` (value initialized so numerical types will be
zeroed in the model).
Template arguments will be deduced and do not need to be specified.
@note The default constructor will be called once immediately, and
subsequent allocations will just copy the model value without invoking the
constructor again. If you want the constructor invoked again at each
allocation (not common), use one of the other signatures to explicitly
provide a method for the allocator to call; that method can then invoke
the `OutputType` default constructor.
@see drake::Value */
template <class MySystem, typename OutputType>
LeafOutputPort<T>& DeclareAbstractOutputPort(
std::variant<std::string, UseDefaultName> name,
void (MySystem::*calc)(const Context<T>&, OutputType*) const,
std::set<DependencyTicket> prerequisites_of_calc = {
all_sources_ticket()}) {
static_assert(
std::is_default_constructible_v<OutputType>,
"LeafSystem::DeclareAbstractOutputPort(calc): the one-argument form of "
"this method requires that the output type has a default constructor");
// Note that value initialization {} is required here.
return DeclareAbstractOutputPort(NextOutputPortName(std::move(name)),
OutputType{}, calc,
std::move(prerequisites_of_calc));
}
/** (Advanced) Declares an abstract-valued output port using the given
allocator and calculator functions provided in their most generic forms.
If you have a member function available use one of the other signatures.
@see LeafOutputPort::AllocCallback, LeafOutputPort::CalcCallback */
LeafOutputPort<T>& DeclareAbstractOutputPort(
std::variant<std::string, UseDefaultName> name,
typename LeafOutputPort<T>::AllocCallback alloc_function,
typename LeafOutputPort<T>::CalcCallback calc_function,
std::set<DependencyTicket> prerequisites_of_calc = {
all_sources_ticket()});
/** Declares a vector-valued output port whose value is the continuous state
of this system.
@param state_index must be ContinuousStateIndex(0) for now, since LeafSystem
only supports a single continuous state group at the moment.
@pydrake_mkdoc_identifier{continuous} */
LeafOutputPort<T>& DeclareStateOutputPort(
std::variant<std::string, UseDefaultName> name,
ContinuousStateIndex state_index);
/** Declares a vector-valued output port whose value is the given discrete
state group of this system.
@pydrake_mkdoc_identifier{discrete} */
LeafOutputPort<T>& DeclareStateOutputPort(
std::variant<std::string, UseDefaultName> name,
DiscreteStateIndex state_index);
/** Declares an abstract-valued output port whose value is the given abstract
state of this system.
@pydrake_mkdoc_identifier{abstract} */
LeafOutputPort<T>& DeclareStateOutputPort(
std::variant<std::string, UseDefaultName> name,
AbstractStateIndex state_index);
/** Flags an already-declared output port as deprecated. The first attempt to
use the port in a program will log a warning message. This function may be
called at most once for any given port. */
void DeprecateOutputPort(const OutputPort<T>& port, std::string message);
//@}
// =========================================================================
/** @name Make witness functions
Methods in this section are used by derived classes to make any
witness functions useful for ensuring that integration ends a step upon
entering particular times or states.
In contrast to other declaration methods (e.g., DeclareVectorOutputPort(),
for which the System class creates and stores the objects and returns
references to them, the witness function declaration functions return
heap-allocated objects that the subclass of leaf system owns. This
facilitates returning pointers to these objects in
System::DoGetWitnessFunctions(). */
//@{
/** Constructs the witness function with the given description (used primarily
for debugging and logging), direction type, and calculator function; and
with no event object.
@note Constructing a witness function with no corresponding event forces
Simulator's integration of an ODE to end a step at the witness
isolation time. For example, isolating a function's minimum or
maximum values can be realized with a witness that triggers on a
sign change of the function's time derivative, ensuring that the
actual extreme value is present in the discretized trajectory.
@note In order for the witness function to be used, you MUST
overload System::DoGetWitnessFunctions().
@exclude_from_pydrake_mkdoc{Only the std::function versions are bound.} */
template <class MySystem>
std::unique_ptr<WitnessFunction<T>> MakeWitnessFunction(
const std::string& description,
const WitnessFunctionDirection& direction_type,
T (MySystem::*calc)(const Context<T>&) const) const {
return std::make_unique<WitnessFunction<T>>(
this, this, description, direction_type, calc);
}
/** Constructs the witness function with the given description (used primarily
for debugging and logging), direction type, and calculator function; and
with no event object.
@note In order for the witness function to be used, you MUST
overload System::DoGetWitnessFunctions(). */
std::unique_ptr<WitnessFunction<T>> MakeWitnessFunction(
const std::string& description,
const WitnessFunctionDirection& direction_type,
std::function<T(const Context<T>&)> calc) const;
/** Constructs the witness function with the given description (used primarily
for debugging and logging), direction type, calculator function, and
publish event callback function for when this triggers.
@note In order for the witness function to be used, you MUST
overload System::DoGetWitnessFunctions().
@exclude_from_pydrake_mkdoc{Only the std::function versions are bound.} */
template <class MySystem>
std::unique_ptr<WitnessFunction<T>> MakeWitnessFunction(
const std::string& description,
const WitnessFunctionDirection& direction_type,
T (MySystem::*calc)(const Context<T>&) const,
void (MySystem::*publish_callback)(
const Context<T>&, const PublishEvent<T>&) const) const {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived system.");
PublishEvent<T> event(
TriggerType::kWitness,
[publish_callback](const System<T>& system, const Context<T>& context,
const PublishEvent<T>& callback_event) {
const auto& sys = dynamic_cast<const MySystem&>(system);
(sys.*publish_callback)(context, callback_event);
return EventStatus::Succeeded();
});
return std::make_unique<WitnessFunction<T>>(
this, this, description, direction_type, calc, event.Clone());
}
/** Constructs the witness function with the given description (used primarily
for debugging and logging), direction type, calculator function, and
discrete update event callback function for when this triggers.
@note In order for the witness function to be used, you MUST
overload System::DoGetWitnessFunctions().
@exclude_from_pydrake_mkdoc{Only the std::function versions are bound.} */
template <class MySystem>
std::unique_ptr<WitnessFunction<T>> MakeWitnessFunction(
const std::string& description,
const WitnessFunctionDirection& direction_type,
T (MySystem::*calc)(const Context<T>&) const,
void (MySystem::*du_callback)(const Context<T>&,
const DiscreteUpdateEvent<T>&, DiscreteValues<T>*) const) const {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived system.");
DiscreteUpdateEvent<T> event(
TriggerType::kWitness,
[du_callback](const System<T>& system, const Context<T>& context,
const DiscreteUpdateEvent<T>& callback_event,
DiscreteValues<T>* values) {
const auto& sys = dynamic_cast<const MySystem&>(system);
(sys.*du_callback)(context, callback_event, values);
return EventStatus::Succeeded();
});
return std::make_unique<WitnessFunction<T>>(
this, this, description, direction_type, calc, event.Clone());
}
/** Constructs the witness function with the given description (used primarily
for debugging and logging), direction type, calculator function, and
unrestricted update event callback function for when this triggers.
@note In order for the witness function to be used, you MUST
overload System::DoGetWitnessFunctions().
@exclude_from_pydrake_mkdoc{Only the std::function versions are bound.} */
template <class MySystem>
std::unique_ptr<WitnessFunction<T>> MakeWitnessFunction(
const std::string& description,
const WitnessFunctionDirection& direction_type,
T (MySystem::*calc)(const Context<T>&) const,
void (MySystem::*uu_callback)(const Context<T>&,
const UnrestrictedUpdateEvent<T>&, State<T>*) const) const {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived system.");
UnrestrictedUpdateEvent<T> event(
TriggerType::kWitness,
[uu_callback](const System<T>& system, const Context<T>& context,
const UnrestrictedUpdateEvent<T>& callback_event,
State<T>* state) {
const auto& sys = dynamic_cast<const MySystem&>(system);
(sys.*uu_callback)(context, callback_event, state);
return EventStatus::Succeeded();
});
return std::make_unique<WitnessFunction<T>>(
this, this, description, direction_type, calc, event.Clone());
}
/** Constructs the witness function with the given description (used primarily
for debugging and logging), direction type, and calculator
function, and with an object corresponding to the event that is to be
dispatched when this witness function triggers. Example types of event
objects are publish, discrete variable update, unrestricted update events.
A clone of the event will be owned by the newly constructed
WitnessFunction.
@note In order for the witness function to be used, you MUST
overload System::DoGetWitnessFunctions().
@exclude_from_pydrake_mkdoc{Only the std::function versions are bound.} */
template <class MySystem>
std::unique_ptr<WitnessFunction<T>> MakeWitnessFunction(
const std::string& description,
const WitnessFunctionDirection& direction_type,
T (MySystem::*calc)(const Context<T>&) const,
const Event<T>& e) const {
static_assert(std::is_base_of_v<LeafSystem<T>, MySystem>,
"Expected to be invoked from a LeafSystem-derived system.");
return std::make_unique<WitnessFunction<T>>(
this, this, description, direction_type, calc, e.Clone());
}
/** Constructs the witness function with the given description (used primarily
for debugging and logging), direction type, and calculator
function, and with an object corresponding to the event that is to be
dispatched when this witness function triggers. Example types of event
objects are publish, discrete variable update, unrestricted update events.
A clone of the event will be owned by the newly constructed
WitnessFunction.
@note In order for the witness function to be used, you MUST
overload System::DoGetWitnessFunctions(). */
std::unique_ptr<WitnessFunction<T>> MakeWitnessFunction(
const std::string& description,
const WitnessFunctionDirection& direction_type,
std::function<T(const Context<T>&)> calc,
const Event<T>& e) const;
//@}
/** Declares a system constraint of the form
f(context) = 0
by specifying a member function to use to calculate the (VectorX)
constraint value with a signature:
@code
void MySystem::CalcConstraint(const Context<T>&, VectorX<T>*) const;
@endcode
@param count is the dimension of the VectorX output.
@param description should be a human-readable phrase.
@returns The index of the constraint.
Template arguments will be deduced and do not need to be specified.
@see SystemConstraint<T> for more information about the meaning of
these constraints. */
template <class MySystem>
SystemConstraintIndex DeclareEqualityConstraint(
void (MySystem::*calc)(const Context<T>&, VectorX<T>*) const,
int count, std::string description) {
auto this_ptr = dynamic_cast<const MySystem*>(this);
DRAKE_DEMAND(this_ptr != nullptr);
return DeclareEqualityConstraint(
[this_ptr, calc](const Context<T>& context, VectorX<T>* value) {
DRAKE_DEMAND(value != nullptr);
(this_ptr->*calc)(context, value);
},
count, std::move(description));
}
/** Declares a system constraint of the form
f(context) = 0
by specifying a std::function to use to calculate the (Vector) constraint
value with a signature:
@code
void CalcConstraint(const Context<T>&, VectorX<T>*);
@endcode
@param count is the dimension of the VectorX output.
@param description should be a human-readable phrase.
@returns The index of the constraint.
@see SystemConstraint<T> for more information about the meaning of
these constraints. */
SystemConstraintIndex DeclareEqualityConstraint(
ContextConstraintCalc<T> calc, int count,
std::string description);
/** Declares a system constraint of the form
bounds.lower() <= calc(context) <= bounds.upper()
by specifying a member function to use to calculate the (VectorX)
constraint value with a signature:
@code
void MySystem::CalcConstraint(const Context<T>&, VectorX<T>*) const;
@endcode
@param description should be a human-readable phrase.
@returns The index of the constraint.
Template arguments will be deduced and do not need to be specified.
@see SystemConstraint<T> for more information about the meaning of
these constraints. */
template <class MySystem>
SystemConstraintIndex DeclareInequalityConstraint(
void (MySystem::*calc)(const Context<T>&, VectorX<T>*) const,
SystemConstraintBounds bounds,
std::string description) {
auto this_ptr = dynamic_cast<const MySystem*>(this);
DRAKE_DEMAND(this_ptr != nullptr);
return DeclareInequalityConstraint(
[this_ptr, calc](const Context<T>& context, VectorX<T>* value) {
DRAKE_DEMAND(value != nullptr);
(this_ptr->*calc)(context, value);
},
std::move(bounds), std::move(description));
}
/** Declares a system constraint of the form
bounds.lower() <= calc(context) <= bounds.upper()
by specifying a std::function to use to calculate the (Vector) constraint
value with a signature:
@code
void CalcConstraint(const Context<T>&, VectorX<T>*);
@endcode
@param description should be a human-readable phrase.
@returns The index of the constraint.
@see SystemConstraint<T> for more information about the meaning of
these constraints. */
SystemConstraintIndex DeclareInequalityConstraint(
ContextConstraintCalc<T> calc,
SystemConstraintBounds bounds,
std::string description);
private:
using SystemBase::NextInputPortName;
using SystemBase::NextOutputPortName;
// Either clones the model_value, or else for vector ports allocates a
// BasicVector, or else for abstract ports throws an exception.
std::unique_ptr<AbstractValue> DoAllocateInput(
const InputPort<T>& input_port) const final;
std::unique_ptr<CompositeEventCollection<T>>
DoAllocateCompositeEventCollection() const final;
std::map<PeriodicEventData, std::vector<const Event<T>*>,
PeriodicEventDataComparator>
DoMapPeriodicEventsByTiming(const Context<T>& context) const final;
void DoFindUniquePeriodicDiscreteUpdatesOrThrow(
const char* api_name, const Context<T>& context,
std::optional<PeriodicEventData>* timing,
EventCollection<DiscreteUpdateEvent<T>>* events) const final;
// Assumes @param events is an instance of LeafEventCollection, throws
// std::bad_cast otherwise.
// Assumes @param events is not empty. Aborts otherwise.
[[nodiscard]] EventStatus DispatchPublishHandler(
const Context<T>& context,
const EventCollection<PublishEvent<T>>& events) const final;
// Assumes @p events is an instance of LeafEventCollection, throws
// std::bad_cast otherwise.
// Assumes @p events is not empty. Aborts otherwise.
[[nodiscard]] EventStatus DispatchDiscreteVariableUpdateHandler(
const Context<T>& context,
const EventCollection<DiscreteUpdateEvent<T>>& events,
DiscreteValues<T>* discrete_state) const final;
// To get here:
// - The EventCollection must be a LeafEventCollection, and
// - There must be at least one Event belonging to this leaf subsystem.
void DoApplyDiscreteVariableUpdate(
const EventCollection<DiscreteUpdateEvent<T>>& events,
DiscreteValues<T>* discrete_state, Context<T>* context) const final;
// Assumes @p events is an instance of LeafEventCollection, throws
// std::bad_cast otherwise.
// Assumes @p events is not empty. Aborts otherwise.
[[nodiscard]] EventStatus DispatchUnrestrictedUpdateHandler(
const Context<T>& context,
const EventCollection<UnrestrictedUpdateEvent<T>>& events,
State<T>* state) const final;
// To get here:
// - The EventCollection must be a LeafEventCollection, and
// - There must be at least one Event belonging to this leaf subsystem.
void DoApplyUnrestrictedUpdate(
const EventCollection<UnrestrictedUpdateEvent<T>>& events,
State<T>* state, Context<T>* context) const final;
void DoGetPeriodicEvents(
const Context<T>& context,
CompositeEventCollection<T>* events) const final;
void DoGetPerStepEvents(
const Context<T>& context,
CompositeEventCollection<T>* events) const final;
void DoGetInitializationEvents(
const Context<T>& context,
CompositeEventCollection<T>* events) const final;
// Creates a new cached, vector-valued LeafOutputPort in this LeafSystem and
// returns a reference to it.
LeafOutputPort<T>& CreateVectorLeafOutputPort(
std::string name,
int fixed_size,
typename LeafOutputPort<T>::AllocCallback vector_allocator,
typename LeafOutputPort<T>::CalcVectorCallback vector_calculator,
std::set<DependencyTicket> calc_prerequisites);
// Creates a new cached, abstract-valued LeafOutputPort in this LeafSystem and
// returns a reference to it.
LeafOutputPort<T>& CreateAbstractLeafOutputPort(
std::string name,
ValueProducer producer,
std::set<DependencyTicket> calc_prerequisites);
// Creates a new cached LeafOutputPort in this LeafSystem and returns a
// reference to it. Pass fixed_size == nullopt for abstract ports, or the
// port size for vector ports. Prerequisites list must not be empty.
LeafOutputPort<T>& CreateCachedLeafOutputPort(
std::string name, const std::optional<int>& fixed_size,
ValueProducer value_producer,
std::set<DependencyTicket> calc_prerequisites);
// Creates an abstract output port allocator function from an arbitrary type
// model value.
template <typename OutputType>
static ValueProducer::AllocateCallback MakeAllocateCallback(
const OutputType& model_value) {
return internal::AbstractValueCloner(model_value);
}
// If @p model_vector's GetElementBounds provides any constraints,
// then declares inequality constraints on `this` using a calc function that
// obtains a VectorBase from a Context using @p get_vector_from_context and
// then compares the runtime value against the declaration-time
// VectorBase::GetElementBounds. The inequality constraint is imposed as
// lower_bounds <= get_vector_from_context(context) <= upper_bounds
// where lower_bounds and upper_bounds are obtained from
// model_vector.GetElementBounds.
void MaybeDeclareVectorBaseInequalityConstraint(
const std::string& kind, const VectorBase<T>& model_vector,
const std::function<const VectorBase<T>&(const Context<T>&)>&
get_vector_from_context);
// Periodic Update or Publish events declared by this system.
LeafCompositeEventCollection<T> periodic_events_;
// Update or Publish events declared by this system for every simulator
// major time step.
LeafCompositeEventCollection<T> per_step_events_;
// Update or Publish events that need to be handled at system initialization.
LeafCompositeEventCollection<T> initialization_events_;
// A model continuous state to be used during Context allocation.
std::unique_ptr<BasicVector<T>> model_continuous_state_vector_{
std::make_unique<BasicVector<T>>(0)};
// A model discrete state to be used during Context allocation.
DiscreteValues<T> model_discrete_state_;
// A model abstract state to be used during Context allocation.
internal::ModelValues model_abstract_states_;
// Model inputs to be used in AllocateInput{Vector,Abstract}.
internal::ModelValues model_input_values_;
// Model numeric parameters to be used during Context allocation.
internal::ModelValues model_numeric_parameters_;
// Model abstract parameters to be used during Context allocation.
internal::ModelValues model_abstract_parameters_;
};
} // namespace systems
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::LeafSystem)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/abstract_value_cloner.h | #pragma once
#include <memory>
#include "drake/common/copyable_unique_ptr.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/value.h"
namespace drake {
namespace systems {
namespace internal {
/* Provides a ValueProducer::AllocateCallback functor that clones the given
model_value. */
class AbstractValueCloner final {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(AbstractValueCloner)
/* Creates a clone functor for the given model value. */
template <typename SomeOutput>
explicit AbstractValueCloner(const SomeOutput& model_value)
: AbstractValueCloner(AbstractValue::Make<SomeOutput>(model_value)) {}
~AbstractValueCloner();
/* Returns a Clone of the model_value passed into the constructor. */
std::unique_ptr<AbstractValue> operator()() const;
private:
/* Creates a clone functor for the given model value. */
explicit AbstractValueCloner(std::unique_ptr<AbstractValue> model_value);
copyable_unique_ptr<AbstractValue> model_value_;
};
} // namespace internal
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/witness_function.cc | #include "drake/systems/framework/witness_function.h"
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::WitnessFunction)
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/system_scalar_conversion_doxygen.h | /** @file
Doxygen-only documentation for @ref system_scalar_conversion. */
//------------------------------------------------------------------------------
/** @defgroup system_scalar_conversion System Scalar Conversion
@ingroup technical_notes
System scalar conversion refers to cloning a System templatized by one scalar
type into an identical System that is templatized by a different scalar type.
For example, a `MySystem<double>` could be cloned to create a
`MySystem<AutoDiffXd>` in order to compute the partial numerical derivatives.
See the @ref default_scalars "default scalars" for list of supported types.
<h2>Example use of system scalar conversion</h2>
This is a small example to illustrate the concept.
@internal
N.B. The code sample immediately below must be kept in sync with the identical
code in test/system_scalar_conversion_doxygen_test.cc. This ensures that the
code sample compiles and runs successfully.
@endinternal
@code
// Establish the plant and its initial conditions:
// tau = 0, theta = 0.1, thetadot = 0.2.
auto plant = std::make_unique<PendulumPlant<double>>();
auto context = plant->CreateDefaultContext();
plant->get_input_port(0).FixValue(context.get(), 0.0); // tau
auto* state = dynamic_cast<PendulumState<double>*>(
context->get_mutable_continuous_state_vector());
state->set_theta(0.1);
state->set_thetadot(0.2);
double energy = plant->CalcTotalEnergy(*context);
ASSERT_NEAR(energy, -4.875, 0.001);
// Convert the plant and its context to use AutoDiff.
auto autodiff_plant = System<double>::ToAutoDiffXd(*plant);
auto autodiff_context = autodiff_plant->CreateDefaultContext();
autodiff_context->SetTimeStateAndParametersFrom(*context);
autodiff_plant->FixInputPortsFrom(*plant, *context, autodiff_context.get());
// Differentiate with respect to theta by setting dtheta/dtheta = 1.0.
constexpr int kNumDerivatives = 1;
auto& xc = *autodiff_context->get_mutable_continuous_state_vector();
xc[PendulumStateIndices::kTheta].derivatives() =
MatrixXd::Identity(kNumDerivatives, kNumDerivatives).col(0);
// Compute denergy/dtheta around its initial conditions.
AutoDiffXd autodiff_energy =
autodiff_plant->CalcTotalEnergy(*autodiff_context);
ASSERT_NEAR(autodiff_energy.value(), -4.875, 0.001);
ASSERT_EQ(autodiff_energy.derivatives().size(), 1);
ASSERT_NEAR(autodiff_energy.derivatives()[0], 0.490, 0.001);
@endcode
For a more thorough example, refer to the implementation of
drake::systems::Linearize.
@warning The supported method to perform scalar conversion uses the member
functions on System, e.g., `System::ToAutoDiffXd`. The scalar-converting
copy constructor (described below) is intended for internal use only.
For example:
@code
PendulumPlant<double> plant;
// WRONG
PendulumPlant<AutoDiffXd> plant_autodiff(plant);
// CORRECT
std::unique_ptr<PendulumPlant<AutoDiffXd>> autodiff_plant =
System<double>::ToAutoDiffXd(plant);
@endcode
@anchor system_scalar_conversion_how_to_write_a_system
<h2>How to write a System that supports scalar conversion</h2>
In the typical case, Drake users' Systems should be marked with the C++ keyword
`final` to prevent them from being subclassed. Whether or not the System is
`final` determines the best way to support scalar conversion.
In the examples below, we use `MySystem` as the name of a System class being
implemented by a Drake user.
<h3>Systems marked as `final`</h3>
For system marked with `final`,
the two examples below show how to enable system scalar conversion.
Example using drake::systems::LeafSystem as the base class:
@code
namespace sample {
template <typename T>
class MySystem final : public LeafSystem<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MySystem);
// Constructs a system with a gain of 1.0.
MySystem() : MySystem(1.0) {}
// Constructs a system with the given `gain`.
explicit MySystem(double gain)
: LeafSystem<T>(SystemTypeTag<MySystem>{}), gain_{gain} {}
// Scalar-converting copy constructor. See @ref system_scalar_conversion.
template <typename U>
explicit MySystem(const MySystem<U>& other) : MySystem<T>(other.gain()) {}
// Returns the gain of this system.
double gain() const { return gain_; }
...
@endcode
Example using drake::systems::VectorSystem as the base class:
@code
namespace sample {
template <typename T>
class MySystem final : public VectorSystem<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MySystem);
// Default constructor.
MySystem() : VectorSystem<T>(SystemTypeTag<MySystem>{}, 1, 1) {}
// Scalar-converting copy constructor. See @ref system_scalar_conversion.
template <typename U>
explicit MySystem(const MySystem<U>&) : MySystem<T>() {}
...
@endcode
The relevant details of the examples are:
- `MySystem` is templated on a scalar type `T`;
- `MySystem` is marked `final`;
- `DRAKE_NO_COPY_...` disables the built-in copy and move constructors;
- `MySystem` has whatever usual constructors make sense;
- sometimes it will have a default constructor;
- sometimes it will be given arguments in its constructor;
- as a C++ best practice, constructors should delegate into one primary
constructor;
- we see that above in the first example where the default constructor
delegates to the one-argument constructor;
- all `MySystem` constructors must pass a `SystemTypeTag` to their superclass
constructor; if all `MySystem` constructors delegate to a single one, this
is easy because only that one needs to provide the `SystemTypeTag` value;
- `MySystem` has a public scalar-converting copy constructor;
- the constructor takes a reference to `MySystem<U>` and delegates to another
constructor;
- the section *How to write a scalar-converting copy constructor* below
provides more details on how to implement this constructor.
<h3>Systems not marked as `final`</h3>
For a class hierarchy of Systems that support scalar conversion, a slightly
different pattern is required.
@code
namespace sample {
template <typename T>
class MySystemBase : public LeafSystem<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MySystemBase);
// Constructs a system with the given `gain`.
// Subclasses must use the protected constructor, not this one.
explicit MySystemBase(double gain)
: LeafSystem<T>(SystemTypeTag<MySystemBase>{}), gain_{gain} {}
// Scalar-converting copy constructor. See @ref system_scalar_conversion.
template <typename U>
explicit MySystemBase(const MySystemBase<U>& other)
: MySystemBase<T>(other.gain()) {}
// Returns the gain of this system.
double gain() const { return gain_; }
protected:
// Constructor that specifies scalar-type conversion support.
// @param converter scalar-type conversion support helper (i.e., AutoDiff,
// etc.); pass a default-constructed object if such support is not desired.
explicit MySystemBase(SystemScalarConverter converter, double gain)
: LeafSystem<T>(std::move(converter)), gain_{gain} {}
...
namespace sample {
template <typename T>
class MySystemDerived final : public MySystemBase<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MySystemDerived);
// Constructs a system with a gain of 1.0.
MySystemDerived() : MySystemBase<T>(
SystemTypeTag<MySystemDerived>{},
1.0) {}
// Scalar-converting copy constructor. See @ref system_scalar_conversion.
template <typename U>
explicit MySystemDerived(const MySystemDerived<U>&) : MySystemDerived<T>() {}
...
@endcode
The relevant details of the examples are:
- Non-`final` classes like `MySystemBase` must offer a protected constructor
that takes a SystemScalarConverter as the first argument.
- Constructors for derived classes such as `MySystemDerived` must delegate
to a base class protected constructor that takes a %SystemScalarConverter,
never to a public constructor without one.
- `MySystemBase` and `MySystemDerived` both have a public scalar-converting copy
constructor;
- if the base system is abstract (cannot be constructed), then it may omit
this constructor.
<h3>Limiting the supported scalar types</h3>
The framework's default implementation System scalar-type conversion only
converts between a limited set of scalar types, as enumerated by the
drake::systems::SystemScalarConverter::SystemScalarConverter(SystemTypeTag<S>)
constructor documentation.
Systems may specialize their drake::systems::scalar_conversion::Traits to
govern the supported scalar types. The recommended mechanism is to use
drake::systems::scalar_conversion::NonSymbolicTraits or
drake::systems::scalar_conversion::FromDoubleTraits.
<h2>How to write a scalar-converting copy constructor</h2>
The scalar-converting copy constructor uses the following form:
@code
template <typename T>
class Foo {
// Scalar-converting copy constructor.
template <typename U>
explicit Foo(const Foo<U>& other);
};
@endcode
Here, `U` is the source scalar type (to convert from), and `T` the resulting
scalar type (to convert into). For example, in the second line of
@code
Foo<double> foo;
Foo<AutoDiffXd> autodiff_foo{foo};
@endcode
we are calling the constructor `Foo<AutoDiffXd>::Foo(const Foo<double>&)` so we
have `U = double` and `T = AutoDiffXd`. In other words, we start with a
`double`-valued object and use it to create an `AutoDiffXd`-valued object.
<h3>Delegation</h3>
In almost all cases, the implementation of the scalar-converting copy
constructor should delegate to another regular constructor, rather than
re-implementing its logic. For example, in the `VectorSystem`-based example
above we have:
@code
MySystem() : VectorSystem<T>(SystemTypeTag<MySystem>{}, 1, 1) {}
template <typename U> explicit MySystem(const MySystem<U>&) : MySystem<T>() {}
@endcode
The default constructor configures the System to have a `input_size == 1` and
`output_size == 1`. The scalar-converting copy constructor delegates to the
default constructor to re-use that logic by stating `: MySystem<T>()`.
Without delegation, we would have to duplicate those arguments:
@code
MySystem() : VectorSystem<T>(SystemTypeTag<MySystem>{}, 1, 1) {}
// NOT RECOMMENDED because it duplicates the details of calling VectorSystem.
template <typename U> explicit MySystem(const MySystem<U>&)
: VectorSystem<T>(SystemTypeTag<MySystem>{}, 1, 1) {}
@endcode
<h3>Instance data</h3>
If the object being copied from (usually named `other`) has any instance data
or customizations, the scalar-converting copy constructor should propagate them
from `other` to `this`. For example, in the `LeafSystem`-based example above,
we have:
@code
template <typename U>
explicit MySystem(const MySystem<U>& other) : MySystem<T>(other.gain()) {}
@endcode
<h2>How to create a Diagram that supports scalar conversion</h2>
In the typical case, no special effort is needed to create a Diagram that
support scalar-type conversion. The Diagram does not even need to be templated
on a scalar type `T`.
Example using DiagramBuilder::BuildInto:
@code
namespace sample {
class MyDiagram : public Diagram<double> {
public:
MyDiagram() {
DiagramBuilder<double> builder;
const auto* integrator = builder.AddSystem<Integrator<double>>(1);
builder.ExportInput(integrator->get_input_port());
builder.ExportOutput(integrator->get_output_port());
builder.BuildInto(this);
}
};
@endcode
In this example, `MyDiagram` will support the same scalar types as the
Integrator. If any sub-system had been added that did not support, e.g.,
symbolic form, then the Diagram would also not support symbolic form.
By default, even subclasses of a `Diagram<U>` will convert to a `Diagram<T>`,
discarding the diagram subclass details. For example, in the above sample
code, `MyDiagram::ToAutoDiffXd()` will return an object of runtime type
`Diagram<AutoDiffXd>`, not type `MyDiagram<AutoDiffXd>`. (There is no such
class as `MyDiagram<AutoDiffXd>` anyway, because `MyDiagram` is not templated.)
In the unusual case that the Diagram's subclass must be preserved during
conversion, a ::drake::systems::SystemTypeTag should be used:
Example using DiagramBuilder::BuildInto along with a `SystemTypeTag`:
@code
namespace sample {
template <typename T>
class SpecialDiagram<T> final : public Diagram<T> {
public:
SpecialDiagram() : Diagram<T>(SystemTypeTag<SpecialDiagram>{}) {
DiagramBuilder<T> builder;
const auto* integrator = builder.template AddSystem<Integrator<T>>(1);
builder.ExportInput(integrator->get_input_port());
builder.ExportOutput(integrator->get_output_port());
builder.BuildInto(this);
}
// Scalar-converting copy constructor. See @ref system_scalar_conversion.
template <typename U>
explicit SpecialDiagram(const SpecialDiagram<U>& other)
: SpecialDiagram<T>(SystemTypeTag<SpecialDiagram>{}, other) {}
};
@endcode
*/
| 0 |
/home/johnshepherd/drake/systems | /home/johnshepherd/drake/systems/framework/abstract_values.h | #pragma once
#include <memory>
#include <vector>
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/value.h"
namespace drake {
namespace systems {
/// AbstractValues is a container for non-numerical state and parameters.
/// It may or may not own the underlying data, and therefore is suitable
/// for both leaf Systems and diagrams.
class AbstractValues {
public:
// AbstractState is not copyable or moveable.
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(AbstractValues)
/// Constructs an empty AbstractValues.
AbstractValues();
/// Constructs an AbstractValues that owns the underlying data.
///
/// @exclude_from_pydrake_mkdoc{The next overload's docstring is better, and
/// we only need one of the two -- overloading on ownership doesn't make
/// sense for pydrake.}
explicit AbstractValues(std::vector<std::unique_ptr<AbstractValue>>&& data);
/// Constructs an AbstractValues that does not own the underlying data.
explicit AbstractValues(const std::vector<AbstractValue*>& data);
/// Constructs an AbstractValues that owns a single @p datum.
///
/// @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
explicit AbstractValues(std::unique_ptr<AbstractValue> datum);
virtual ~AbstractValues();
/// Returns the number of elements of AbstractValues.
int size() const;
/// Returns the element of AbstractValues at the given @p index, or aborts if
/// the index is out-of-bounds.
const AbstractValue& get_value(int index) const;
/// Returns the element of AbstractValues at the given @p index, or aborts if
/// the index is out-of-bounds.
AbstractValue& get_mutable_value(int index);
/// Copies all of the AbstractValues in @p other into this. Asserts if the
/// two are not equal in size.
/// @throws std::exception if any of the elements are of incompatible type.
void SetFrom(const AbstractValues& other);
/// Returns a deep copy of all the data in this AbstractValues. The clone
/// will own its own data. This is true regardless of whether the data being
/// cloned had ownership of its data or not.
std::unique_ptr<AbstractValues> Clone() const;
private:
// Pointers to the data. If the data is owned, these pointers are equal to
// the pointers in owned_data_.
std::vector<AbstractValue*> data_;
// Owned pointers to the data. The only purpose of these pointers is to
// maintain ownership. They may be populated at construction time, and are
// never accessed thereafter.
std::vector<std::unique_ptr<AbstractValue>> owned_data_;
};
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test_utilities/my_vector.h | #pragma once
#include <memory>
#include <utility>
#include "drake/common/drake_copyable.h"
#include "drake/common/drake_throw.h"
#include "drake/common/eigen_types.h"
#include "drake/common/pointer_cast.h"
#include "drake/systems/framework/basic_vector.h"
namespace drake {
namespace systems {
/// A simple subclass of BasicVector<T> for testing, particularly for cases
/// where BasicVector subtyping must be preserved through the framework.
template <typename T, int N>
class MyVector : public BasicVector<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MyVector)
/// Constructs an uninitialized N-vector.
MyVector() : BasicVector<T>(N) {}
/// Constructs from a variable-length vector whose length must be N.
explicit MyVector(const VectorX<T>& data) : BasicVector<T>(data) {
DRAKE_THROW_UNLESS(data.size() == N);
}
/// Constructs from a fixed-size Eigen VectorN.
explicit MyVector(const Eigen::Matrix<T, N, 1>& data)
: BasicVector<T>(data) {}
/// Constructs a MyVector where each element is constructed using the
/// placewise-corresponding member of @p args as the sole constructor
/// argument. For instance: `MyVector<2, double>::Make(1.1, 2.2)`.
template<typename... Fargs>
static std::unique_ptr<MyVector> Make(Fargs&&... args) {
static_assert(sizeof...(args) == N,
"The number of arguments must match the MyVector size");
auto data = std::make_unique<MyVector>();
BasicVector<T>::MakeRecursive(data.get(), 0, args...);
return data;
}
// TODO(jwnimmer-tri) This is extremely dangerous -- the return type of Clone
// determines template argument for the Value<> that is type-erased into an
// AbstractValue; we should not pun away from BasicVector, since many methods
// in the leaf system and context code assumes that BasicVector is what gets
// type-erased!
/// Shadows the base class Clone() method to change the return type, so that
/// this can be used in `copyable_unique_ptr<MyVector>` and `Value<MyVector>`.
std::unique_ptr<MyVector<T, N>> Clone() const {
return dynamic_pointer_cast_or_throw<MyVector<T, N>>(
BasicVector<T>::Clone());
}
// Allow unit tests to read/write the underlying MatrixXd directly.
using BasicVector<T>::values;
private:
// BasicVector's Clone() method handles copying the values; DoClone() is
// only supposed to allocate a vector of the right concrete type and size.
[[nodiscard]] MyVector* DoClone() const override {
return new MyVector();
}
};
using MyVector1d = MyVector<double, 1>;
using MyVector2d = MyVector<double, 2>;
using MyVector3d = MyVector<double, 3>;
using MyVector4d = MyVector<double, 4>;
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test_utilities/BUILD.bazel | load("//tools/lint:lint.bzl", "add_lint_tests")
load(
"//tools/skylark:drake_cc.bzl",
"drake_cc_googletest",
"drake_cc_library",
"drake_cc_package_library",
)
package(default_visibility = ["//visibility:public"])
drake_cc_package_library(
name = "test_utilities",
testonly = 1,
visibility = ["//visibility:public"],
deps = [
":initialization_test_system",
":my_vector",
":pack_value",
":scalar_conversion",
],
)
drake_cc_library(
name = "initialization_test_system",
testonly = 1,
srcs = [],
hdrs = ["initialization_test_system.h"],
deps = [
"//systems/framework",
],
)
drake_cc_library(
name = "pack_value",
testonly = 1,
srcs = [],
hdrs = ["pack_value.h"],
deps = [
"//common:value",
],
)
drake_cc_library(
name = "my_vector",
testonly = 1,
srcs = [],
hdrs = ["my_vector.h"],
deps = [
"//common:essential",
"//common:pointer_cast",
"//systems/framework:vector",
],
)
drake_cc_library(
name = "scalar_conversion",
testonly = 1,
srcs = [],
hdrs = ["scalar_conversion.h"],
deps = [
"//common/test_utilities:is_dynamic_castable",
],
)
# === test/ ===
drake_cc_googletest(
name = "my_vector_test",
deps = [
":my_vector",
"//common:copyable_unique_ptr",
"//common:value",
"//common/test_utilities:expect_throws_message",
"//common/test_utilities:is_dynamic_castable",
],
)
add_lint_tests(enable_clang_format_lint = False)
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test_utilities/initialization_test_system.h | #pragma once
#include <vector>
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace systems {
/** A LeafSystem which declares all possible initialization events, and records
information (in mutable variables and in the context) about whether the events
have been processed. This can be used to confirm that initialization events
are properly handled. */
class InitializationTestSystem : public LeafSystem<double> {
public:
InitializationTestSystem() {
// N.B. In the code below, we call the DeclareInitializationEvent() internal
// API to declare events, so that we can carefully inspect the contents
// during unit testing. Users should NOT use this event API, but instead the
// DeclareInitializationPublishEvent(), etc.
// Publish event.
PublishEvent<double> pub_event(
TriggerType::kInitialization,
[this](const System<double>&, const Context<double>&,
const PublishEvent<double>& event) {
EXPECT_EQ(event.get_trigger_type(), TriggerType::kInitialization);
this->InitPublish();
return EventStatus::Succeeded();
});
DeclareInitializationEvent(pub_event);
// Discrete state and update event.
DeclareDiscreteState(1);
DiscreteUpdateEvent<double> discrete_update_event(
TriggerType::kInitialization,
[this](const System<double>&, const Context<double>&,
const DiscreteUpdateEvent<double>& event,
DiscreteValues<double>* discrete_state) {
EXPECT_EQ(event.get_trigger_type(), TriggerType::kInitialization);
this->InitDiscreteUpdate(discrete_state);
return EventStatus::Succeeded();
});
DeclareInitializationEvent(discrete_update_event);
// Abstract state and update event.
DeclareAbstractState(Value<bool>(false));
UnrestrictedUpdateEvent<double> unrestricted_update_event(
TriggerType::kInitialization,
[this](const System<double>&, const Context<double>&,
const UnrestrictedUpdateEvent<double>& event,
State<double>* state) {
EXPECT_EQ(event.get_trigger_type(), TriggerType::kInitialization);
this->InitUnrestrictedUpdate(state);
return EventStatus::Succeeded();
});
DeclareInitializationEvent(unrestricted_update_event);
}
bool get_pub_init() const { return pub_init_; }
bool get_dis_update_init() const { return dis_update_init_; }
bool get_unres_update_init() const { return unres_update_init_; }
private:
void InitPublish() const {
pub_init_ = true;
}
void InitDiscreteUpdate(DiscreteValues<double>* discrete_state) const {
dis_update_init_ = true;
discrete_state->set_value(Vector1d(1.23));
}
void InitUnrestrictedUpdate(State<double>* state) const {
unres_update_init_ = true;
state->get_mutable_abstract_state<bool>(0) = true;
}
mutable bool pub_init_{false};
mutable bool dis_update_init_{false};
mutable bool unres_update_init_{false};
};
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test_utilities/scalar_conversion.h | #pragma once
#include <memory>
#include "drake/common/test_utilities/is_dynamic_castable.h"
namespace drake {
namespace systems {
namespace test {
// A helper function incompatible with symbolic::Expression. This is useful to
// prove that scalar conversion code does not even instantiate this function
// when T = symbolic::Expression when told not to. If it did, we see compile
// errors that this function does not compile with T = symbolic::Expression.
template <typename T>
static T copysign_int_to_non_symbolic_scalar(int magic, const T& value) {
if ((magic < 0) == (value < 0.0)) {
return value;
} else {
return -value;
}
}
} // namespace test
/// Tests whether the given device under test of type S<double> can be
/// converted to use AutoDiffXd as its scalar type. If the test passes,
/// additional checks on the converted object of type `const S<AutoDiffXd>&`
/// can be passed via a lambda into @p callback. The Callback must take an
/// `const S<AutoDiffXd>&` and return void; a typical value would be a lambda
/// such as `[](const auto& converted) { EXPECT_TRUE(converted.thing()); }`.
template <template <typename> class S, typename Callback>
::testing::AssertionResult is_autodiffxd_convertible(
const S<double>& dut, Callback callback) {
// We must use salted local variable names ("_67273" suffix) to work around
// GCC 5.4 bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67273 because the
// `callback` is a generic lambda. The bug is fixed as of GCC 6.1.
// Check if a proper type came out; return early if not.
std::unique_ptr<System<AutoDiffXd>> converted_67273 =
dut.ToAutoDiffXdMaybe();
::testing::AssertionResult result_67273 =
is_dynamic_castable<S<AutoDiffXd>>(converted_67273);
if (!result_67273) { return result_67273; }
// Allow calling code to specify additional tests on the converted System.
const S<AutoDiffXd>& downcast_67273 =
dynamic_cast<const S<AutoDiffXd>&>(*converted_67273);
callback(downcast_67273);
return ::testing::AssertionSuccess();
}
/// Tests whether the given device under test of type S<double> can be
/// converted to use AutoDiffXd as its scalar type.
template <template <typename> class S>
::testing::AssertionResult is_autodiffxd_convertible(const S<double>& dut) {
return is_autodiffxd_convertible(dut, [](const auto&){});
}
/// Tests whether the given device under test of type S<double> can be
/// converted to use Expression as its scalar type. If the test passes,
/// additional checks on the converted object of type `const S<Expression>&`
/// can be passed via a lambda into @p callback. The Callback must take an
/// `const S<Expression>&` and return void; a typical value would be a lambda
/// such as `[](const auto& converted) { EXPECT_TRUE(converted.thing()); }`.
template <template <typename> class S, typename Callback>
::testing::AssertionResult is_symbolic_convertible(
const S<double>& dut, Callback callback) {
// We must use salted local variable names ("_67273" suffix) to work around
// GCC 5.4 bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67273 because the
// `callback` is a generic lambda. The bug is fixed as of GCC 6.1.
// Check if a proper type came out; return early if not.
std::unique_ptr<System<symbolic::Expression>> converted_67273 =
dut.ToSymbolicMaybe();
::testing::AssertionResult result_67273 =
is_dynamic_castable<S<symbolic::Expression>>(converted_67273);
if (!result_67273) { return result_67273; }
// Allow calling code to specify additional tests on the converted System.
const S<symbolic::Expression>& downcast_67273 =
dynamic_cast<const S<symbolic::Expression>&>(*converted_67273);
callback(downcast_67273);
return ::testing::AssertionSuccess();
}
/// Tests whether the given device under test of type S<double> can be
/// converted to use Expression as its scalar type.
template <template <typename> class S>
::testing::AssertionResult is_symbolic_convertible(const S<double>& dut) {
return is_symbolic_convertible(dut, [](const auto&){});
}
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test_utilities/pack_value.h | #pragma once
#include <memory>
#include "drake/common/drake_assert.h"
#include "drake/common/value.h"
namespace drake {
namespace systems {
/// Makes a new AbstractValue containing the @p value.
template <typename T>
std::unique_ptr<AbstractValue> PackValue(T value) {
return std::make_unique<Value<T>>(value);
}
/// Extracts data of type T from the given @p value, or throws if the
/// @p value does not contain type T.
template <typename T>
T UnpackValue(const AbstractValue& value) {
return value.get_value<T>();
}
/// Extracts an integer from the given @p value, or aborts if the
/// @p value does not contain an integer.
int UnpackIntValue(const AbstractValue* value) {
return UnpackValue<int>(*value);
}
/// Extracts an integer from the given @p value, or aborts if the
/// @p value does not contain an integer.
int UnpackIntValue(const AbstractValue& value) {
return UnpackValue<int>(value);
}
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework/test_utilities | /home/johnshepherd/drake/systems/framework/test_utilities/test/my_vector_test.cc | #include "drake/systems/framework/test_utilities/my_vector.h"
#include <gtest/gtest.h>
#include "drake/common/copyable_unique_ptr.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/test_utilities/is_dynamic_castable.h"
#include "drake/common/value.h"
namespace drake {
namespace systems {
namespace {
using Eigen::Vector2d;
using Eigen::Vector3d;
using Eigen::Vector4d;
// Make sure all the constructors work properly.
GTEST_TEST(MyVectorTest, Construction) {
// Default constructor leaves memory uninitialized so don't peek.
MyVector3d default_vector;
EXPECT_TRUE(is_dynamic_castable<BasicVector<double>>(&default_vector));
EXPECT_EQ(default_vector.size(), 3);
Vector4d fixed_size4(1., 2., 3., 4.);
VectorX<double> variable_size4(fixed_size4);
MyVector4d from_fixed_size(fixed_size4);
EXPECT_EQ(from_fixed_size.get_value(), variable_size4);
MyVector4d from_variable_size(variable_size4);
EXPECT_EQ(from_variable_size.get_value(), fixed_size4);
}
// Misuse of the test utility is an abort-able infraction.
GTEST_TEST(MyVectorTest, BadSize) {
Vector4d fixed_size4(1., 2., 3., 4.);
DRAKE_EXPECT_THROWS_MESSAGE(
MyVector3d(VectorX<double>(fixed_size4)),
".*size.*fail.*");
// This won't compile since there is no constructor with mismatched sizes.
// MyVector3d from_4(fixed_size4);
}
// Test the Make() method (takes a variable length arg list).
GTEST_TEST(MyVectorTest, MakeMethod) {
auto vector3 = MyVector3d::Make(1., 2., 3.);
EXPECT_EQ(vector3->get_value(), Vector3d(1., 2., 3.));
auto vector4 = MyVector4d::Make(10, 20, 30, 40);
EXPECT_EQ(vector4->get_value(), Vector4d(10., 20., 30., 40.));
}
// Tests that cloning works and check compatibility with copyable_unique_ptr
// and AbstractValue.
GTEST_TEST(MyVectorTest, Clone) {
MyVector3d vector3(Vector3d(1., 2., 3.));
auto clone = vector3.Clone();
// Changing the original should not affect the clone.
vector3[1] = 20.;
EXPECT_EQ(vector3.get_value(), Vector3d(1., 20., 3.));
EXPECT_EQ(clone->get_value(), Vector3d(1., 2., 3.));
// Value<T> requires that T be copyable or cloneable.
auto abstract3 = AbstractValue::Make(vector3);
auto& casted3 = abstract3->get_value<MyVector3d>();
EXPECT_EQ(casted3.get_value(), vector3.get_value());
// copyable_unique_ptr<T> requires that T be copyable or cloneable.
copyable_unique_ptr<MyVector2d> vec1{new MyVector2d(Vector2d(1, 2))};
EXPECT_EQ(vec1->size(), 2);
EXPECT_EQ(vec1->get_value(), Vector2d(1, 2));
copyable_unique_ptr<MyVector2d> vec2(vec1);
vec2->set_value(Vector2d(9, 10));
EXPECT_EQ(vec1->get_value(), Vector2d(1, 2));
EXPECT_EQ(vec2->get_value(), Vector2d(9, 10));
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/abstract_value_cloner_test.cc | #include "drake/systems/framework/abstract_value_cloner.h"
#include <gtest/gtest.h>
#include "drake/systems/framework/basic_vector.h"
namespace drake {
namespace systems {
namespace {
// Tests AbstractValueCloner on a copyable type.
GTEST_TEST(AbstractValueClonerTest, Copyable) {
const internal::AbstractValueCloner dut(std::string("foo"));
const internal::AbstractValueCloner dut_copy(dut);
std::unique_ptr<AbstractValue> new_value = dut_copy();
EXPECT_EQ(new_value->get_value<std::string>(), "foo");
}
// Tests AbstractValueCloner on a non-copyable, cloneable type.
GTEST_TEST(AbstractValueClonerTest, Cloneable) {
static_assert(is_cloneable<BasicVector<double>>::value, "");
const internal::AbstractValueCloner dut(BasicVector<double>(2));
const internal::AbstractValueCloner dut_copy(dut);
std::unique_ptr<AbstractValue> new_value = dut_copy();
EXPECT_EQ(new_value->get_value<BasicVector<double>>().size(), 2);
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/diagram_context_test.cc | #include "drake/systems/framework/diagram_context.h"
#include <stdexcept>
#include <vector>
#include <Eigen/Dense>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "drake/common/pointer_cast.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/fixed_input_port_value.h"
#include "drake/systems/framework/leaf_context.h"
#include "drake/systems/framework/leaf_system.h"
#include "drake/systems/framework/system.h"
#include "drake/systems/framework/test_utilities/pack_value.h"
#include "drake/systems/primitives/adder.h"
#include "drake/systems/primitives/integrator.h"
namespace drake {
namespace systems {
namespace {
constexpr int kSize = 1;
constexpr int kNumSystems = 8;
constexpr double kTime = 12.0;
class SystemWithDiscreteState : public LeafSystem<double> {
public:
SystemWithDiscreteState() {
DeclareDiscreteState(1);
}
~SystemWithDiscreteState() override {}
};
class SystemWithAbstractState : public LeafSystem<double> {
public:
SystemWithAbstractState() {
DeclareAbstractState(Value<int>(42));
}
~SystemWithAbstractState() override {}
};
class SystemWithNumericParameters : public LeafSystem<double> {
public:
SystemWithNumericParameters() {
DeclareNumericParameter(BasicVector<double>(2));
}
~SystemWithNumericParameters() override {}
};
class SystemWithAbstractParameters : public LeafSystem<double> {
public:
SystemWithAbstractParameters() {
DeclareAbstractParameter(Value<int>(2048));
}
~SystemWithAbstractParameters() override {}
};
} // namespace
// This class must be outside the anonymous namespace to permit the
// DiagramContext friend declaration to work.
class DiagramContextTest : public ::testing::Test {
protected:
void SetUp() override {
adder0_ = std::make_unique<Adder<double>>(2 /* inputs */, kSize);
adder1_ = std::make_unique<Adder<double>>(2 /* inputs */, kSize);
integrator0_.reset(new Integrator<double>(kSize));
integrator1_.reset(new Integrator<double>(kSize));
discrete_state_system_ = std::make_unique<SystemWithDiscreteState>();
abstract_state_system_ = std::make_unique<SystemWithAbstractState>();
system_with_numeric_parameters_ =
std::make_unique<SystemWithNumericParameters>();
system_with_abstract_parameters_ =
std::make_unique<SystemWithAbstractParameters>();
adder0_->set_name("adder0");
adder1_->set_name("adder1");
integrator0_->set_name("integrator0");
integrator1_->set_name("integrator1");
discrete_state_system_->set_name("discrete_state_system");
abstract_state_system_->set_name("abstract_state_system");
system_with_numeric_parameters_->set_name("system_with_numeric_parameters");
system_with_abstract_parameters_->set_name(
"system_with_abstract_parameters");
// This chunk of code is partially mimicking Diagram::DoAllocateContext()
// which is normally in charge of making DiagramContexts.
context_ = std::make_unique<DiagramContext<double>>(kNumSystems);
internal::SystemBaseContextBaseAttorney::set_system_id(
context_.get(), internal::SystemId::get_new_id());
// Don't change these indexes -- tests below depend on them.
AddSystem(*adder0_, SubsystemIndex(0));
AddSystem(*adder1_, SubsystemIndex(1));
AddSystem(*integrator0_, SubsystemIndex(2));
AddSystem(*integrator1_, SubsystemIndex(3));
AddSystem(*discrete_state_system_, SubsystemIndex(4));
AddSystem(*abstract_state_system_, SubsystemIndex(5));
AddSystem(*system_with_numeric_parameters_, SubsystemIndex(6));
AddSystem(*system_with_abstract_parameters_, SubsystemIndex(7));
// Fake up some input ports for this diagram.
context_->AddInputPort(InputPortIndex(0), DependencyTicket(100), {});
context_->AddInputPort(InputPortIndex(1), DependencyTicket(101), {});
context_->MakeState();
context_->MakeParameters();
context_->SubscribeDiagramCompositeTrackersToChildrens();
context_->SetTime(kTime);
ContinuousState<double>& xc = context_->get_mutable_continuous_state();
xc.get_mutable_vector()[0] = 42.0;
xc.get_mutable_vector()[1] = 43.0;
DiscreteValues<double>& xd = context_->get_mutable_discrete_state();
xd.get_mutable_vector(0)[0] = 44.0;
context_->get_mutable_numeric_parameter(0)[0] = 76.0;
context_->get_mutable_numeric_parameter(0)[1] = 77.0;
// Sanity checks: tests below count on these dimensions.
EXPECT_EQ(context_->num_continuous_states(), 2);
EXPECT_EQ(context_->num_discrete_state_groups(), 1);
EXPECT_EQ(context_->num_abstract_states(), 1);
EXPECT_EQ(context_->num_numeric_parameter_groups(), 1);
EXPECT_EQ(context_->num_abstract_parameters(), 1);
EXPECT_EQ(context_->num_subcontexts(), kNumSystems);
}
// Some tests below need to know which of the subsystems above have particular
// resources. They use kNumSystems to identify the "parent" subsystem which
// inherits all the resources of its children.
static std::set<int> has_continuous_state() { return {2, 3, kNumSystems}; }
static std::set<int> has_discrete_state() { return {4, kNumSystems}; }
static std::set<int> has_abstract_state() { return {5, kNumSystems}; }
static std::set<int> has_state() { return {2, 3, 4, 5, kNumSystems}; }
static std::set<int> has_numeric_parameter() { return {6, kNumSystems}; }
static std::set<int> has_abstract_parameter() { return {7, kNumSystems}; }
static std::set<int> has_parameter() { return {6, 7, kNumSystems}; }
void AddSystem(const System<double>& sys, SubsystemIndex index) {
auto subcontext = sys.CreateDefaultContext();
context_->AddSystem(index, std::move(subcontext));
}
void AttachInputPorts() {
context_->FixInputPort(0, Value<BasicVector<double>>(
Vector1<double>(128.0)));
context_->FixInputPort(1, Value<BasicVector<double>>(
Vector1<double>(256.0)));
}
// Reads a FixedInputPortValue connected to @p context at @p index.
// Returns nullptr if the port is not connected.
const BasicVector<double>* ReadVectorInputPort(const Context<double>& context,
int index) {
const FixedInputPortValue* free_value =
context.MaybeGetFixedInputPortValue(InputPortIndex(index));
return free_value ? &free_value->get_vector_value<double>() : nullptr;
}
// Check that time is set as expected in the Diagram and all the subcontexts.
void VerifyTimeValue(double expected_time) {
// Check the Diagram.
EXPECT_EQ(context_->get_time(), expected_time);
// Make sure time got delivered to the subcontexts.
for (SubsystemIndex i(0); i < kNumSystems; ++i) {
const auto& subcontext = context_->GetSubsystemContext(i);
EXPECT_EQ(subcontext.get_time(), expected_time);
}
}
// Check that accuracy is set to the expected numerical value in the Diagram
// and all the subcontexts. Don't call this for uninitialized (optional)
// accuracy.
void VerifyAccuracyValue(double expected_accuracy) {
// Check the Diagram.
ASSERT_TRUE(context_->get_accuracy());
EXPECT_EQ(context_->get_accuracy().value(), expected_accuracy);
// Make sure time got delivered to the subcontexts.
for (SubsystemIndex i(0); i < kNumSystems; ++i) {
const auto& subcontext = context_->GetSubsystemContext(i);
ASSERT_TRUE(subcontext.get_accuracy());
EXPECT_EQ(subcontext.get_accuracy().value(), expected_accuracy);
}
}
// Check that the continuous state has the expected value, in both the
// Diagram and its continuous-state-holding subcontexts, which are the two
// integrators.
void VerifyContinuousStateValue(const Eigen::Vector2d& expected) {
// Make sure state is right in the Diagram.
EXPECT_EQ(context_->get_continuous_state_vector().CopyToVector(), expected);
// Make sure state got delivered to the integrators.
EXPECT_EQ(context_->GetSubsystemContext(SubsystemIndex(2))
.get_continuous_state_vector()[0],
expected[0]);
EXPECT_EQ(context_->GetSubsystemContext(SubsystemIndex(3))
.get_continuous_state_vector()[0],
expected[1]);
}
// Record the notification count for the given tracker in each of the
// subcontexts, followed by the notification count for that same tracker in
// the diagram context, so there are kNumSystems + 1 in the returned vector.
std::vector<int64_t> SaveNotifications(DependencyTicket ticket) {
std::vector<int64_t> notifications;
for (SubsystemIndex i(0); i < kNumSystems; ++i) {
notifications.push_back(
NumNotifications(context_->GetSubsystemContext(i), ticket));
}
notifications.push_back(NumNotifications(*context_, ticket));
return notifications;
}
// Verify that the current notification count is as expected, relative to the
// given `before_count`. `should_have_been_notified` says which subsystems
// should have received a notification, with kNumSystems treated as the index
// of the diagram "subsystem". `before_count` is updated on return so it can
// be used in a subsequent test.
void VerifyNotifications(const std::string& which,
const std::set<int>& should_have_been_notified,
DependencyTicket ticket,
std::vector<int64_t>* before_count) { // in/out
auto count_now = SaveNotifications(ticket);
ASSERT_EQ(count_now.size(), kNumSystems + 1);
ASSERT_EQ(before_count->size(), kNumSystems + 1);
for (int i = 0; i <= kNumSystems; ++i) {
const int n = should_have_been_notified.contains(i) ? 1 : 0;
(*before_count)[i] += n;
EXPECT_EQ(count_now[i], (*before_count)[i]) << which << " of system "
<< i;
}
}
// Verify that all subsystem trackers with this ticket were notified,
// including the diagram, and updated the expected notification count.
void VerifyNotifications(const std::string& which, DependencyTicket ticket,
std::vector<int64_t>* before_count) { // in/out
std::set<int> should_have_been_notified;
for (int i = 0; i <= kNumSystems; ++i) should_have_been_notified.insert(i);
VerifyNotifications(which, should_have_been_notified, ticket, before_count);
}
// Return the current notification count for the given tracker in the given
// context. Don't count multiple notifications for the same change event.
static int64_t NumNotifications(const ContextBase& context,
DependencyTicket ticket) {
const auto& tracker = context.get_tracker(ticket);
return tracker.num_notifications_received()
- tracker.num_ignored_notifications();
}
std::unique_ptr<DiagramContext<double>> context_;
std::unique_ptr<Adder<double>> adder0_;
std::unique_ptr<Adder<double>> adder1_;
std::unique_ptr<Integrator<double>> integrator0_;
std::unique_ptr<Integrator<double>> integrator1_;
std::unique_ptr<SystemWithDiscreteState> discrete_state_system_;
std::unique_ptr<SystemWithAbstractState> abstract_state_system_;
std::unique_ptr<SystemWithNumericParameters> system_with_numeric_parameters_;
std::unique_ptr<SystemWithAbstractParameters>
system_with_abstract_parameters_;
};
namespace {
// Verifies that @p state is a clone of the state constructed in
// DiagramContextTest::SetUp.
void VerifyClonedState(const State<double>& clone) {
// - Continuous
const ContinuousState<double>& xc = clone.get_continuous_state();
EXPECT_EQ(42.0, xc.get_vector()[0]);
EXPECT_EQ(43.0, xc.get_vector()[1]);
// - Discrete
const DiscreteValues<double>& xd = clone.get_discrete_state();
EXPECT_EQ(44.0, xd.get_vector(0)[0]);
// - Abstract
const AbstractValues& xa = clone.get_abstract_state();
EXPECT_EQ(42, xa.get_value(0).get_value<int>());
}
// Verifies that the @p params are a clone of the params constructed in
// DiagramContextTest::SetUp.
void VerifyClonedParameters(const Parameters<double>& params) {
ASSERT_EQ(1, params.num_numeric_parameter_groups());
EXPECT_EQ(76.0, params.get_numeric_parameter(0)[0]);
EXPECT_EQ(77.0, params.get_numeric_parameter(0)[1]);
ASSERT_EQ(1, params.num_abstract_parameters());
EXPECT_EQ(2048, UnpackIntValue(params.get_abstract_parameter(0)));
}
// Tests that subsystems have contexts in the DiagramContext.
TEST_F(DiagramContextTest, RetrieveConstituents) {
// All of the subsystems should be leaf Systems.
for (SubsystemIndex i(0); i < kNumSystems; ++i) {
auto context = dynamic_cast<const LeafContext<double>*>(
&context_->GetSubsystemContext(i));
EXPECT_TRUE(context != nullptr);
}
}
// The notification tests here are verifying the "down" notification direction.
// That is, we want to see that if we modify a context value at the Diagram
// level, change notifications propagate out to the contained LeafSystems.
// The other direction, modifying a LeafContext value that should notify
// the Diagram, is verified in diagram_test.
// Tests that the time writes through to the subsystem contexts, and that all
// time trackers are notified.
TEST_F(DiagramContextTest, Time) {
auto before = SaveNotifications(SystemBase::time_ticket());
context_->SetTime(42.0);
VerifyTimeValue(42.);
VerifyNotifications("Time", SystemBase::time_ticket(), &before);
}
// Tests that the accuracy writes through to the subsystem contexts, and that
// all accuracy trackers are notified.
TEST_F(DiagramContextTest, Accuracy) {
auto before = SaveNotifications(SystemBase::accuracy_ticket());
const double new_accuracy = 1e-12;
context_->SetAccuracy(new_accuracy);
VerifyAccuracyValue(new_accuracy);
VerifyNotifications("Accuracy", SystemBase::accuracy_ticket(), &before);
}
// Test that State notifications propagate down from the diagram to the leaves.
TEST_F(DiagramContextTest, MutableStateNotifications) {
auto x_before = SaveNotifications(SystemBase::all_state_ticket());
auto xc_before = SaveNotifications(SystemBase::xc_ticket());
auto xd_before = SaveNotifications(SystemBase::xd_ticket());
auto xa_before = SaveNotifications(SystemBase::xa_ticket());
// Changing the whole state should affect all the substates.
context_->get_mutable_state(); // Return value ignored.
VerifyNotifications("get_mutable_state: x", has_state(),
SystemBase::all_state_ticket(), &x_before);
VerifyNotifications("get_mutable_state: xc", has_continuous_state(),
SystemBase::xc_ticket(), &xc_before);
VerifyNotifications("get_mutable_state: xd", has_discrete_state(),
SystemBase::xd_ticket(), &xd_before);
VerifyNotifications("get_mutable_state: xa", has_abstract_state(),
SystemBase::xa_ticket(), &xa_before);
// Changing continuous state should affect only x and xc.
context_->get_mutable_continuous_state(); // Return value ignored.
VerifyNotifications("get_mutable_continuous_state: x", has_continuous_state(),
SystemBase::all_state_ticket(), &x_before);
VerifyNotifications("get_mutable_continuous_state: xc",
has_continuous_state(), SystemBase::xc_ticket(),
&xc_before);
VerifyNotifications("get_mutable_continuous_state: xd", {}, // None.
SystemBase::xd_ticket(), &xd_before);
VerifyNotifications("get_mutable_continuous_state: xa", {}, // None.
SystemBase::xa_ticket(), &xa_before);
context_->get_mutable_continuous_state_vector(); // Return value ignored.
VerifyNotifications("get_mutable_continuous_state_vector: x",
has_continuous_state(), SystemBase::all_state_ticket(),
&x_before);
VerifyNotifications("get_mutable_continuous_state_vector: xc",
has_continuous_state(), SystemBase::xc_ticket(),
&xc_before);
VerifyNotifications("get_mutable_continuous_state_vector: xd", {}, // None.
SystemBase::xd_ticket(), &xd_before);
VerifyNotifications("get_mutable_continuous_state_vector: xa", {}, // None.
SystemBase::xa_ticket(), &xa_before);
const Eigen::Vector2d new_xc1(3.25, 5.5);
context_->SetContinuousState(VectorX<double>(new_xc1));
VerifyContinuousStateValue(new_xc1);
VerifyNotifications("SetContinuousState: x", has_continuous_state(),
SystemBase::all_state_ticket(), &x_before);
VerifyNotifications("SetContinuousState: xc", has_continuous_state(),
SystemBase::xc_ticket(), &xc_before);
VerifyNotifications("SetContinuousState: xd", {}, // None.
SystemBase::xd_ticket(), &xd_before);
VerifyNotifications("SetContinuousState: xa", {}, // None.
SystemBase::xa_ticket(), &xa_before);
// Changing time and continuous state should affect only t, x and xc.
auto t_before = SaveNotifications(SystemBase::time_ticket());
const double new_time = context_->get_time() + 1.;
const Eigen::Vector2d new_xc2(1.25, 1.5);
context_->SetTimeAndContinuousState(new_time, VectorX<double>(new_xc2));
VerifyTimeValue(new_time);
// Make sure state got delivered to the integrators.
VerifyContinuousStateValue(new_xc2);
// Make sure notifications got delivered.
VerifyNotifications("SetTimeAndContinuousState: t",
SystemBase::time_ticket(), &t_before);
VerifyNotifications("SetTimeAndContinuousState: x", has_continuous_state(),
SystemBase::all_state_ticket(), &x_before);
VerifyNotifications("SetTimeAndContinuousState: xc", has_continuous_state(),
SystemBase::xc_ticket(), &xc_before);
VerifyNotifications("SetTimeAndContinuousState: xd", {}, // None.
SystemBase::xd_ticket(), &xd_before);
VerifyNotifications("SetTimeAndContinuousState: xa", {}, // None.
SystemBase::xa_ticket(), &xa_before);
// Changing discrete state should affect only x and xd, and those should only
// get notified for systems that actually have discrete variables.
context_->get_mutable_discrete_state(); // Return value ignored.
VerifyNotifications("get_mutable_discrete_state: x", has_discrete_state(),
SystemBase::all_state_ticket(), &x_before);
VerifyNotifications("get_mutable_discrete_state: xd", has_discrete_state(),
SystemBase::xd_ticket(), &xd_before);
VerifyNotifications("get_mutable_discrete_state: xc", {}, // None.
SystemBase::xc_ticket(), &xc_before);
VerifyNotifications("get_mutable_discrete_state: xa", {}, // None.
SystemBase::xa_ticket(), &xa_before);
context_->get_mutable_discrete_state_vector(); // Return value ignored.
VerifyNotifications("get_mutable_discrete_state_vector: x",
has_discrete_state(),
SystemBase::all_state_ticket(), &x_before);
VerifyNotifications("get_mutable_discrete_state_vector: xd",
has_discrete_state(), SystemBase::xd_ticket(),
&xd_before);
VerifyNotifications("get_mutable_discrete_state_vector: xc", {}, // None.
SystemBase::xc_ticket(), &xc_before);
VerifyNotifications("get_mutable_discrete_state_vector: xa", {}, // None.
SystemBase::xa_ticket(), &xa_before);
context_->get_mutable_discrete_state(0); // Return value ignored.
VerifyNotifications("get_mutable_discrete_state(0): x", has_discrete_state(),
SystemBase::all_state_ticket(), &x_before);
VerifyNotifications("get_mutable_discrete_state(0): xd", has_discrete_state(),
SystemBase::xd_ticket(), &xd_before);
VerifyNotifications("get_mutable_discrete_state(0): xc", {}, // None.
SystemBase::xc_ticket(), &xc_before);
VerifyNotifications("get_mutable_discrete_state(0): xa", {}, // None.
SystemBase::xa_ticket(), &xa_before);
// Changing abstract state should affect only x and xa, and those should only
// get notified for systems that actually have discrete variables.
context_->get_mutable_abstract_state(); // Return value ignored.
VerifyNotifications("get_mutable_abstract_state: x", has_abstract_state(),
SystemBase::all_state_ticket(), &x_before);
VerifyNotifications("get_mutable_abstract_state: xa", has_abstract_state(),
SystemBase::xa_ticket(), &xa_before);
VerifyNotifications("get_mutable_abstract_state: xc", {}, // None.
SystemBase::xc_ticket(), &xc_before);
VerifyNotifications("get_mutable_abstract_state: xd", {}, // None.
SystemBase::xd_ticket(), &xd_before);
context_->get_mutable_abstract_state<int>(0); // Return value ignored.
VerifyNotifications("get_mutable_abstract_state(0): x", has_abstract_state(),
SystemBase::all_state_ticket(), &x_before);
VerifyNotifications("get_mutable_abstract_state(0): xa", has_abstract_state(),
SystemBase::xa_ticket(), &xa_before);
VerifyNotifications("get_mutable_abstract_state(0): xc", {}, // None.
SystemBase::xc_ticket(), &xc_before);
VerifyNotifications("get_mutable_abstract_state(0): xd", {}, // None.
SystemBase::xd_ticket(), &xd_before);
}
TEST_F(DiagramContextTest, MutableParameterNotifications) {
auto p_before =
SaveNotifications(SystemBase::all_parameters_ticket());
auto pn_before = SaveNotifications(SystemBase::pn_ticket());
auto pa_before = SaveNotifications(SystemBase::pa_ticket());
// Changing the whole set of parameters should affect all subcontexts that
// have any parameters.
context_->get_mutable_parameters(); // Return value ignored.
VerifyNotifications("get_mutable_parameters: p", has_parameter(),
SystemBase::all_parameters_ticket(), &p_before);
VerifyNotifications("get_mutable_parameters: pn", has_numeric_parameter(),
SystemBase::pn_ticket(), &pn_before);
VerifyNotifications("get_mutable_parameters: pa", has_abstract_parameter(),
SystemBase::pa_ticket(), &pa_before);
// Changing numeric or abstract should affect only subcontexts with that kind
// of parameter.
context_->get_mutable_numeric_parameter(0); // Return value ignored.
VerifyNotifications("get_mutable_numeric_parameter(0): p",
has_numeric_parameter(),
SystemBase::all_parameters_ticket(), &p_before);
VerifyNotifications("get_mutable_numeric_parameter(0): pn",
has_numeric_parameter(),
SystemBase::pn_ticket(), &pn_before);
VerifyNotifications("get_mutable_numeric_parameter(0): pa", {}, // None.
SystemBase::pa_ticket(), &pa_before);
context_->get_mutable_abstract_parameter(0); // Return value ignored.
VerifyNotifications("get_mutable_abstract_parameter(0): p",
has_abstract_parameter(),
SystemBase::all_parameters_ticket(), &p_before);
VerifyNotifications("get_mutable_abstract_parameter(0): pa",
has_abstract_parameter(),
SystemBase::pa_ticket(), &pa_before);
VerifyNotifications("get_mutable_abstract_parameter(0): pn", {}, // None.
SystemBase::pn_ticket(), &pn_before);
}
// We have a method that copies everything from one context to another. That
// should produce a lot of notifications in the destination context.
TEST_F(DiagramContextTest, MutableEverythingNotifications) {
auto clone = context_->Clone();
ASSERT_TRUE(clone != nullptr);
// Make sure clone's values are different from context's. These numbers are
// arbitrary as long as they don't match the default context_ values.
const double new_time = context_->get_time() + 1.;
const double new_accuracy = 3e-12;
const Eigen::Vector2d new_xc(0.125, 7.5);
const double new_xd = -1.;
const int new_xa = 12345;
const double new_pn = -2;
const int new_pa = 101;
clone->SetTime(new_time);
clone->SetAccuracy(new_accuracy);
clone->SetContinuousState(new_xc);
clone->get_mutable_discrete_state(0)[0] = new_xd;
clone->get_mutable_abstract_state<int>(0) = new_xa;
clone->get_mutable_numeric_parameter(0).SetAtIndex(0, new_pn);
clone->get_mutable_abstract_parameter(0).set_value<int>(new_pa);
auto t_before = SaveNotifications(SystemBase::time_ticket());
auto a_before = SaveNotifications(SystemBase::accuracy_ticket());
auto p_before =
SaveNotifications(SystemBase::all_parameters_ticket());
auto pn_before = SaveNotifications(SystemBase::pn_ticket());
auto pa_before = SaveNotifications(SystemBase::pa_ticket());
auto x_before = SaveNotifications(SystemBase::all_state_ticket());
auto xc_before = SaveNotifications(SystemBase::xc_ticket());
auto xd_before = SaveNotifications(SystemBase::xd_ticket());
auto xa_before = SaveNotifications(SystemBase::xa_ticket());
// This is the method under test.
context_->SetTimeStateAndParametersFrom(*clone);
// First make sure that all the values got passed through.
VerifyTimeValue(new_time);
VerifyAccuracyValue(new_accuracy);
VerifyContinuousStateValue(new_xc);
// Check that non-continuous states and parameter got set in diagram and
// subcontext that has the resource.
EXPECT_EQ(context_->get_discrete_state_vector()[0], new_xd);
EXPECT_EQ(context_->GetSubsystemContext(SubsystemIndex(4)) // discrete state
.get_discrete_state_vector()[0],
new_xd);
EXPECT_EQ(context_->get_abstract_state<int>(0), new_xa);
EXPECT_EQ(context_->GetSubsystemContext(SubsystemIndex(5)) // abstract state
.get_abstract_state<int>(0),
new_xa);
EXPECT_EQ(context_->get_numeric_parameter(0)[0], new_pn);
EXPECT_EQ(context_->GetSubsystemContext(SubsystemIndex(6)) // numeric param.
.get_numeric_parameter(0)[0],
new_pn);
EXPECT_EQ(context_->get_abstract_parameter(0).get_value<int>(), new_pa);
EXPECT_EQ(context_->GetSubsystemContext(SubsystemIndex(7)) // abstract param.
.get_abstract_parameter(0).get_value<int>(),
new_pa);
VerifyNotifications("SetTimeStateAndParametersFrom: t",
SystemBase::time_ticket(), &t_before);
VerifyNotifications("SetTimeStateAndParametersFrom: a",
SystemBase::accuracy_ticket(), &a_before);
VerifyNotifications("SetTimeStateAndParametersFrom: p", has_parameter(),
SystemBase::all_parameters_ticket(),
&p_before);
VerifyNotifications("SetTimeStateAndParametersFrom: pn",
has_numeric_parameter(),
SystemBase::pn_ticket(), &pn_before);
VerifyNotifications("SetTimeStateAndParametersFrom: pa",
has_abstract_parameter(),
SystemBase::pa_ticket(), &pa_before);
VerifyNotifications("SetTimeStateAndParametersFrom: x", has_state(),
SystemBase::all_state_ticket(), &x_before);
VerifyNotifications("SetTimeStateAndParametersFrom: xc",
has_continuous_state(), SystemBase::xc_ticket(),
&xc_before);
VerifyNotifications("SetTimeStateAndParametersFrom: xd", has_discrete_state(),
SystemBase::xd_ticket(), &xd_before);
VerifyNotifications("SetTimeStateAndParametersFrom: xa", has_abstract_state(),
SystemBase::xa_ticket(), &xa_before);
}
// Tests that state variables appear in the diagram context, and write
// transparently through to the constituent system contexts.
TEST_F(DiagramContextTest, State) {
// Each integrator has a single continuous state variable.
ContinuousState<double>& xc = context_->get_mutable_continuous_state();
EXPECT_EQ(2, xc.size());
EXPECT_EQ(0, xc.get_generalized_position().size());
EXPECT_EQ(0, xc.get_generalized_velocity().size());
EXPECT_EQ(2, xc.get_misc_continuous_state().size());
// The discrete state vector has length 1.
DiscreteValues<double>& xd = context_->get_mutable_discrete_state();
EXPECT_EQ(1, xd.num_groups());
EXPECT_EQ(1, xd.get_vector(0).size());
// Changes to the diagram state write through to constituent system states.
// - Continuous
ContinuousState<double>& integrator0_xc =
context_->GetMutableSubsystemContext(SubsystemIndex(2))
.get_mutable_continuous_state();
ContinuousState<double>& integrator1_xc =
context_->GetMutableSubsystemContext(SubsystemIndex(3))
.get_mutable_continuous_state();
EXPECT_EQ(42.0, integrator0_xc.get_vector()[0]);
EXPECT_EQ(43.0, integrator1_xc.get_vector()[0]);
// - Discrete
DiscreteValues<double>& discrete_xd =
context_->GetMutableSubsystemContext(SubsystemIndex(4))
.get_mutable_discrete_state();
EXPECT_EQ(44.0, discrete_xd.get_vector(0)[0]);
// Changes to constituent system states appear in the diagram state.
// - Continuous
integrator1_xc.get_mutable_vector()[0] = 1000.0;
EXPECT_EQ(1000.0, xc.get_vector()[1]);
// - Discrete
discrete_xd.get_mutable_vector(0)[0] = 1001.0;
EXPECT_EQ(1001.0, xd.get_vector(0)[0]);
}
// Tests that the pointers to substates in the DiagramState are equal to the
// substates in the subsystem contexts.
TEST_F(DiagramContextTest, DiagramState) {
auto diagram_state = dynamic_cast<DiagramState<double>*>(
&context_->get_mutable_state());
ASSERT_NE(nullptr, diagram_state);
for (SubsystemIndex i(0); i < kNumSystems; ++i) {
EXPECT_EQ(&context_->GetMutableSubsystemContext(i).get_mutable_state(),
&diagram_state->get_mutable_substate(i));
}
}
// Tests that no exception is thrown when connecting a valid source
// and destination port.
TEST_F(DiagramContextTest, ConnectValid) {
DRAKE_EXPECT_NO_THROW(context_->SubscribeInputPortToOutputPort(
{SubsystemIndex(0) /* adder0_ */, OutputPortIndex(0)},
{SubsystemIndex(1) /* adder1_ */, InputPortIndex(1)}));
}
// Tests that input ports can be assigned to the DiagramContext and then
// retrieved.
TEST_F(DiagramContextTest, SetAndGetInputPorts) {
ASSERT_EQ(2, context_->num_input_ports());
AttachInputPorts();
EXPECT_EQ(128, ReadVectorInputPort(*context_, 0)->get_value()[0]);
EXPECT_EQ(256, ReadVectorInputPort(*context_, 1)->get_value()[0]);
}
TEST_F(DiagramContextTest, ToString) {
const std::string str = context_->to_string();
EXPECT_THAT(str, ::testing::HasSubstr("integrator0"));
EXPECT_THAT(str, ::testing::HasSubstr("integrator1"));
EXPECT_THAT(str, ::testing::HasSubstr("discrete_state_system"));
EXPECT_THAT(str, ::testing::HasSubstr("abstract_state_system"));
EXPECT_THAT(str, ::testing::HasSubstr("system_with_numeric_parameters"));
EXPECT_THAT(str, ::testing::HasSubstr("system_with_abstract_parameters"));
// Adders named adder0 and adder1 are part of the diagram, but don't have
// any context that is useful to print, so are excluded.
EXPECT_THAT(str, ::testing::Not(::testing::HasSubstr("adder0")));
EXPECT_THAT(str, ::testing::Not(::testing::HasSubstr("adder1")));
}
// Test that start_next_change_event() returns a sequentially increasing
// number regardless of from where in the DiagramContext tree the request
// is initiated. Also, it should continue counting up after cloning.
TEST_F(DiagramContextTest, NextChangeEventNumber) {
const int64_t first = context_->start_new_change_event();
EXPECT_EQ(context_->start_new_change_event(), first + 1);
// Verify that this also works on a const Context.
EXPECT_EQ(const_cast<const DiagramContext<double>*>(context_.get())
->start_new_change_event(),
first + 2);
// Obtain a subcontext and verify we still count up.
Context<double>& discrete_context =
context_->GetMutableSubsystemContext(SubsystemIndex(4));
EXPECT_EQ(discrete_context.start_new_change_event(), first + 3);
// Now clone the context and make sure we're still counting up.
auto clone = dynamic_pointer_cast<DiagramContext<double>>(context_->Clone());
EXPECT_EQ(clone->start_new_change_event(), first + 4);
EXPECT_EQ(context_->start_new_change_event(), first + 4); // Sanity check.
Context<double>& discrete_clone =
clone->GetMutableSubsystemContext(SubsystemIndex(4));
EXPECT_EQ(discrete_clone.start_new_change_event(), first + 5);
}
TEST_F(DiagramContextTest, Clone) {
context_->SubscribeInputPortToOutputPort(
{SubsystemIndex(0) /* adder0_ */, OutputPortIndex(0)},
{SubsystemIndex(1) /* adder1_ */, InputPortIndex(1)});
AttachInputPorts();
auto clone = dynamic_pointer_cast<DiagramContext<double>>(context_->Clone());
ASSERT_TRUE(clone != nullptr);
// Verify that the time was copied.
EXPECT_EQ(kTime, clone->get_time());
// Verify that the system id was copied.
EXPECT_TRUE(clone->get_system_id().is_valid());
EXPECT_EQ(clone->get_system_id(), context_->get_system_id());
const ContinuousState<double>& xc = clone->get_continuous_state();
EXPECT_TRUE(xc.get_system_id().is_valid());
EXPECT_EQ(xc.get_system_id(), context_->get_system_id());
const DiscreteValues<double>& xd = clone->get_discrete_state();
EXPECT_TRUE(xd.get_system_id().is_valid());
EXPECT_EQ(xd.get_system_id(), context_->get_system_id());
// Verify that the state has the same value.
VerifyClonedState(clone->get_state());
// Verify that the parameters have the same value.
VerifyClonedParameters(clone->get_parameters());
// Verify that changes to the state do not write through to the original
// context.
clone->get_mutable_continuous_state_vector()[0] = 1024.0;
EXPECT_EQ(1024.0, clone->get_continuous_state()[0]);
EXPECT_EQ(42.0, context_->get_continuous_state()[0]);
// Verify that the cloned input ports contain the same data,
// but are different pointers.
EXPECT_EQ(2, clone->num_input_ports());
for (int i = 0; i < 2; ++i) {
const BasicVector<double>* orig_port = ReadVectorInputPort(*context_, i);
const BasicVector<double>* clone_port = ReadVectorInputPort(*clone, i);
EXPECT_NE(orig_port, clone_port);
EXPECT_TRUE(CompareMatrices(orig_port->get_value(), clone_port->get_value(),
1e-8, MatrixCompareType::absolute));
}
}
TEST_F(DiagramContextTest, CloneState) {
std::unique_ptr<State<double>> state = context_->CloneState();
// Verify that the state was copied.
VerifyClonedState(*state);
// Verify that the underlying type was preserved.
EXPECT_NE(nullptr, dynamic_cast<DiagramState<double>*>(state.get()));
// Verify that the system id was copied.
EXPECT_TRUE(state->get_system_id().is_valid());
EXPECT_EQ(state->get_system_id(), context_->get_system_id());
ContinuousState<double>& xc = state->get_mutable_continuous_state();
EXPECT_TRUE(xc.get_system_id().is_valid());
EXPECT_EQ(xc.get_system_id(), context_->get_system_id());
const DiscreteValues<double>& xd = state->get_discrete_state();
EXPECT_TRUE(xd.get_system_id().is_valid());
EXPECT_EQ(xd.get_system_id(), context_->get_system_id());
// Verify that changes to the state do not write through to the original
// context.
xc[1] = 1024.0;
EXPECT_EQ(1024.0, state->get_continuous_state()[1]);
EXPECT_EQ(43.0, context_->get_continuous_state()[1]);
}
// Verifies that accuracy is set properly during cloning.
TEST_F(DiagramContextTest, CloneAccuracy) {
// Verify accuracy is not set by default.
EXPECT_FALSE(context_->get_accuracy());
// Verify that setting the accuracy is reflected in cloning.
const double unity = 1.0;
context_->SetAccuracy(unity);
std::unique_ptr<Context<double>> clone = context_->Clone();
EXPECT_EQ(clone->get_accuracy().value(), unity);
}
TEST_F(DiagramContextTest, SubcontextCloneIsError) {
const auto& subcontext = context_->GetSubsystemContext(SubsystemIndex{0});
DRAKE_EXPECT_THROWS_MESSAGE(
subcontext.Clone(),
"Context::Clone..: Cannot clone a non-root Context; "
"this Context was created by 'adder0'.");
}
TEST_F(DiagramContextTest, SubcontextSetTimeStateAndParametersFromIsError) {
auto clone = dynamic_pointer_cast<DiagramContext<double>>(context_->Clone());
ASSERT_TRUE(clone != nullptr);
const auto& source_subcontext =
context_->GetSubsystemContext(SubsystemIndex{0});
auto& dest_subcontext = clone->GetMutableSubsystemContext(SubsystemIndex{0});
DRAKE_EXPECT_THROWS_MESSAGE(
dest_subcontext.SetTimeStateAndParametersFrom(source_subcontext),
"SetTimeStateAndParametersFrom\\(\\): Time change allowed only in the "
"root Context.");
}
TEST_F(DiagramContextTest, SubcontextSetStateAndParametersFrom) {
auto clone = dynamic_pointer_cast<DiagramContext<double>>(context_->Clone());
ASSERT_TRUE(clone != nullptr);
// Set arbitrary time, accuracy, state and parameters to the cloned
// context so that they are different from the original context.
const double new_time = context_->get_time() + 1.;
const double new_accuracy = 3e-12;
const Eigen::Vector2d new_xc(0.125, 7.5);
const double new_xd = -1.;
const int new_xa = 12345;
const double new_pn = -2;
const int new_pa = 101;
clone->SetTime(new_time);
clone->SetAccuracy(new_accuracy);
clone->SetContinuousState(new_xc);
clone->get_mutable_discrete_state(0)[0] = new_xd;
clone->get_mutable_abstract_state<int>(0) = new_xa;
clone->get_mutable_numeric_parameter(0).SetAtIndex(0, new_pn);
clone->get_mutable_abstract_parameter(0).set_value<int>(new_pa);
// Call the method under test for the subcontexts of context_.
for (int i = 0; i < kNumSystems; ++i) {
const auto& source_subcontext =
context_->GetSubsystemContext(SubsystemIndex{i});
auto& dest_subcontext =
clone->GetMutableSubsystemContext(SubsystemIndex{i});
dest_subcontext.SetStateAndParametersFrom(source_subcontext);
}
// The state and the parameters should have been set to be the same
// as the source context.
VerifyClonedParameters(clone->get_parameters());
VerifyClonedState(clone->get_state());
// Verify time and accuracy did not change for this context and its
// subcontexts.
EXPECT_EQ(clone->get_time(), new_time);
EXPECT_EQ(clone->get_accuracy(), new_accuracy);
for (SubsystemIndex i(0); i < kNumSystems; ++i) {
const auto& subcontext = clone->GetSubsystemContext(i);
EXPECT_EQ(subcontext.get_time(), new_time);
EXPECT_EQ(subcontext.get_accuracy(), new_accuracy);
}
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/value_checker_test.cc | #include "drake/systems/framework/value_checker.h"
#include <memory>
#include <stdexcept>
#include <gtest/gtest.h>
#include "drake/common/drake_copyable.h"
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/systems/framework/basic_vector.h"
using std::make_unique;
namespace drake {
namespace systems {
namespace {
// This is what DoClone should look like.
class GoodVector : public BasicVector<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(GoodVector)
GoodVector() : BasicVector<double>(2) {}
[[nodiscard]] GoodVector* DoClone() const override {
return new GoodVector;
}
};
// This one forgot the DoClone override entirely.
class MissingCloneVector : public BasicVector<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MissingCloneVector)
MissingCloneVector() : BasicVector<double>(2) {}
};
// This one forgot to override DoClone again in a subclass; relying on the
// superclass implementation is not good enough.
class NotSoGoodVector : public GoodVector {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(NotSoGoodVector)
NotSoGoodVector() {}
};
// This one remembers to DoClone in the subclass, but does it wrong.
class NotQuiteGoodVector : public GoodVector {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(NotQuiteGoodVector)
NotQuiteGoodVector() {}
[[nodiscard]] GoodVector* DoClone() const override {
return new GoodVector;
}
};
// A convenience wrapper for the "device under test".
void CheckVector(const BasicVector<double>* basic_vector) {
drake::systems::internal::CheckBasicVectorInvariants(basic_vector);
}
GTEST_TEST(ValueCheckerTest, CheckBasicVectorInvariantsTest) {
const BasicVector<double> basic(2);
const GoodVector good;
const MissingCloneVector missing_clone;
const NotSoGoodVector not_so_good;
const NotQuiteGoodVector not_quite_good;
DRAKE_EXPECT_NO_THROW(CheckVector(&basic));
DRAKE_EXPECT_NO_THROW(CheckVector(&good));
EXPECT_THROW(CheckVector(nullptr), std::exception);
EXPECT_THROW(CheckVector(&missing_clone), std::exception);
EXPECT_THROW(CheckVector(¬_so_good), std::exception);
EXPECT_THROW(CheckVector(¬_quite_good), std::exception);
}
// A convenience wrapper for the "device under test".
void CheckValue(const AbstractValue* abstract_value) {
drake::systems::internal::CheckVectorValueInvariants<double>(abstract_value);
}
GTEST_TEST(ValueCheckerTest, CheckVectorValueInvariantsTest) {
using VectorValue = Value<BasicVector<double>>;
const VectorValue basic(BasicVector<double>::Make({1, 2}));
const VectorValue good(make_unique<GoodVector>());
const VectorValue missing_clone(make_unique<MissingCloneVector>());
const VectorValue not_so_good(make_unique<NotSoGoodVector>());
const VectorValue not_quite_good(make_unique<NotQuiteGoodVector>());
DRAKE_EXPECT_NO_THROW(CheckValue(&basic));
DRAKE_EXPECT_NO_THROW(CheckValue(&good));
EXPECT_THROW(CheckValue(nullptr), std::exception);
EXPECT_THROW(CheckValue(&missing_clone), std::exception);
EXPECT_THROW(CheckValue(¬_so_good), std::exception);
EXPECT_THROW(CheckValue(¬_quite_good), std::exception);
// Other unrelated Values are ignored.
const Value<int> int_value(2);
DRAKE_EXPECT_NO_THROW(CheckValue(&int_value));
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/diagram_test.cc | #include "drake/systems/framework/diagram.h"
#include <Eigen/Dense>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "drake/common/eigen_types.h"
#include "drake/common/random.h"
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/examples/pendulum/pendulum_plant.h"
#include "drake/systems/analysis/test_utilities/stateless_system.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/framework/fixed_input_port_value.h"
#include "drake/systems/framework/leaf_system.h"
#include "drake/systems/framework/output_port.h"
#include "drake/systems/framework/test_utilities/initialization_test_system.h"
#include "drake/systems/framework/test_utilities/pack_value.h"
#include "drake/systems/framework/test_utilities/scalar_conversion.h"
#include "drake/systems/primitives/adder.h"
#include "drake/systems/primitives/constant_value_source.h"
#include "drake/systems/primitives/constant_vector_source.h"
#include "drake/systems/primitives/gain.h"
#include "drake/systems/primitives/integrator.h"
#include "drake/systems/primitives/zero_order_hold.h"
using Eigen::Vector2d;
using Eigen::Vector3d;
using Eigen::Vector4d;
using Eigen::VectorXd;
using drake::systems::analysis_test::StatelessSystem;
using testing::ElementsAreArray;
namespace drake {
namespace systems {
namespace {
class DoubleOnlySystem : public LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DoubleOnlySystem);
DoubleOnlySystem() = default;
};
/// A stateless system that can set an arbitrary periodic discrete update.
template <class T>
class EmptySystem : public LeafSystem<T> {
public:
~EmptySystem() override {}
// Adds an arbitrary periodic discrete update.
void AddPeriodicDiscreteUpdate() {
const double default_period = 1.125;
const double default_offset = 2.25;
this->DeclarePeriodicDiscreteUpdateEvent(default_period, default_offset,
&EmptySystem::Noop);
}
// Adds a specific periodic discrete update.
void AddPeriodicDiscreteUpdate(double period, double offset) {
this->DeclarePeriodicDiscreteUpdateEvent(period, offset,
&EmptySystem::Noop);
}
EventStatus Noop(const Context<T>&, DiscreteValues<T>*) const {
return EventStatus::DidNothing();
}
};
/// A recursive diagram of purely empty systems used for testing that diagram
/// mechanics are working for periodic discrete update events.
class EmptySystemDiagram : public Diagram<double> {
public:
// Enum for how many periodic discrete updates are performed at each level
// of the diagram.
enum UpdateType {
kTwoUpdatesPerLevel,
kOneUpdatePerLevelSys1,
kOneUpdatePerLevelSys2,
kOneUpdateAtLastLevelSys1,
kOneUpdateAtLastLevelSys2,
kTwoUpdatesAtLastLevel,
};
// Creates a diagram of "empty" systems with the specified recursion depth.
// A recursion depth of zero will create two empty systems only; Otherwise,
// 2*`recursion_depth` empty systems will be created.
EmptySystemDiagram(UpdateType num_periodic_discrete_updates,
int recursion_depth,
bool unique_updates) {
DRAKE_DEMAND(recursion_depth >= 0);
DiagramBuilder<double> builder;
// Add in two empty systems.
auto sys1 = builder.AddSystem<EmptySystem<double>>();
auto sys2 = builder.AddSystem<EmptySystem<double>>();
switch (num_periodic_discrete_updates) {
case kTwoUpdatesPerLevel:
if (unique_updates) {
sys1->AddPeriodicDiscreteUpdate();
sys2->AddPeriodicDiscreteUpdate();
} else {
sys1->AddPeriodicDiscreteUpdate(recursion_depth + 1,
recursion_depth * 3);
sys2->AddPeriodicDiscreteUpdate(recursion_depth + 3,
recursion_depth * 5);
}
break;
case kOneUpdatePerLevelSys1:
if (unique_updates) {
sys1->AddPeriodicDiscreteUpdate();
} else {
sys1->AddPeriodicDiscreteUpdate(recursion_depth * 7, recursion_depth);
}
break;
case kOneUpdatePerLevelSys2:
if (unique_updates) {
sys2->AddPeriodicDiscreteUpdate();
} else {
sys2->AddPeriodicDiscreteUpdate(recursion_depth,
recursion_depth * 11);
}
break;
case kOneUpdateAtLastLevelSys1:
if (recursion_depth == 0) {
if (unique_updates) {
sys1->AddPeriodicDiscreteUpdate();
} else {
sys1->AddPeriodicDiscreteUpdate(13, 17);
}
}
break;
case kOneUpdateAtLastLevelSys2:
if (recursion_depth == 0) {
if (unique_updates) {
sys2->AddPeriodicDiscreteUpdate();
} else {
sys2->AddPeriodicDiscreteUpdate(19, 23);
}
}
break;
case kTwoUpdatesAtLastLevel:
if (recursion_depth == 0) {
if (unique_updates) {
sys1->AddPeriodicDiscreteUpdate();
sys2->AddPeriodicDiscreteUpdate();
} else {
sys1->AddPeriodicDiscreteUpdate(29, 31);
sys2->AddPeriodicDiscreteUpdate(37, 43);
}
}
break;
}
// Now add a sub-StatelessDiagram with one less recursion depth (if the
// recursion depth is not zero).
if (recursion_depth > 0) {
builder.AddSystem<EmptySystemDiagram>(
num_periodic_discrete_updates,
recursion_depth - 1,
unique_updates);
}
builder.BuildInto(this);
EXPECT_FALSE(IsDifferenceEquationSystem());
// There are periodic updates, but no discrete state.
EXPECT_TRUE(IsDifferentialEquationSystem());
}
};
void CheckPeriodAndOffset(const PeriodicEventData& data) {
EXPECT_EQ(data.period_sec(), 1.125);
EXPECT_EQ(data.offset_sec(), 2.25);
}
// Tests whether the diagram exhibits the correct behavior for
// GetUniquePeriodicDiscreteUpdateAttribute().
GTEST_TEST(EmptySystemDiagramTest, CheckPeriodicTriggerDiscreteUpdateUnique) {
// Check diagrams with no recursion.
std::optional<PeriodicEventData> periodic_data;
EmptySystemDiagram d_sys2upd_zero(
EmptySystemDiagram::kOneUpdatePerLevelSys1, 0, true);
EmptySystemDiagram d_sys1upd_zero(
EmptySystemDiagram::kOneUpdatePerLevelSys2, 0, true);
EmptySystemDiagram d_bothupd_zero(EmptySystemDiagram::kTwoUpdatesPerLevel, 0,
true);
ASSERT_TRUE(periodic_data =
d_sys2upd_zero.GetUniquePeriodicDiscreteUpdateAttribute());
CheckPeriodAndOffset(periodic_data.value());
ASSERT_TRUE(periodic_data =
d_sys1upd_zero.GetUniquePeriodicDiscreteUpdateAttribute());
CheckPeriodAndOffset(periodic_data.value());
ASSERT_TRUE(periodic_data =
d_bothupd_zero.GetUniquePeriodicDiscreteUpdateAttribute());
CheckPeriodAndOffset(periodic_data.value());
// Check systems with up to three levels of recursion.
for (int i = 1; i <= 3; ++i) {
// Create the systems.
EmptySystemDiagram d_sys1upd(
EmptySystemDiagram::kOneUpdatePerLevelSys1, i, true);
EmptySystemDiagram d_sys2upd(
EmptySystemDiagram::kOneUpdatePerLevelSys2, i, true);
EmptySystemDiagram d_bothupd(
EmptySystemDiagram::kTwoUpdatesPerLevel, i, true);
EmptySystemDiagram d_sys1_last(
EmptySystemDiagram::kOneUpdateAtLastLevelSys1, i, true);
EmptySystemDiagram d_sys2_last(
EmptySystemDiagram::kOneUpdateAtLastLevelSys2, i, true);
EmptySystemDiagram d_both_last(
EmptySystemDiagram::kTwoUpdatesAtLastLevel, i, true);
// All of these should return "true". Check them.
ASSERT_TRUE(periodic_data =
d_sys1upd.GetUniquePeriodicDiscreteUpdateAttribute());
CheckPeriodAndOffset(periodic_data.value());
ASSERT_TRUE(periodic_data =
d_sys2upd.GetUniquePeriodicDiscreteUpdateAttribute());
CheckPeriodAndOffset(periodic_data.value());
ASSERT_TRUE(periodic_data =
d_bothupd.GetUniquePeriodicDiscreteUpdateAttribute());
CheckPeriodAndOffset(periodic_data.value());
ASSERT_TRUE(periodic_data =
d_both_last.GetUniquePeriodicDiscreteUpdateAttribute());
CheckPeriodAndOffset(periodic_data.value());
ASSERT_TRUE(periodic_data =
d_sys1_last.GetUniquePeriodicDiscreteUpdateAttribute());
CheckPeriodAndOffset(periodic_data.value());
ASSERT_TRUE(periodic_data =
d_sys2_last.GetUniquePeriodicDiscreteUpdateAttribute());
CheckPeriodAndOffset(periodic_data.value());
}
}
// Tests whether the diagram exhibits the correct behavior for
// GetUniquePeriodicDiscreteUpdateAttribute() with non-unique updates
GTEST_TEST(EmptySystemDiagramTest, CheckPeriodicTriggerDiscreteUpdate) {
// Check diagrams with no recursion.
PeriodicEventData periodic_data;
EmptySystemDiagram d_sys2upd_zero(
EmptySystemDiagram::kOneUpdatePerLevelSys1, 0, false);
EmptySystemDiagram d_sys1upd_zero(
EmptySystemDiagram::kOneUpdatePerLevelSys2, 0, false);
EmptySystemDiagram d_bothupd_zero(EmptySystemDiagram::kTwoUpdatesPerLevel, 0,
false);
EXPECT_TRUE(d_sys2upd_zero.GetUniquePeriodicDiscreteUpdateAttribute());
EXPECT_TRUE(d_sys1upd_zero.GetUniquePeriodicDiscreteUpdateAttribute());
EXPECT_FALSE(d_bothupd_zero.GetUniquePeriodicDiscreteUpdateAttribute());
// Check systems with up to three levels of recursion.
for (int i = 1; i <= 3; ++i) {
// Create the systems.
EmptySystemDiagram d_sys1upd(
EmptySystemDiagram::kOneUpdatePerLevelSys1, i, false);
EmptySystemDiagram d_sys2upd(
EmptySystemDiagram::kOneUpdatePerLevelSys2, i, false);
EmptySystemDiagram d_bothupd(
EmptySystemDiagram::kTwoUpdatesPerLevel, i, false);
EmptySystemDiagram d_sys1_last(
EmptySystemDiagram::kOneUpdateAtLastLevelSys1, i, false);
EmptySystemDiagram d_sys2_last(
EmptySystemDiagram::kOneUpdateAtLastLevelSys2, i, false);
EmptySystemDiagram d_both_last(
EmptySystemDiagram::kTwoUpdatesAtLastLevel, i, false);
// None of these should have a unique periodic event.
EXPECT_FALSE(d_sys1upd.GetUniquePeriodicDiscreteUpdateAttribute());
EXPECT_EQ(d_sys1upd.MapPeriodicEventsByTiming().size(), i + 1);
EXPECT_FALSE(d_sys2upd.GetUniquePeriodicDiscreteUpdateAttribute());
EXPECT_EQ(d_sys2upd.MapPeriodicEventsByTiming().size(), i + 1);
EXPECT_FALSE(d_bothupd.GetUniquePeriodicDiscreteUpdateAttribute());
EXPECT_EQ(d_bothupd.MapPeriodicEventsByTiming().size(), 2 * (i + 1));
EXPECT_FALSE(d_both_last.GetUniquePeriodicDiscreteUpdateAttribute());
EXPECT_EQ(d_both_last.MapPeriodicEventsByTiming().size(), 2);
// All of these should have a unique periodic event.
EXPECT_TRUE(d_sys1_last.GetUniquePeriodicDiscreteUpdateAttribute());
EXPECT_EQ(d_sys1_last.MapPeriodicEventsByTiming().size(), 1);
EXPECT_TRUE(d_sys2_last.GetUniquePeriodicDiscreteUpdateAttribute());
EXPECT_EQ(d_sys2_last.MapPeriodicEventsByTiming().size(), 1);
}
}
/* This Diagram contains a sub-Diagram with one of its input ports unconnected.
This is a specialized test to cover a case that was otherwise missed -- a
Diagram has an input port that is neither exported nor fixed.
+--------------------------+
| |
| +------------------+ |
| | | |
| | +-----------+ | |
----------> u0 | | |
| | | | | |
| | | Adder1 | | |
| | | +----------> y0
| | | | | |
| X----> u1 | | |
| | +-----------+ | | X = forgot to export
| | | |
| +------------------+ |
| InsideBadDiagram |
| |
+--------------------------+
BadDiagram
*/
class InsideBadDiagram : public Diagram<double> {
public:
InsideBadDiagram() {
const int kSize = 1;
DiagramBuilder<double> builder;
adder0_ = builder.AddSystem<Adder<double>>(2 /* inputs */, kSize);
adder0_->set_name("adder0");
builder.ExportInput(adder0().get_input_port(0));
builder.ExportInput(adder0().get_input_port(1));
builder.ExportOutput(adder0().get_output_port());
builder.BuildInto(this);
}
const Adder<double>& adder0() { return *adder0_; }
private:
Adder<double>* adder0_{};
};
class BadDiagram : public Diagram<double> {
public:
BadDiagram() {
DiagramBuilder<double> builder;
inside_ = builder.AddSystem<InsideBadDiagram>();
inside_->set_name("inside");
builder.ExportInput(inside().get_input_port(0));
// Oops -- "forgot" to export this.
// builder.ExportInput(inside().get_input_port(1));
builder.ExportOutput(inside().get_output_port(0));
builder.BuildInto(this);
}
const InsideBadDiagram& inside() { return *inside_; }
private:
InsideBadDiagram* inside_{};
};
GTEST_TEST(BadDiagramTest, UnconnectedInsideInputPort) {
BadDiagram diagram;
auto context = diagram.AllocateContext();
diagram.get_input_port(0).FixValue(context.get(), 1.0);
const Context<double>& inside_context =
diagram.GetSubsystemContext(diagram.inside(), *context);
// This should get the value we just fixed above.
EXPECT_EQ(diagram.inside().get_input_port(0).Eval(inside_context)[0], 1);
// This is neither exported, connected, nor fixed so shouldn't have a value.
EXPECT_FALSE(diagram.inside().get_input_port(1).HasValue(inside_context));
}
/* This System declares at least one of every kind of state and parameter
so we can check if the SystemBase "declared sizes" counts work correctly.
(FYI this has nothing to do with dishwashing -- think "everything but the
kitchen sink"!) */
template <typename T>
class KitchenSinkStateAndParameters final : public LeafSystem<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(KitchenSinkStateAndParameters)
KitchenSinkStateAndParameters() :
LeafSystem<T>(systems::SystemTypeTag<KitchenSinkStateAndParameters>{}) {
this->DeclareContinuousState(4, 3, 5); // nq, nv, nz
for (int i = 0; i < 2; ++i) // Make two "groups" of discrete variables.
this->DeclareDiscreteState(4 + i);
for (int i = 0; i < 10; ++i) // Ten abstract state variables.
this->DeclareAbstractState(Value<int>(3 + i));
for (int i = 0; i < 3; ++i) // Three "groups" of numeric parameters.
this->DeclareNumericParameter(BasicVector<T>(1 + i));
for (int i = 0; i < 7; ++i) // Seven abstract parameters.
this->DeclareAbstractParameter(Value<int>(29 + i));
}
// Scalar-converting copy constructor. See @ref system_scalar_conversion.
template <typename U>
explicit KitchenSinkStateAndParameters(
const KitchenSinkStateAndParameters<U>&)
: KitchenSinkStateAndParameters<T>() {}
private:
// Must provide derivatives since we have continuous states.
void DoCalcTimeDerivatives(
const Context<T>& context,
ContinuousState<T>* derivatives) const override {
// xdot = 0.
derivatives->SetFromVector(
VectorX<T>::Zero(this->num_continuous_states()));
}
};
GTEST_TEST(KitchenSinkStateAndParametersTest, LeafSystemCounts) {
KitchenSinkStateAndParameters<double> kitchen_sink;
EXPECT_EQ(kitchen_sink.num_continuous_states(), 12);
EXPECT_EQ(kitchen_sink.num_discrete_state_groups(), 2);
EXPECT_EQ(kitchen_sink.num_abstract_states(), 10);
EXPECT_EQ(kitchen_sink.num_numeric_parameter_groups(), 3);
EXPECT_EQ(kitchen_sink.num_abstract_parameters(), 7);
}
// Helper class that has one input port, and no output ports.
template <typename T>
class Sink final : public LeafSystem<T> {
public:
explicit Sink(int size) : LeafSystem<T>(SystemTypeTag<Sink>{}) {
this->DeclareInputPort("in", kVectorValued, size);
}
// Scalar-converting copy constructor. See @ref system_scalar_conversion.
template <typename U>
explicit Sink(const Sink<U>& other): Sink<T>(other.get_input_port().size()) {}
};
/* ExampleDiagram has the following structure:
adder0_: (input0_ + input1_) -> A
adder1_: (A + input2_) -> B, output 0
adder2_: (A + B) -> output 1
integrator1_: A -> C
integrator2_: C -> output 2
sink_ : (input2_)
It also uses a StatelessSystem to verify Diagram's ability to retrieve
witness functions from its subsystems.
+----------------------------------------------------------+
| |
| +--------+ +------------------------->
1, 2, 4 +------> | | B | y0
u0 | | Adder0 | A +-----------+ | |
| | +-+--> u0 | | |
8, 16, 32+------> | | | | | |
u1 | +--------+ | | Adder1 | B | +-----------+ |
| | | +------+-------> u1 | |
64, 128, 256 | | | | 73,146,292 | | |
+----------+---------> u1 | | Adder2 | |
u2 | | | +-----------+ | +----->
| | | A | | | y1
| | +-----------------------------> u0 | |
| | | 9, 18, 36 +-----------+ | 82
| | | | 164
| | | | 328
| | | |
| | | +------------+ +-----------+ |
| | | | | | | |
| | A | | | C | | |
| | +--> Integ0 +-------------> Integ1 +----->
| | | | | | | y2
| | | 3, 9, 27 | |81,243,729 | |
| | +------------+ +-----------+ |
| | |
| | +------+ |
| | | | |
| +---------> Sink | |
| | | |
| +------+ |
| |
| +-----------+ +----------------+ +----------------+ |
| | | | ConstantVector | | | |
| | Stateless | | or | | KitchenSink | |
| | | | DoubleOnly | | | |
| +-----------+ +----------------+ +----------------+ |
| |
+----------------------------------------------------------|
*/
class ExampleDiagram : public Diagram<double> {
public:
explicit ExampleDiagram(
int size, bool use_abstract = false, bool use_double_only = false) {
DiagramBuilder<double> builder;
adder0_ = builder.AddSystem<Adder<double>>(2 /* inputs */, size);
adder0_->set_name("adder0");
adder1_ = builder.AddSystem<Adder<double>>(2 /* inputs */, size);
adder1_->set_name("adder1");
adder2_ = builder.AddSystem<Adder<double>>(2 /* inputs */, size);
adder2_->set_name("adder2");
stateless_ = builder.AddSystem<StatelessSystem<double>>(
1.0 /* trigger time */,
WitnessFunctionDirection::kCrossesZero);
stateless_->set_name("stateless");
integrator0_ = builder.AddSystem<Integrator<double>>(size);
integrator0_->set_name("integrator0");
integrator1_ = builder.AddSystem<Integrator<double>>(size);
integrator1_->set_name("integrator1");
sink_ = builder.AddSystem<Sink>(size);
sink_->set_name("sink");
builder.Connect(adder0_->get_output_port(), adder1_->get_input_port(0));
builder.Connect(adder0_->get_output_port(), adder2_->get_input_port(0));
builder.Connect(adder1_->get_output_port(), adder2_->get_input_port(1));
builder.Connect(adder0_->get_output_port(),
integrator0_->get_input_port());
builder.Connect(integrator0_->get_output_port(),
integrator1_->get_input_port());
builder.ExportInput(adder0_->get_input_port(0));
builder.ExportInput(adder0_->get_input_port(1), "adder0");
const auto port_index = builder.ExportInput(adder1_->get_input_port(1));
builder.ConnectInput(port_index, sink_->get_input_port());
builder.ExportOutput(adder1_->get_output_port());
builder.ExportOutput(adder2_->get_output_port(), "adder2");
builder.ExportOutput(integrator1_->get_output_port());
if (use_abstract) {
builder.AddSystem<ConstantValueSource<double>>(Value<int>(0));
}
if (use_double_only) {
builder.AddSystem<DoubleOnlySystem>();
}
kitchen_sink_ = builder.AddSystem<KitchenSinkStateAndParameters<double>>();
kitchen_sink_->set_name("kitchen_sink");
builder.BuildInto(this);
}
Adder<double>* adder0() { return adder0_; }
Adder<double>* adder1() { return adder1_; }
Adder<double>* adder2() { return adder2_; }
Integrator<double>* integrator0() { return integrator0_; }
Integrator<double>* integrator1() { return integrator1_; }
Sink<double>* sink() { return sink_; }
StatelessSystem<double>* stateless() { return stateless_; }
KitchenSinkStateAndParameters<double>* kitchen_sink() {
return kitchen_sink_;
}
private:
Adder<double>* adder0_ = nullptr;
Adder<double>* adder1_ = nullptr;
Adder<double>* adder2_ = nullptr;
StatelessSystem<double>* stateless_ = nullptr;
Integrator<double>* integrator0_ = nullptr;
Integrator<double>* integrator1_ = nullptr;
Sink<double>* sink_ = nullptr;
KitchenSinkStateAndParameters<double>* kitchen_sink_ = nullptr;
};
class DiagramTest : public ::testing::Test {
protected:
void SetUp() override {
diagram_ = std::make_unique<ExampleDiagram>(kSize);
diagram_->set_name("Unicode Snowman's Favorite Diagram!!1!☃!");
context_ = diagram_->CreateDefaultContext();
output_ = diagram_->AllocateOutput();
// Make sure caching is on locally, even if it is off by default.
// Do not remove this line; we want to show that these tests function
// correctly with caching on. It is easier to pass with caching off!
context_->EnableCaching();
// Initialize the integrator states.
auto& integrator0_xc = GetMutableContinuousState(integrator0());
integrator0_xc.get_mutable_vector()[0] = 3;
integrator0_xc.get_mutable_vector()[1] = 9;
integrator0_xc.get_mutable_vector()[2] = 27;
auto& integrator1_xc = GetMutableContinuousState(integrator1());
integrator1_xc.get_mutable_vector()[0] = 81;
integrator1_xc.get_mutable_vector()[1] = 243;
integrator1_xc.get_mutable_vector()[2] = 729;
}
// Returns the continuous state of the given @p system.
ContinuousState<double>& GetMutableContinuousState(
const System<double>* system) {
return diagram_->GetMutableSubsystemState(*system, context_.get())
.get_mutable_continuous_state();
}
// Asserts that output_ is what it should be for the default values
// of input0_, input1_, and input2_.
void ExpectDefaultOutputs() {
Vector3d expected_output0(
1 + 8 + 64,
2 + 16 + 128,
4 + 32 + 256); // B
Vector3d expected_output1(
1 + 8,
2 + 16,
4 + 32); // A
expected_output1 += expected_output0; // A + B
Vector3d expected_output2(81, 243, 729); // state of integrator1_
const BasicVector<double>* output0 = output_->get_vector_data(0);
ASSERT_TRUE(output0 != nullptr);
EXPECT_EQ(expected_output0[0], output0->get_value()[0]);
EXPECT_EQ(expected_output0[1], output0->get_value()[1]);
EXPECT_EQ(expected_output0[2], output0->get_value()[2]);
const BasicVector<double>* output1 = output_->get_vector_data(1);
ASSERT_TRUE(output1 != nullptr);
EXPECT_EQ(expected_output1[0], output1->get_value()[0]);
EXPECT_EQ(expected_output1[1], output1->get_value()[1]);
EXPECT_EQ(expected_output1[2], output1->get_value()[2]);
const BasicVector<double>* output2 = output_->get_vector_data(2);
ASSERT_TRUE(output2 != nullptr);
EXPECT_EQ(expected_output2[0], output2->get_value()[0]);
EXPECT_EQ(expected_output2[1], output2->get_value()[1]);
EXPECT_EQ(expected_output2[2], output2->get_value()[2]);
}
void AttachInputs() {
diagram_->get_input_port(0).FixValue(context_.get(), input0_);
diagram_->get_input_port(1).FixValue(context_.get(), input1_);
diagram_->get_input_port(2).FixValue(context_.get(), input2_);
}
Adder<double>* adder0() { return diagram_->adder0(); }
Integrator<double>* integrator0() { return diagram_->integrator0(); }
Integrator<double>* integrator1() { return diagram_->integrator1(); }
const int kSize = 3;
std::unique_ptr<ExampleDiagram> diagram_;
const Vector3d input0_{1, 2, 4};
const Vector3d input1_{8, 16, 32};
const Vector3d input2_{64, 128, 256};
std::unique_ptr<Context<double>> context_;
std::unique_ptr<SystemOutput<double>> output_;
};
// Tests that the diagram returns the correct number of continuous states
// without a context. The class ExampleDiagram above contains two integrators,
// each of which has three state variables, plus the "kitchen sink" which
// has 12.
TEST_F(DiagramTest, NumberOfContinuousStates) {
EXPECT_EQ(3+3+12, diagram_->num_continuous_states());
}
// Tests that the diagram returns the correct number of witness functions and
// that the witness function can be called correctly.
TEST_F(DiagramTest, Witness) {
std::vector<const WitnessFunction<double>*> wf;
diagram_->GetWitnessFunctions(*context_, &wf);
// Stateless function always returns the ClockWitness.
ASSERT_EQ(wf.size(), 1);
EXPECT_LT(diagram_->CalcWitnessValue(*context_, *wf.front()), 0);
}
// Tests that the diagram exports the correct topology.
TEST_F(DiagramTest, Topology) {
ASSERT_EQ(kSize, diagram_->num_input_ports());
for (int i = 0; i < kSize; ++i) {
const auto& input_port = diagram_->get_input_port(i);
EXPECT_EQ(diagram_.get(), &input_port.get_system());
EXPECT_EQ(kVectorValued, input_port.get_data_type());
EXPECT_EQ(kSize, input_port.size());
}
ASSERT_EQ(kSize, diagram_->num_output_ports());
for (int i = 0; i < kSize; ++i) {
const auto& port = diagram_->get_output_port(i);
EXPECT_EQ(diagram_.get(), &port.get_system());
EXPECT_EQ(kVectorValued, port.get_data_type());
EXPECT_EQ(kSize, port.size());
}
// The diagram has direct feedthrough.
EXPECT_TRUE(diagram_->HasAnyDirectFeedthrough());
// Specifically, outputs 0 and 1 have direct feedthrough, but not output 2.
EXPECT_TRUE(diagram_->HasDirectFeedthrough(0));
EXPECT_TRUE(diagram_->HasDirectFeedthrough(1));
EXPECT_FALSE(diagram_->HasDirectFeedthrough(2));
// Specifically, outputs 0 and 1 have direct feedthrough from all inputs.
for (int i = 0; i < kSize; ++i) {
EXPECT_TRUE(diagram_->HasDirectFeedthrough(i, 0));
EXPECT_TRUE(diagram_->HasDirectFeedthrough(i, 1));
EXPECT_FALSE(diagram_->HasDirectFeedthrough(i, 2));
}
}
// Confirms that the Diagram::AreConnected() query reports the correct results.
TEST_F(DiagramTest, AreConnected) {
// Several verifiably connected ports.
EXPECT_TRUE(diagram_->AreConnected(diagram_->adder0()->get_output_port(),
diagram_->adder1()->get_input_port(0)));
EXPECT_TRUE(diagram_->AreConnected(diagram_->adder1()->get_output_port(),
diagram_->adder2()->get_input_port(1)));
EXPECT_TRUE(diagram_->AreConnected(diagram_->adder0()->get_output_port(),
diagram_->adder2()->get_input_port(0)));
// A couple unconnected ports -- but they all belong to the diagram.
EXPECT_FALSE(diagram_->AreConnected(diagram_->adder0()->get_output_port(),
diagram_->adder1()->get_input_port(1)));
EXPECT_FALSE(diagram_->AreConnected(diagram_->adder1()->get_output_port(),
diagram_->adder2()->get_input_port(0)));
// Test against a port that does *not* belong to the diagram.
Adder<double> temp_adder(2, kSize);
EXPECT_FALSE(diagram_->AreConnected(temp_adder.get_output_port(),
diagram_->adder1()->get_input_port(1)));
EXPECT_FALSE(diagram_->AreConnected(diagram_->adder1()->get_output_port(),
temp_adder.get_input_port(1)));
}
// Tests that dependency wiring is set up correctly between
// 1. input ports and their source output ports,
// 2. diagram output ports and their source leaf output ports,
// 3. diagram input ports and the corresponding exported leaf inputs,
// 4. diagram states/parameters and their constituent leaf states/parameters.
TEST_F(DiagramTest, CheckPortSubscriptions) {
const Context<double>& adder1_subcontext =
diagram_->GetSubsystemContext(*diagram_->adder1(), *context_);
const OutputPortBase& adder1_oport0 =
diagram_->adder1()->get_output_port_base(OutputPortIndex(0));
const DependencyTracker& adder1_oport0_tracker =
adder1_subcontext.get_tracker(adder1_oport0.ticket());
const Context<double>& adder2_subcontext =
diagram_->GetSubsystemContext(*diagram_->adder2(), *context_);
const InputPortBase& adder2_iport1 =
diagram_->adder2()->get_input_port_base(InputPortIndex(1));
const DependencyTracker& adder2_iport1_tracker =
adder2_subcontext.get_tracker(adder2_iport1.ticket());
// 1. Adder2's input port 1 depends on adder1's output port 0.
EXPECT_TRUE(adder1_oport0_tracker.HasSubscriber(adder2_iport1_tracker));
EXPECT_TRUE(adder2_iport1_tracker.HasPrerequisite(adder1_oport0_tracker));
const OutputPortBase& diagram_oport1 =
diagram_->get_output_port_base(OutputPortIndex(1));
const DependencyTracker& diagram_oport1_tracker =
context_->get_tracker(diagram_oport1.ticket());
const OutputPortBase& adder2_oport0 =
diagram_->adder2()->get_output_port_base(OutputPortIndex(0));
const DependencyTracker& adder2_oport0_tracker =
adder2_subcontext.get_tracker(adder2_oport0.ticket());
// 2. Diagram's output port 1 is exported from adder2's output port 0.
EXPECT_TRUE(adder2_oport0_tracker.HasSubscriber(diagram_oport1_tracker));
EXPECT_TRUE(diagram_oport1_tracker.HasPrerequisite(adder2_oport0_tracker));
const InputPortBase& diagram_iport2 =
diagram_->get_input_port_base(InputPortIndex(2));
const DependencyTracker& diagram_iport2_tracker =
context_->get_tracker(diagram_iport2.ticket());
const InputPortBase& adder1_iport1 =
diagram_->adder1()->get_input_port_base(InputPortIndex(1));
const DependencyTracker& adder1_iport1_tracker =
adder1_subcontext.get_tracker(adder1_iport1.ticket());
// 3. Diagram's input port 2 is imported to adder1's input port 1.
EXPECT_TRUE(diagram_iport2_tracker.HasSubscriber(adder1_iport1_tracker));
EXPECT_TRUE(adder1_iport1_tracker.HasPrerequisite(diagram_iport2_tracker));
// 4. Diagrams q, v, z, xd, xa state trackers and pn, pa parameter trackers
// subscribe to the corresponding leaf trackers.
auto systems = diagram_->GetSystems();
for (auto subsystem : systems) {
const auto& subcontext =
diagram_->GetSubsystemContext(*subsystem, *context_);
// Not checking "HasSubscriber" separately to cut down on fluff;
// prerequisite and subscriber are set in the same call and checked above.
EXPECT_TRUE(context_->get_tracker(diagram_->q_ticket())
.HasPrerequisite(subcontext.get_tracker(subsystem->q_ticket())));
EXPECT_TRUE(context_->get_tracker(diagram_->v_ticket())
.HasPrerequisite(subcontext.get_tracker(subsystem->v_ticket())));
EXPECT_TRUE(context_->get_tracker(diagram_->z_ticket())
.HasPrerequisite(subcontext.get_tracker(subsystem->z_ticket())));
EXPECT_TRUE(context_->get_tracker(diagram_->xd_ticket())
.HasPrerequisite(subcontext.get_tracker(subsystem->xd_ticket())));
EXPECT_TRUE(context_->get_tracker(diagram_->xa_ticket())
.HasPrerequisite(subcontext.get_tracker(subsystem->xa_ticket())));
EXPECT_TRUE(context_->get_tracker(diagram_->pn_ticket())
.HasPrerequisite(subcontext.get_tracker(subsystem->pn_ticket())));
EXPECT_TRUE(context_->get_tracker(diagram_->pa_ticket())
.HasPrerequisite(subcontext.get_tracker(subsystem->pa_ticket())));
}
}
TEST_F(DiagramTest, Path) {
const std::string path = adder0()->GetSystemPathname();
EXPECT_EQ("::Unicode Snowman's Favorite Diagram!!1!☃!::adder0", path);
// Just the root.
EXPECT_EQ("::Unicode Snowman's Favorite Diagram!!1!☃!",
diagram_->GetSystemPathname());
}
// Tests the special cases in ValidateContext() that recognize if the context
// or system is the root.
TEST_F(DiagramTest, ValidateContext) {
// Root diagram given root context.
DRAKE_EXPECT_NO_THROW(diagram_->ValidateContext(*context_));
// Internal system given root diagram's context.
DRAKE_EXPECT_THROWS_MESSAGE(
adder0()->ValidateContext(*context_),
".*was passed the root Diagram's Context.+GetMyContextFromRoot"
"[^]*troubleshooting.html.+");
// Root diagram given context for internal system.
const auto& adder_context = adder0()->GetMyContextFromRoot(*context_);
DRAKE_EXPECT_THROWS_MESSAGE(diagram_->ValidateContext(adder_context),
".*root Diagram was passed a subcontext"
"[^]*troubleshooting.html.+");
// And for the sake of completeness, one leaf system's context passed to
// another leaf system.
const auto& integrator0_context =
integrator0()->GetMyContextFromRoot(*context_);
DRAKE_EXPECT_THROWS_MESSAGE(
integrator1()->ValidateContext(integrator0_context),
"A function call on .+ system named '.+' was passed the Context of a "
"system named '.+'[^]*troubleshooting.html.+");
}
TEST_F(DiagramTest, Graphviz) {
SystemBase::GraphvizFragment fragment = diagram_->GetGraphvizFragment();
const std::string dot = fmt::format("{}", fmt::join(fragment.fragments, ""));
// Check that the Diagram is labeled with its name.
EXPECT_THAT(dot,
testing::HasSubstr(
"\nname=Unicode Snowman's Favorite Diagram!!1!☃!\n"));
// Check that ports are declared with blue and green bubbles.
EXPECT_THAT(dot, testing::HasSubstr(
"COLOR=\"blue\" CELLSPACING=\"3\" STYLE=\"rounded\""));
EXPECT_THAT(dot, testing::HasSubstr(
"COLOR=\"green\" CELLSPACING=\"3\" STYLE=\"rounded\""));
// Check that subsystems appear.
EXPECT_THAT(dot, testing::HasSubstr("\nname=adder1\n"));
// Check that internal edges appear.
const SystemBase::GraphvizFragment adder1_frag =
diagram_->adder1()->GetGraphvizFragment();
const SystemBase::GraphvizFragment adder2_frag =
diagram_->adder2()->GetGraphvizFragment();
// [Adder 1, output 0] -> [Adder 2, input 1]
std::string edge = fmt::format("{}:e -> {}:w", adder1_frag.output_ports.at(0),
adder2_frag.input_ports.at(1));
EXPECT_THAT(dot, testing::HasSubstr(edge));
// Check that synthetic I/O edges appear: inputs in blue, outputs in green.
// [Diagram Input 2] -> [Adder 1, input 1]
edge = fmt::format("{}:e -> {}:w [color=blue]", fragment.input_ports.at(2),
adder1_frag.input_ports.at(1));
EXPECT_THAT(dot, testing::HasSubstr(edge));
// [Diagram Input 2] -> [Sink, input]
const SystemBase::GraphvizFragment sink_frag =
diagram_->sink()->GetGraphvizFragment();
edge = fmt::format("{}:e -> {}:w [color=blue]", fragment.input_ports.at(2),
sink_frag.input_ports.at(0));
EXPECT_THAT(dot, testing::HasSubstr(edge));
// [Adder 2, output 0] -> [Diagram Output 1]
edge =
fmt::format("{}:e -> {}:w [color=green]", adder2_frag.output_ports.at(0),
fragment.output_ports.at(1));
EXPECT_THAT(dot, testing::HasSubstr(edge));
}
// Tests that both variants of GetMutableSubsystemState do what they say on
// the tin.
TEST_F(DiagramTest, GetMutableSubsystemState) {
State<double>& state_from_context = diagram_->GetMutableSubsystemState(
*diagram_->integrator0(), context_.get());
State<double>& state_from_state = diagram_->GetMutableSubsystemState(
*diagram_->integrator0(), &context_->get_mutable_state());
EXPECT_EQ(&state_from_context, &state_from_state);
const ContinuousState<double>& xc =
state_from_context.get_continuous_state();
EXPECT_EQ(3, xc[0]);
EXPECT_EQ(9, xc[1]);
EXPECT_EQ(27, xc[2]);
}
// Tests that the diagram computes the correct sum.
TEST_F(DiagramTest, CalcOutput) {
AttachInputs();
diagram_->CalcOutput(*context_, output_.get());
ASSERT_EQ(kSize, output_->num_ports());
ExpectDefaultOutputs();
}
// Tests that Diagram output ports are built with the right prerequisites
// and that Eval caches as expected.
TEST_F(DiagramTest, EvalOutput) {
AttachInputs();
// Sanity check output port prerequisites. Diagram ports should designate
// a subsystem since they are resolved internally. We don't know the right
// dependency ticket, but at least it should be valid.
ASSERT_EQ(diagram_->num_output_ports(), 3);
const int expected_subsystem[] = {1, 2, 5}; // From drawing above.
for (OutputPortIndex i(0); i < diagram_->num_output_ports(); ++i) {
internal::OutputPortPrerequisite prereq =
diagram_->get_output_port(i).GetPrerequisite();
EXPECT_EQ(*prereq.child_subsystem, expected_subsystem[i]);
EXPECT_TRUE(prereq.dependency.is_valid());
}
}
TEST_F(DiagramTest, CalcTimeDerivatives) {
AttachInputs();
std::unique_ptr<ContinuousState<double>> derivatives =
diagram_->AllocateTimeDerivatives();
EXPECT_EQ(derivatives->get_system_id(), context_->get_system_id());
diagram_->CalcTimeDerivatives(*context_, derivatives.get());
ASSERT_EQ(18, derivatives->size());
ASSERT_EQ(4, derivatives->get_generalized_position().size());
ASSERT_EQ(3, derivatives->get_generalized_velocity().size());
ASSERT_EQ(11, derivatives->get_misc_continuous_state().size());
// The derivative of the first integrator is A.
const ContinuousState<double>& integrator0_xcdot =
diagram_->GetSubsystemDerivatives(*integrator0(), *derivatives);
EXPECT_EQ(1 + 8, integrator0_xcdot.get_vector()[0]);
EXPECT_EQ(2 + 16, integrator0_xcdot.get_vector()[1]);
EXPECT_EQ(4 + 32, integrator0_xcdot.get_vector()[2]);
// The derivative of the second integrator is the state of the first.
const ContinuousState<double>& integrator1_xcdot =
diagram_->GetSubsystemDerivatives(*integrator1(), *derivatives);
EXPECT_EQ(3, integrator1_xcdot.get_vector()[0]);
EXPECT_EQ(9, integrator1_xcdot.get_vector()[1]);
EXPECT_EQ(27, integrator1_xcdot.get_vector()[2]);
}
TEST_F(DiagramTest, ContinuousStateBelongsWithSystem) {
AttachInputs();
// Successfully calc using storage that was created by the system.
std::unique_ptr<ContinuousState<double>> derivatives =
diagram_->AllocateTimeDerivatives();
DRAKE_EXPECT_NO_THROW(
diagram_->CalcTimeDerivatives(*context_, derivatives.get()));
// Successfully calc using storage that was indirectly created by the system.
auto temp_context = diagram_->AllocateContext();
ContinuousState<double>& temp_xc =
temp_context->get_mutable_continuous_state();
DRAKE_EXPECT_NO_THROW(
diagram_->CalcTimeDerivatives(*context_, &temp_xc));
// Cannot ask the other_diagram to calc into storage that was created by the
// original diagram.
const ExampleDiagram other_diagram(kSize);
auto other_context = other_diagram.AllocateContext();
DRAKE_EXPECT_THROWS_MESSAGE(
other_diagram.CalcTimeDerivatives(*other_context, derivatives.get()),
".*::ContinuousState<double> was not created for.*::ExampleDiagram.*");
}
// Tests the AllocateInput logic.
TEST_F(DiagramTest, AllocateInputs) {
auto context = diagram_->CreateDefaultContext();
for (int port = 0; port < 3; port++) {
EXPECT_FALSE(diagram_->get_input_port(port).HasValue(*context));
}
diagram_->AllocateFixedInputs(context.get());
for (int port = 0; port < 3; port++) {
EXPECT_TRUE(diagram_->get_input_port(port).HasValue(*context));
EXPECT_EQ(diagram_->get_input_port(port).Eval(*context).size(), kSize);
}
}
TEST_F(DiagramTest, GetSubsystemByName) {
EXPECT_TRUE(diagram_->HasSubsystemNamed("stateless"));
const System<double>& stateless = diagram_->GetSubsystemByName("stateless");
EXPECT_NE(
dynamic_cast<const StatelessSystem<double>*>(&stateless),
nullptr);
EXPECT_FALSE(diagram_->HasSubsystemNamed("not_a_subsystem"));
DRAKE_EXPECT_THROWS_MESSAGE(
diagram_->GetSubsystemByName("not_a_subsystem"),
"System .* does not have a subsystem named not_a_subsystem. The existing "
"subsystems are named \\{adder0, adder1, adder2, stateless, integrator0, "
"integrator1, sink, kitchen_sink\\}.");
}
TEST_F(DiagramTest, GetDowncastSubsystemByName) {
const StatelessSystem<double>& stateless =
diagram_->GetDowncastSubsystemByName<StatelessSystem>("stateless");
EXPECT_EQ(stateless.get_name(), "stateless");
DRAKE_EXPECT_THROWS_MESSAGE(
diagram_->GetDowncastSubsystemByName<EmptySystem>("stateless"),
".*cast.*StatelessSystem.*EmptySystem.*");
DRAKE_EXPECT_THROWS_MESSAGE(
diagram_->GetDowncastSubsystemByName<StatelessSystem>("not_a_subsystem"),
"System .* does not have a subsystem named not_a_subsystem. The existing "
"subsystems are named \\{adder0, adder1, adder2, stateless, integrator0, "
"integrator1, sink, kitchen_sink\\}.");
// Now downcast a non-templatized system (invokes a different overload).
// This will only compile if the subsystem's scalar type matches the
// Diagram's scalar type.
const StatelessSystem<double>& also_stateless =
diagram_->GetDowncastSubsystemByName<StatelessSystem<double>>
("stateless");
EXPECT_EQ(also_stateless.get_name(), "stateless");
// Both overloads use the same implementation and depend on
// GetSubsystemByName() for the error checking tested above.
}
// 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.
TEST_F(DiagramTest, CachingChangePropagation) {
AttachInputs(); // So we can Eval() below.
const Context<double>& adder1_subcontext =
diagram_->GetSubsystemContext(*diagram_->adder1(), *context_);
const OutputPort<double>& adder1_output =
diagram_->adder1()->get_output_port();
auto& adder1_leaf_output =
dynamic_cast<const LeafOutputPort<double>&>(adder1_output);
auto& cache_entry = adder1_leaf_output.cache_entry();
EXPECT_FALSE(cache_entry.is_cache_entry_disabled(adder1_subcontext));
EXPECT_TRUE(cache_entry.is_out_of_date(adder1_subcontext));
context_->DisableCaching();
EXPECT_TRUE(cache_entry.is_cache_entry_disabled(adder1_subcontext));
EXPECT_TRUE(cache_entry.is_out_of_date(adder1_subcontext));
context_->EnableCaching();
EXPECT_FALSE(cache_entry.is_cache_entry_disabled(adder1_subcontext));
EXPECT_TRUE(cache_entry.is_out_of_date(adder1_subcontext));
// Bring the cache entry up to date.
cache_entry.EvalAbstract(adder1_subcontext);
EXPECT_FALSE(cache_entry.is_out_of_date(adder1_subcontext));
context_->SetAllCacheEntriesOutOfDate();
EXPECT_TRUE(cache_entry.is_out_of_date(adder1_subcontext));
}
// Tests that a diagram can be transmogrified to AutoDiffXd.
TEST_F(DiagramTest, ToAutoDiffXd) {
std::string double_inputs;
for (int k = 0; k < diagram_->num_input_ports(); k++) {
double_inputs += diagram_->get_input_port(k).get_name();
double_inputs += ",";
}
std::unique_ptr<System<AutoDiffXd>> ad_diagram =
diagram_->ToAutoDiffXd();
std::string ad_inputs;
for (int k = 0; k < ad_diagram->num_input_ports(); k++) {
ad_inputs += ad_diagram->get_input_port(k).get_name();
ad_inputs += ",";
}
ASSERT_EQ(double_inputs, ad_inputs);
std::unique_ptr<Context<AutoDiffXd>> context =
ad_diagram->CreateDefaultContext();
std::unique_ptr<SystemOutput<AutoDiffXd>> output =
ad_diagram->AllocateOutput();
// The name was preserved.
EXPECT_EQ(diagram_->get_name(), ad_diagram->get_name());
// Set up some inputs, computing gradients with respect to every other input.
/// adder0_: (input0_ + input1_) -> A
/// adder1_: (A + input2_) -> B, output 0
/// adder2_: (A + B) -> output 1
/// integrator1_: A -> C
/// integrator2_: C -> output 2
VectorX<AutoDiffXd> input0(3);
VectorX<AutoDiffXd> input1(3);
VectorX<AutoDiffXd> input2(3);
for (int i = 0; i < 3; ++i) {
input0[i].value() = 1 + 0.1 * i;
input0[i].derivatives() = VectorXd::Unit(9, i);
input1[i].value() = 2 + 0.2 * i;
input1[i].derivatives() = VectorXd::Unit(9, 3 + i);
input2[i].value() = 3 + 0.3 * i;
input2[i].derivatives() = VectorXd::Unit(9, 6 + i);
}
ad_diagram->get_input_port(0).FixValue(context.get(), input0);
ad_diagram->get_input_port(1).FixValue(context.get(), input1);
ad_diagram->get_input_port(2).FixValue(context.get(), input2);
ad_diagram->CalcOutput(*context, output.get());
ASSERT_EQ(kSize, output->num_ports());
// Spot-check some values and gradients.
// A = [1.0 + 2.0, 1.1 + 2.2, 1.2 + 2.4]
// output0 = B = A + [3.0, 3.3, 3.6]
const BasicVector<AutoDiffXd>* output0 = output->get_vector_data(0);
EXPECT_DOUBLE_EQ(1.2 + 2.4 + 3.6, (*output0)[2].value());
// ∂B[2]/∂input0,1,2[2] is 1. Other partials are zero.
for (int i = 0; i < 9; ++i) {
if (i == 2 || i == 5 || i == 8) {
EXPECT_EQ(1.0, (*output0)[2].derivatives()[i]);
} else {
EXPECT_EQ(0.0, (*output0)[2].derivatives()[i]);
}
}
// output1 = A + B = 2A + [3.0, 3.3, 3.6]
const BasicVector<AutoDiffXd>* output1 = output->get_vector_data(1);
EXPECT_DOUBLE_EQ(2 * (1.1 + 2.2) + 3.3, (*output1)[1].value());
// ∂B[1]/∂input0,1[1] is 2. ∂B[1]/∂input2[1] is 1. Other partials are zero.
for (int i = 0; i < 9; ++i) {
if (i == 1 || i == 4) {
EXPECT_EQ(2.0, (*output1)[1].derivatives()[i]);
} else if (i == 7) {
EXPECT_EQ(1.0, (*output1)[1].derivatives()[i]);
} else {
EXPECT_EQ(0.0, (*output1)[1].derivatives()[i]);
}
}
// Make sure that the input port names survive type conversion.
for (InputPortIndex i{0}; i < diagram_->num_input_ports(); i++) {
EXPECT_EQ(diagram_->get_input_port(i).get_name(),
ad_diagram->get_input_port(i).get_name());
}
// Make sure that the output port names survive type conversion.
for (OutputPortIndex i{0}; i < diagram_->num_output_ports(); i++) {
EXPECT_EQ(diagram_->get_output_port(i).get_name(),
ad_diagram->get_output_port(i).get_name());
}
// When the Diagram contains a System that does not support AutoDiffXd,
// we cannot transmogrify the Diagram to AutoDiffXd.
const bool use_abstract = false;
const bool use_double_only = true;
auto diagram_with_double_only = std::make_unique<ExampleDiagram>(
kSize, use_abstract, use_double_only);
DRAKE_EXPECT_THROWS_MESSAGE(
diagram_with_double_only->ToAutoDiffXd(),
".*ExampleDiagram.*AutoDiffXd.*DoubleOnlySystem.*");
}
/// Tests that a diagram can be transmogrified to symbolic.
TEST_F(DiagramTest, ToSymbolic) {
// We manually specify the template argument so that is_symbolic_convertible
// asserts the result is merely a Diagram, not an ExampleDiagram.
EXPECT_TRUE(is_symbolic_convertible<systems::Diagram>(*diagram_));
// No symbolic support when one of the subsystems does not declare support.
const bool use_abstract = false;
const bool use_double_only = true;
auto diagram_with_double_only = std::make_unique<ExampleDiagram>(
kSize, use_abstract, use_double_only);
EXPECT_THROW(diagram_with_double_only->ToSymbolic(), std::exception);
}
// Tests that the same diagram can be evaluated into the same output with
// different contexts interchangeably.
TEST_F(DiagramTest, Clone) {
AttachInputs();
// Compute the output with the default inputs and sanity-check it.
diagram_->CalcOutput(*context_, output_.get());
ExpectDefaultOutputs();
// Verify that we start with a DiagramContext with Diagram ingredients.
EXPECT_TRUE(is_dynamic_castable<DiagramContext<double>>(context_));
EXPECT_TRUE(is_dynamic_castable<DiagramContinuousState<double>>(
diagram_->AllocateTimeDerivatives()));
EXPECT_TRUE(is_dynamic_castable<DiagramDiscreteValues<double>>(
diagram_->AllocateDiscreteVariables()));
const State<double>& state = context_->get_state();
EXPECT_TRUE(is_dynamic_castable<DiagramState<double>>(&state));
EXPECT_TRUE(is_dynamic_castable<DiagramContinuousState<double>>(
&state.get_continuous_state()));
EXPECT_TRUE(is_dynamic_castable<DiagramDiscreteValues<double>>(
&state.get_discrete_state()));
// FYI there is no DiagramAbstractValues.
// Create a clone of the context and change an input.
auto clone = context_->Clone();
// Verify that the clone is also a DiagramContext with Diagram ingredients.
EXPECT_TRUE(is_dynamic_castable<DiagramContext<double>>(clone));
const State<double>& clone_state = context_->get_state();
EXPECT_TRUE(is_dynamic_castable<DiagramState<double>>(&clone_state));
EXPECT_TRUE(is_dynamic_castable<DiagramContinuousState<double>>(
&clone_state.get_continuous_state()));
EXPECT_TRUE(is_dynamic_castable<DiagramDiscreteValues<double>>(
&clone_state.get_discrete_state()));
DRAKE_DEMAND(kSize == 3);
diagram_->get_input_port(0).FixValue(clone.get(), Vector3d(3, 6, 9));
// Recompute the output and check the values.
diagram_->CalcOutput(*clone, output_.get());
Vector3d expected_output0(
3 + 8 + 64,
6 + 16 + 128,
9 + 32 + 256); // B
const BasicVector<double>* output0 = output_->get_vector_data(0);
ASSERT_TRUE(output0 != nullptr);
EXPECT_EQ(expected_output0[0], output0->get_value()[0]);
EXPECT_EQ(expected_output0[1], output0->get_value()[1]);
EXPECT_EQ(expected_output0[2], output0->get_value()[2]);
Vector3d expected_output1(
3 + 8,
6 + 16,
9 + 32); // A
expected_output1 += expected_output0; // A + B
const BasicVector<double>* output1 = output_->get_vector_data(1);
ASSERT_TRUE(output1 != nullptr);
EXPECT_EQ(expected_output1[0], output1->get_value()[0]);
EXPECT_EQ(expected_output1[1], output1->get_value()[1]);
EXPECT_EQ(expected_output1[2], output1->get_value()[2]);
// Check that the context that was cloned is unaffected.
diagram_->CalcOutput(*context_, output_.get());
ExpectDefaultOutputs();
}
// Tests that, when asked for the state derivatives of Systems that are
// stateless, Diagram returns an empty state.
TEST_F(DiagramTest, DerivativesOfStatelessSystemAreEmpty) {
std::unique_ptr<ContinuousState<double>> derivatives =
diagram_->AllocateTimeDerivatives();
EXPECT_EQ(0,
diagram_->GetSubsystemDerivatives(*adder0(), *derivatives).size());
}
// Tests that, when asked for the discrete state of Systems that are
// stateless, Diagram returns an empty state.
TEST_F(DiagramTest, DiscreteValuesOfStatelessSystemAreEmpty) {
std::unique_ptr<DiscreteValues<double>> updates =
diagram_->AllocateDiscreteVariables();
EXPECT_EQ(
0,
diagram_->GetSubsystemDiscreteValues(*adder0(), *updates).num_groups());
}
class DiagramOfDiagramsTest : public ::testing::Test {
protected:
void SetUp() override {
DiagramBuilder<double> builder;
subdiagram0_ = builder.AddSystem<ExampleDiagram>(kSize);
subdiagram0_->set_name("subdiagram0");
subdiagram1_ = builder.AddSystem<ExampleDiagram>(kSize);
subdiagram1_->set_name("subdiagram1");
// Hook up the two diagrams in portwise series.
for (int i = 0; i < 3; i++) {
builder.ExportInput(subdiagram0_->get_input_port(i));
builder.Connect(subdiagram0_->get_output_port(i),
subdiagram1_->get_input_port(i));
builder.ExportOutput(subdiagram1_->get_output_port(i));
}
diagram_ = builder.Build();
diagram_->set_name("DiagramOfDiagrams");
context_ = diagram_->CreateDefaultContext();
// Make sure caching is on locally, even if it is off by default.
// Do not remove this line; we want to show that these tests function
// correctly with caching on. It is easier to pass with caching off!
context_->EnableCaching();
output_ = diagram_->AllocateOutput();
diagram_->get_input_port(0).FixValue(context_.get(), 8.0);
diagram_->get_input_port(1).FixValue(context_.get(), 64.0);
diagram_->get_input_port(2).FixValue(context_.get(), 512.0);
// Initialize the integrator states.
Context<double>& d0_context =
diagram_->GetMutableSubsystemContext(*subdiagram0_, context_.get());
Context<double>& d1_context =
diagram_->GetMutableSubsystemContext(*subdiagram1_, context_.get());
State<double>& integrator0_x = subdiagram0_->GetMutableSubsystemState(
*subdiagram0_->integrator0(), &d0_context);
integrator0_x.get_mutable_continuous_state()
.get_mutable_vector()[0] = 3;
State<double>& integrator1_x = subdiagram0_->GetMutableSubsystemState(
*subdiagram0_->integrator1(), &d0_context);
integrator1_x.get_mutable_continuous_state()
.get_mutable_vector()[0] = 9;
State<double>& integrator2_x = subdiagram1_->GetMutableSubsystemState(
*subdiagram1_->integrator0(), &d1_context);
integrator2_x.get_mutable_continuous_state()
.get_mutable_vector()[0] = 27;
State<double>& integrator3_x = subdiagram1_->GetMutableSubsystemState(
*subdiagram1_->integrator1(), &d1_context);
integrator3_x.get_mutable_continuous_state()
.get_mutable_vector()[0] = 81;
}
const int kSize = 1;
std::unique_ptr<Diagram<double>> diagram_ = nullptr;
ExampleDiagram* subdiagram0_ = nullptr;
ExampleDiagram* subdiagram1_ = nullptr;
std::unique_ptr<Context<double>> context_;
std::unique_ptr<SystemOutput<double>> output_;
};
// Now we can check that the nested Diagram reports correct declared sizes.
// It is sufficient to check the Diagram declared sizes with the actual
// Context sizes since we verify elsewhere that Diagrams produce correct
// Contexts.
TEST_F(DiagramOfDiagramsTest, DeclaredContextSizes) {
EXPECT_EQ(diagram_->num_continuous_states(),
context_->num_continuous_states());
EXPECT_EQ(diagram_->num_discrete_state_groups(),
context_->num_discrete_state_groups());
EXPECT_EQ(diagram_->num_abstract_states(),
context_->num_abstract_states());
EXPECT_EQ(diagram_->num_numeric_parameter_groups(),
context_->num_numeric_parameter_groups());
EXPECT_EQ(diagram_->num_abstract_parameters(),
context_->num_abstract_parameters());
}
// ContextSizes for a Diagram must be accumulated recursively. We checked
// above that a Diagram built using DiagramBuilder counts properly. Diagrams
// can also be built via scalar conversion. We'll check here that the
// context sizes are correct that way also.
TEST_F(DiagramOfDiagramsTest, ScalarConvertAndCheckContextSizes) {
Diagram<AutoDiffXd> diagram_ad(*diagram_);
// Anticipated context sizes should be unchanged from the original.
EXPECT_EQ(diagram_ad.num_continuous_states(),
context_->num_continuous_states());
EXPECT_EQ(diagram_ad.num_discrete_state_groups(),
context_->num_discrete_state_groups());
EXPECT_EQ(diagram_ad.num_abstract_states(),
context_->num_abstract_states());
EXPECT_EQ(diagram_ad.num_numeric_parameter_groups(),
context_->num_numeric_parameter_groups());
EXPECT_EQ(diagram_ad.num_abstract_parameters(),
context_->num_abstract_parameters());
}
TEST_F(DiagramOfDiagramsTest, Graphviz) {
const std::string dot = diagram_->GetGraphvizString();
// Check that both subdiagrams appear.
const std::string needle0 = "\nname=subdiagram0\n";
const std::string needle1 = "\nname=subdiagram1\n";
EXPECT_THAT(dot, testing::HasSubstr(needle0));
EXPECT_THAT(dot, testing::HasSubstr(needle1));
// Check that edges between the two subdiagrams exist.
const SystemBase::GraphvizFragment sub0_frag =
subdiagram0_->GetGraphvizFragment();
const SystemBase::GraphvizFragment sub1_frag =
subdiagram1_->GetGraphvizFragment();
const std::string sub0_y0 = sub0_frag.output_ports.at(0);
const std::string sub1_u0 = sub1_frag.input_ports.at(0);
const std::string edge = fmt::format("{}:e -> {}:w", sub0_y0, sub1_u0);
EXPECT_THAT(dot, testing::HasSubstr(edge));
// Check that the subdiagrams no longer appear.
const int max_depth = 0;
const std::string dot_no_depth = diagram_->GetGraphvizString(max_depth);
EXPECT_THAT(dot_no_depth, testing::Not(testing::HasSubstr(needle0)));
EXPECT_THAT(dot_no_depth, testing::Not(testing::HasSubstr(needle1)));
}
// Tests that a diagram composed of diagrams can be evaluated, and gives
// correct answers with caching enabled.
TEST_F(DiagramOfDiagramsTest, EvalOutput) {
context_->EnableCaching(); // Just to be sure.
EXPECT_EQ(diagram_->get_input_port(0).Eval(*context_)[0], 8.);
EXPECT_EQ(diagram_->get_input_port(1).Eval(*context_)[0], 64.);
EXPECT_EQ(diagram_->get_input_port(2).Eval(*context_)[0], 512.);
// The outputs of subsystem0_ are:
// output0 = 8 + 64 + 512 = 584
// output1 = output0 + 8 + 64 = 656
// output2 = 9 (state of integrator1_)
// So, the outputs of subsystem1_, and thus of the whole diagram, are:
// output0 = 584 + 656 + 9 = 1249
// output1 = output0 + 584 + 656 = 2489
// output2 = 81 (state of integrator1_)
EXPECT_EQ(1249, diagram_->get_output_port(0).Eval(*context_)[0]);
EXPECT_EQ(2489, diagram_->get_output_port(1).Eval(*context_)[0]);
EXPECT_EQ(81, diagram_->get_output_port(2).Eval(*context_)[0]);
// Check that invalidation flows through input ports properly, either due
// to replacing the fixed value or by modifying it.
//
// First we'll replace the fixed input value 8 for input port 0 with
// a new object that has value 10. That should cause everything to get
// recalculated when the ports are Eval()-ed.
// The outputs of subsystem0_ are now:
// output0 = 10 + 64 + 512 = 586
// output1 = output0 + 10 + 64 = 660
// output2 = 9 (state of integrator1_)
// So, the outputs of subsystem1_, and thus of the whole diagram, are:
// output0 = 586 + 660 + 9 = 1255
// output1 = output0 + 586 + 660 = 2501
// output2 = 81 (state of integrator1_)
FixedInputPortValue& port_value =
diagram_->get_input_port(0).FixValue(context_.get(), 10.0);
EXPECT_EQ(1255, diagram_->get_output_port(0).
Eval<BasicVector<double>>(*context_)[0]);
EXPECT_EQ(2501, diagram_->get_output_port(1).
Eval<BasicVector<double>>(*context_)[0]);
EXPECT_EQ(81, diagram_->get_output_port(2).
Eval<BasicVector<double>>(*context_)[0]);
// Now change the value back to 8 using mutable access to the port_value
// object. Should also cause re-evaluation.
port_value.GetMutableVectorData<double>()->SetAtIndex(0, 8.0);
EXPECT_EQ(1249, diagram_->get_output_port(0).
Eval<BasicVector<double>>(*context_)[0]);
EXPECT_EQ(2489, diagram_->get_output_port(1).
Eval<BasicVector<double>>(*context_)[0]);
EXPECT_EQ(81, diagram_->get_output_port(2).
Eval<BasicVector<double>>(*context_)[0]);
}
TEST_F(DiagramOfDiagramsTest, DirectFeedthrough) {
// The diagram has direct feedthrough.
EXPECT_TRUE(diagram_->HasAnyDirectFeedthrough());
// Specifically, outputs 0 and 1 have direct feedthrough, but not output 2.
EXPECT_TRUE(diagram_->HasDirectFeedthrough(0));
EXPECT_TRUE(diagram_->HasDirectFeedthrough(1));
EXPECT_FALSE(diagram_->HasDirectFeedthrough(2));
// Specifically, outputs 0 and 1 have direct feedthrough from all inputs.
for (int i = 0; i < kSize; ++i) {
EXPECT_TRUE(diagram_->HasDirectFeedthrough(i, 0));
EXPECT_TRUE(diagram_->HasDirectFeedthrough(i, 1));
EXPECT_FALSE(diagram_->HasDirectFeedthrough(i, 2));
}
}
// A Diagram that adds a constant to an input, and outputs the sum.
class AddConstantDiagram : public Diagram<double> {
public:
explicit AddConstantDiagram(double constant) : Diagram<double>() {
DiagramBuilder<double> builder;
constant_ = builder.AddSystem<ConstantVectorSource>(Vector1d{constant});
constant_->set_name("constant");
adder_ = builder.AddSystem<Adder>(2 /* inputs */, 1 /* size */);
adder_->set_name("adder");
builder.Connect(constant_->get_output_port(), adder_->get_input_port(1));
builder.ExportInput(adder_->get_input_port(0));
builder.ExportOutput(adder_->get_output_port());
builder.BuildInto(this);
}
private:
Adder<double>* adder_ = nullptr;
ConstantVectorSource<double>* constant_ = nullptr;
};
GTEST_TEST(DiagramSubclassTest, TwelvePlusSevenIsNineteen) {
AddConstantDiagram plus_seven(7.0);
auto context = plus_seven.CreateDefaultContext();
auto output = plus_seven.AllocateOutput();
ASSERT_TRUE(context != nullptr);
ASSERT_TRUE(output != nullptr);
plus_seven.get_input_port(0).FixValue(context.get(), 12.0);
plus_seven.CalcOutput(*context, output.get());
ASSERT_EQ(1, output->num_ports());
const BasicVector<double>* output_vector = output->get_vector_data(0);
EXPECT_EQ(1, output_vector->size());
EXPECT_EQ(19.0, output_vector->get_value().x());
}
// PublishingSystem has an input port for a single double. It publishes that
// double to a function provided in the constructor.
class PublishingSystem : public LeafSystem<double> {
public:
explicit PublishingSystem(std::function<void(double)> callback)
: callback_(callback) {
this->DeclareInputPort(kUseDefaultName, kVectorValued, 1);
this->DeclareForcedPublishEvent(&PublishingSystem::InvokeCallback);
}
private:
// TODO(15465) When forced event declaration sugar allows for callbacks
// whose result is "assumed to succeed", change this to void return.
EventStatus InvokeCallback(const Context<double>& context) const {
callback_(this->get_input_port(0).Eval(context)[0]);
return EventStatus::Succeeded();
}
std::function<void(int)> callback_;
};
// PublishNumberDiagram publishes a double provided to its constructor.
class PublishNumberDiagram : public Diagram<double> {
public:
explicit PublishNumberDiagram(double constant) : Diagram<double>() {
DiagramBuilder<double> builder;
constant_ =
builder.AddSystem<ConstantVectorSource<double>>(Vector1d{constant});
constant_->set_name("constant");
publisher_ =
builder.AddSystem<PublishingSystem>([this](double v) { this->set(v); });
publisher_->set_name("publisher");
builder.Connect(constant_->get_output_port(),
publisher_->get_input_port(0));
builder.BuildInto(this);
}
double get() const { return published_value_; }
private:
void set(double value) { published_value_ = value; }
ConstantVectorSource<double>* constant_ = nullptr;
PublishingSystem* publisher_ = nullptr;
double published_value_ = 0;
};
GTEST_TEST(DiagramPublishTest, Publish) {
PublishNumberDiagram publishing_diagram(42.0);
EXPECT_EQ(0, publishing_diagram.get());
auto context = publishing_diagram.CreateDefaultContext();
publishing_diagram.ForcedPublish(*context);
EXPECT_EQ(42.0, publishing_diagram.get());
}
// FeedbackDiagram is a diagram containing a feedback loop of two
// constituent diagrams, an Integrator and a Gain. The Integrator is not
// direct-feedthrough, so there is no algebraic loop.
//
// (N.B. Normally a class that supports scalar conversion, but does not offer a
// SystemScalarConverter-accepting constructor would be marked `final`, but we
// leave the `final` off here to test what happens during wrong-subclassing.)
template <typename T>
class FeedbackDiagram : public Diagram<T> {
public:
FeedbackDiagram()
// We choose this constructor from our parent class so that we have a
// useful Diagram for the SubclassTransmogrificationTest.
: Diagram<T>(SystemTypeTag<FeedbackDiagram>{}) {
constexpr int kSize = 1;
DiagramBuilder<T> builder;
DiagramBuilder<T> integrator_builder;
Integrator<T>* const integrator =
integrator_builder.template AddSystem<Integrator>(kSize);
integrator->set_name("integrator");
integrator_builder.ExportInput(integrator->get_input_port());
integrator_builder.ExportOutput(integrator->get_output_port());
Diagram<T>* const integrator_diagram =
builder.AddSystem(integrator_builder.Build());
integrator_diagram->set_name("integrator_diagram");
DiagramBuilder<T> gain_builder;
Gain<T>* const gain =
gain_builder.template AddSystem<Gain>(1.0 /* gain */, kSize);
gain->set_name("gain");
gain_builder.ExportInput(gain->get_input_port());
gain_builder.ExportOutput(gain->get_output_port());
Diagram<T>* const gain_diagram =
builder.AddSystem(gain_builder.Build());
gain_diagram->set_name("gain_diagram");
builder.Connect(*integrator_diagram, *gain_diagram);
builder.Connect(*gain_diagram, *integrator_diagram);
builder.BuildInto(this);
}
// Scalar-converting copy constructor.
template <typename U>
explicit FeedbackDiagram(const FeedbackDiagram<U>& other)
: Diagram<T>(SystemTypeTag<FeedbackDiagram>{}, other) {}
};
// Tests that since there are no outputs, there is no direct feedthrough.
GTEST_TEST(FeedbackDiagramTest, HasDirectFeedthrough) {
FeedbackDiagram<double> diagram;
EXPECT_FALSE(diagram.HasAnyDirectFeedthrough());
}
// Tests that a FeedbackDiagram's context can be deleted without accessing
// already-freed memory. https://github.com/RobotLocomotion/drake/issues/3349
GTEST_TEST(FeedbackDiagramTest, DeletionIsMemoryClean) {
FeedbackDiagram<double> diagram;
auto context = diagram.CreateDefaultContext();
DRAKE_EXPECT_NO_THROW(context.reset());
}
// If a SystemScalarConverter is passed into the Diagram constructor, then
// transmogrification will preserve the subtype.
TEST_F(DiagramTest, SubclassTransmogrificationTest) {
const FeedbackDiagram<double> dut;
EXPECT_TRUE(is_autodiffxd_convertible(dut, [](const auto& converted) {
EXPECT_FALSE(converted.HasAnyDirectFeedthrough());
}));
EXPECT_TRUE(is_symbolic_convertible(dut, [](const auto& converted) {
EXPECT_FALSE(converted.HasAnyDirectFeedthrough());
}));
// Check that the subtype makes it all the way through cloning.
// Any mismatched subtype will fail-fast within the Clone implementation.
std::unique_ptr<FeedbackDiagram<double>> copy = System<double>::Clone(dut);
EXPECT_NE(copy, nullptr);
// Diagram subclasses that declare a specific SystemTypeTag but then use a
// subclass at runtime will fail-fast.
class SubclassOfFeedbackDiagram : public FeedbackDiagram<double> {};
const SubclassOfFeedbackDiagram subclass_dut{};
EXPECT_THROW(({
try {
subclass_dut.ToAutoDiffXd();
} catch (const std::runtime_error& e) {
EXPECT_THAT(
std::string(e.what()),
testing::MatchesRegex(
".*convert a .*::FeedbackDiagram<double>.* called with a"
".*::SubclassOfFeedbackDiagram at runtime"));
throw;
}
}), std::runtime_error);
}
// A simple class that consumes *two* inputs and passes one input through. The
// sink input (S) is consumed, the feed through input (F) is passed through to
// the output (O). This system has direct feedthrough, but only with respect to
// one input. Support class for the PortDependentFeedthroughTest.
// +-----------+
// +--+ |
// +S | |
// +--+ +--+
// | +->+O |
// +--+ | +--+
// |F +--+ |
// +--+ |
// +-----------+
class Reduce : public LeafSystem<double> {
public:
Reduce() {
const auto& input0 = this->DeclareInputPort(
kUseDefaultName, kVectorValued, 1);
feedthrough_input_ = input0.get_index();
sink_input_ = this->DeclareInputPort(
kUseDefaultName, kVectorValued, 1).get_index();
this->DeclareVectorOutputPort(kUseDefaultName, 1, &Reduce::CalcFeedthrough,
{input0.ticket()});
}
const systems::InputPort<double>& get_sink_input() const {
return this->get_input_port(sink_input_);
}
const systems::InputPort<double>& get_feedthrough_input() const {
return this->get_input_port(feedthrough_input_);
}
void CalcFeedthrough(const Context<double>& context,
BasicVector<double>* output) const {
const auto& input = get_feedthrough_input().Eval(context);
output->get_mutable_value() = input;
}
private:
int feedthrough_input_{-1};
int sink_input_{-1};
};
// Diagram input and output are connected by a system that has direct
// feedthrough, but the path between diagram input and output doesn't follow
// this path.
GTEST_TEST(PortDependentFeedthroughTest, DetectNoFeedthrough) {
// This is a diagram that wraps a Reduce Leaf system, exporting the output
// and the *sink* input. There should be *no* direct feedthrough on the diagram.
// +-----------------+
// | |
// | +-----------+ |
// | +--+ | |
// I +---->+S | | |
// | +--+ +--+ |
// | | +->+O +------> O
// | +--+ | +--+ |
// | |F +--+ | |
// | +--+ | |
// | +-----------+ |
// | |
// +-----------------+
DiagramBuilder<double> builder;
auto reduce = builder.AddSystem<Reduce>();
builder.ExportInput(reduce->get_sink_input());
builder.ExportOutput(reduce->get_output_port(0));
auto diagram = builder.Build();
EXPECT_FALSE(diagram->HasAnyDirectFeedthrough());
EXPECT_FALSE(diagram->HasDirectFeedthrough(0));
EXPECT_FALSE(diagram->HasDirectFeedthrough(0, 0));
}
// Diagram input and output are connected by a system that has direct
// feedthrough, and the input and output *are* connected by that path.
GTEST_TEST(PortDependentFeedthroughTest, DetectFeedthrough) {
// This is a diagram that wraps a Reduce Leaf system, exporting the output
// and the *feedthrough* input. There should be direct feedthrough on the
// diagram.
// +-----------------+
// | |
// | +-----------+ |
// | +--+ | |
// | |S | | |
// | +--+ +--+ |
// | | +->+O +------> O
// | +--+ | +--+ |
// I +---->|F +--+ | |
// | +--+ | |
// | +-----------+ |
// | |
// +-----------------+
DiagramBuilder<double> builder;
auto reduce = builder.AddSystem<Reduce>();
builder.ExportInput(reduce->get_feedthrough_input());
builder.ExportOutput(reduce->get_output_port(0));
auto diagram = builder.Build();
EXPECT_TRUE(diagram->HasAnyDirectFeedthrough());
EXPECT_TRUE(diagram->HasDirectFeedthrough(0));
EXPECT_TRUE(diagram->HasDirectFeedthrough(0, 0));
}
// A system with a random source inputs.
class RandomInputSystem : public LeafSystem<double> {
public:
RandomInputSystem() {
this->DeclareInputPort("deterministic", kVectorValued, 1);
this->DeclareInputPort("uniform", kVectorValued, 1,
RandomDistribution::kUniform);
this->DeclareInputPort("gaussian", kVectorValued, 1,
RandomDistribution::kGaussian);
}
};
GTEST_TEST(RandomInputSystemTest, RandomInputTest) {
DiagramBuilder<double> builder;
auto random = builder.AddSystem<RandomInputSystem>();
builder.ExportInput(random->get_input_port(0));
builder.ExportInput(random->get_input_port(1));
builder.ExportInput(random->get_input_port(2));
auto diagram = builder.Build();
EXPECT_FALSE(diagram->get_input_port(0).get_random_type());
EXPECT_EQ(diagram->get_input_port(1).get_random_type(),
RandomDistribution::kUniform);
EXPECT_EQ(diagram->get_input_port(2).get_random_type(),
RandomDistribution::kGaussian);
}
// A vector with a scalar configuration and scalar velocity.
class SecondOrderStateVector : public BasicVector<double> {
public:
SecondOrderStateVector() : BasicVector<double>(2) {}
double q() const { return GetAtIndex(0); }
double v() const { return GetAtIndex(1); }
void set_q(double q) { SetAtIndex(0, q); }
void set_v(double v) { SetAtIndex(1, v); }
protected:
[[nodiscard]] SecondOrderStateVector* DoClone() const override {
return new SecondOrderStateVector;
}
};
// A minimal system that has second-order state.
class SecondOrderStateSystem : public LeafSystem<double> {
public:
SecondOrderStateSystem() {
DeclareInputPort(kUseDefaultName, kVectorValued, 1);
DeclareContinuousState(SecondOrderStateVector{},
1 /* num_q */, 1 /* num_v */, 0 /* num_z */);
}
SecondOrderStateVector* x(Context<double>* context) const {
return dynamic_cast<SecondOrderStateVector*>(
&context->get_mutable_continuous_state_vector());
}
protected:
// qdot = 2 * v.
void DoMapVelocityToQDot(
const Context<double>& context,
const Eigen::Ref<const VectorX<double>>& generalized_velocity,
VectorBase<double>* qdot) const override {
qdot->SetAtIndex(0, 2 * generalized_velocity[0]);
}
// v = 1/2 * qdot.
void DoMapQDotToVelocity(
const Context<double>& context,
const Eigen::Ref<const VectorX<double>>& qdot,
VectorBase<double>* generalized_velocity) const override {
generalized_velocity->SetAtIndex(0, 0.5 * qdot[0]);
}
};
// A diagram that has second-order state.
class SecondOrderStateDiagram : public Diagram<double> {
public:
SecondOrderStateDiagram() : Diagram<double>() {
DiagramBuilder<double> builder;
sys1_ = builder.template AddSystem<SecondOrderStateSystem>();
sys1_->set_name("sys1");
sys2_ = builder.template AddSystem<SecondOrderStateSystem>();
sys2_->set_name("sys2");
builder.ExportInput(sys1_->get_input_port(0));
builder.ExportInput(sys2_->get_input_port(0));
builder.BuildInto(this);
}
SecondOrderStateSystem* sys1() { return sys1_; }
SecondOrderStateSystem* sys2() { return sys2_; }
// Returns the state of the given subsystem.
SecondOrderStateVector* x(Context<double>* context,
const SecondOrderStateSystem* subsystem) {
Context<double>& subsystem_context =
GetMutableSubsystemContext(*subsystem, context);
return subsystem->x(&subsystem_context);
}
private:
SecondOrderStateSystem* sys1_ = nullptr;
SecondOrderStateSystem* sys2_ = nullptr;
};
// Tests that MapVelocityToQDot and MapQDotToVelocity recursively invoke
// MapVelocityToQDot (resp. MapQDotToVelocity) on the constituent systems,
// and preserve placewise correspondence.
GTEST_TEST(SecondOrderStateTest, MapVelocityToQDot) {
SecondOrderStateDiagram diagram;
std::unique_ptr<Context<double>> context = diagram.CreateDefaultContext();
diagram.x(context.get(), diagram.sys1())->set_v(13);
diagram.x(context.get(), diagram.sys2())->set_v(17);
BasicVector<double> qdot(2);
const VectorBase<double>& v =
context->get_continuous_state().get_generalized_velocity();
diagram.MapVelocityToQDot(*context, v, &qdot);
// The order of these derivatives is defined to be the same as the order
// subsystems are added.
EXPECT_EQ(qdot[0], 26);
EXPECT_EQ(qdot[1], 34);
// Now map the configuration derivatives back to v.
BasicVector<double> vmutable(v.size());
diagram.MapQDotToVelocity(*context, qdot, &vmutable);
EXPECT_EQ(vmutable[0], 13);
EXPECT_EQ(vmutable[1], 17);
}
// Test for GetSystems.
GTEST_TEST(GetSystemsTest, GetSystems) {
auto diagram = std::make_unique<ExampleDiagram>(2);
EXPECT_EQ((std::vector<const System<double>*>{
diagram->adder0(), diagram->adder1(), diagram->adder2(),
diagram->stateless(),
diagram->integrator0(), diagram->integrator1(),
diagram->sink(),
diagram->kitchen_sink()
}),
diagram->GetSystems());
}
const double kTestPublishPeriod = 19.0;
class TestPublishingSystem final : public LeafSystem<double> {
public:
TestPublishingSystem() {
this->DeclarePeriodicPublishEvent(
kTestPublishPeriod, 0.0, &TestPublishingSystem::HandlePeriodPublish);
// Verify that no periodic discrete updates are registered.
EXPECT_FALSE(this->GetUniquePeriodicDiscreteUpdateAttribute());
}
bool published() const { return published_; }
private:
void HandlePeriodPublish(const Context<double>&) const {
published_ = true;
}
// Recording state through event handlers, like this system does, is an
// anti-pattern, but we do it to simplify testing.
mutable bool published_{false};
};
// A diagram that has discrete state and publishers.
class DiscreteStateDiagram : public Diagram<double> {
public:
DiscreteStateDiagram() : Diagram<double>() {
DiagramBuilder<double> builder;
hold1_ = builder.template AddSystem<ZeroOrderHold<double>>(2.0, kSize);
hold1_->set_name("hold1");
hold2_ = builder.template AddSystem<ZeroOrderHold<double>>(3.0, kSize);
hold2_->set_name("hold2");
publisher_ = builder.template AddSystem<TestPublishingSystem>();
publisher_->set_name("publisher");
builder.ExportInput(hold1_->get_input_port());
builder.ExportInput(hold2_->get_input_port());
builder.BuildInto(this);
EXPECT_FALSE(IsDifferenceEquationSystem());
EXPECT_FALSE(IsDifferentialEquationSystem());
}
ZeroOrderHold<double>* hold1() { return hold1_; }
ZeroOrderHold<double>* hold2() { return hold2_; }
TestPublishingSystem* publisher() { return publisher_; }
private:
const int kSize = 1;
ZeroOrderHold<double>* hold1_ = nullptr;
ZeroOrderHold<double>* hold2_ = nullptr;
TestPublishingSystem* publisher_ = nullptr;
};
class ForcedPublishingSystem : public LeafSystem<double> {
public:
ForcedPublishingSystem() {
this->DeclareForcedPublishEvent(
&ForcedPublishingSystem::PublishHandler);
}
bool published() const { return published_; }
private:
// TODO(15465) When forced event declaration sugar allows for callbacks
// whose result is "assumed to succeed", change this to void return.
EventStatus PublishHandler(const Context<double>& context) const {
published_ = true;
return EventStatus::Succeeded();
}
// Recording state through event handlers, like this system does, is an
// anti-pattern, but we do it to simplify testing.
mutable bool published_{false};
};
// A diagram that consists of only forced publishing systems.
class ForcedPublishingSystemDiagram : public Diagram<double> {
public:
ForcedPublishingSystemDiagram() : Diagram<double>() {
DiagramBuilder<double> builder;
publishing_system_one_ =
builder.template AddSystem<ForcedPublishingSystem>();
publishing_system_two_ =
builder.template AddSystem<ForcedPublishingSystem>();
builder.BuildInto(this);
}
ForcedPublishingSystem* publishing_system_one() const {
return publishing_system_one_;
}
ForcedPublishingSystem* publishing_system_two() const {
return publishing_system_two_;
}
private:
ForcedPublishingSystem* publishing_system_one_{nullptr};
ForcedPublishingSystem* publishing_system_two_{nullptr};
};
class DiscreteStateTest : public ::testing::Test {
public:
void SetUp() override {
context_ = diagram_.CreateDefaultContext();
diagram_.get_input_port(0).FixValue(context_.get(), 17.0);
diagram_.get_input_port(1).FixValue(context_.get(), 23.0);
}
protected:
DiscreteStateDiagram diagram_;
std::unique_ptr<Context<double>> context_;
};
// Tests that the next update time after 0.05 is 2.0.
TEST_F(DiscreteStateTest, CalcNextUpdateTimeHold1) {
context_->SetTime(0.05);
auto events = diagram_.AllocateCompositeEventCollection();
double time = diagram_.CalcNextUpdateTime(*context_, events.get());
EXPECT_EQ(2.0, time);
const auto& subevent_collection =
diagram_.GetSubsystemCompositeEventCollection(
*diagram_.hold1(), *events);
EXPECT_TRUE(subevent_collection.get_discrete_update_events().HasEvents());
}
// Tests that the next update time after 5.1 is 6.0.
TEST_F(DiscreteStateTest, CalcNextUpdateTimeHold2) {
context_->SetTime(5.1);
auto events = diagram_.AllocateCompositeEventCollection();
double time = diagram_.CalcNextUpdateTime(*context_, events.get());
EXPECT_EQ(6.0, time);
{
const auto& subevent_collection =
diagram_.GetSubsystemCompositeEventCollection(
*diagram_.hold2(), *events);
EXPECT_TRUE(subevent_collection.get_discrete_update_events().HasEvents());
}
{
const auto& subevent_collection =
diagram_.GetSubsystemCompositeEventCollection(
*diagram_.hold1(), *events);
EXPECT_TRUE(subevent_collection.get_discrete_update_events().HasEvents());
}
}
// Tests that on the 9-second tick, only hold2 latches its inputs. Then, on
// the 12-second tick, both hold1 and hold2 latch their inputs.
TEST_F(DiscreteStateTest, UpdateDiscreteVariables) {
// Initialize the zero-order holds to different values than their input ports.
Context<double>& ctx1 =
diagram_.GetMutableSubsystemContext(*diagram_.hold1(), context_.get());
ctx1.get_mutable_discrete_state(0)[0] = 1001.0;
Context<double>& ctx2 =
diagram_.GetMutableSubsystemContext(*diagram_.hold2(), context_.get());
ctx2.get_mutable_discrete_state(0)[0] = 1002.0;
// Allocate the discrete variables.
std::unique_ptr<DiscreteValues<double>> updates =
diagram_.AllocateDiscreteVariables();
EXPECT_EQ(updates->get_system_id(), context_->get_system_id());
const DiscreteValues<double>& updates1 =
diagram_
.GetSubsystemDiscreteValues(*diagram_.hold1(), *updates);
const DiscreteValues<double>& updates2 =
diagram_
.GetSubsystemDiscreteValues(*diagram_.hold2(), *updates);
updates->get_mutable_vector(0)[0] = 0.0; // Start with known values.
updates->get_mutable_vector(1)[0] = 0.0;
// Set the time to 8.5, so only hold2 updates.
context_->SetTime(8.5);
// Request the next update time. Note that CalcNextUpdateTime() clears the
// event collection.
auto events = diagram_.AllocateCompositeEventCollection();
double time = diagram_.CalcNextUpdateTime(*context_, events.get());
EXPECT_EQ(9.0, time);
EXPECT_TRUE(events->HasDiscreteUpdateEvents());
// Fast forward to 9.0 sec and do the update.
context_->SetTime(9.0);
EventStatus status = diagram_.CalcDiscreteVariableUpdate(
*context_, events->get_discrete_update_events(), updates.get());
EXPECT_TRUE(status.succeeded());
// Note that non-participating hold1's state should not have been
// copied (if it had been it would be 1001.0).
EXPECT_EQ(0.0, updates1[0]); // Same as we started with.
EXPECT_EQ(23.0, updates2[0]); // Updated.
// Apply the updates to the context_.
diagram_.ApplyDiscreteVariableUpdate(events->get_discrete_update_events(),
updates.get(), context_.get());
EXPECT_EQ(1001.0, ctx1.get_discrete_state(0)[0]);
EXPECT_EQ(23.0, ctx2.get_discrete_state(0)[0]);
// Restore hold2 to its original value.
ctx2.get_mutable_discrete_state(0)[0] = 1002.0;
// Set the time to 11.5, so both hold1 and hold2 update. Note that
// CalcNextUpdateTime() clears the event collection.
context_->SetTime(11.5);
time = diagram_.CalcNextUpdateTime(*context_, events.get());
EXPECT_EQ(12.0, time);
EXPECT_TRUE(events->HasDiscreteUpdateEvents());
// Fast forward to 12.0 sec and do the update again.
context_->SetTime(12.0);
status = diagram_.CalcDiscreteVariableUpdate(
*context_, events->get_discrete_update_events(), updates.get());
EXPECT_TRUE(status.succeeded());
EXPECT_EQ(17.0, updates1[0]);
EXPECT_EQ(23.0, updates2[0]);
}
// Tests that in a Diagram where multiple subsystems have discrete variables,
// an update in one subsystem doesn't cause invalidation in the other. Note
// that although we use the caching system to observe what gets invalidated,
// we are testing for proper Diagram behavior here; we're not testing the
// caching system (which is well-tested elsewhere).
TEST_F(DiscreteStateTest, DiscreteUpdateNotificationsAreLocalized) {
// Initialize the zero-order holds to different values than their input ports.
Context<double>& ctx1 =
diagram_.GetMutableSubsystemContext(*diagram_.hold1(), context_.get());
ctx1.get_mutable_discrete_state(0)[0] = 1001.0;
Context<double>& ctx2 =
diagram_.GetMutableSubsystemContext(*diagram_.hold2(), context_.get());
ctx2.get_mutable_discrete_state(0)[0] = 1002.0;
// Allocate space to hold the updated discrete variables.
std::unique_ptr<DiscreteValues<double>> updates =
diagram_.AllocateDiscreteVariables();
// Hold1 is due for an update at 2s, so only it should be included in the
// next update time event collection.
context_->SetTime(1.5);
// Request the next update time.
auto events = diagram_.AllocateCompositeEventCollection();
double time = diagram_.CalcNextUpdateTime(*context_, events.get());
EXPECT_EQ(2.0, time);
EXPECT_TRUE(events->HasDiscreteUpdateEvents());
const auto& discrete_events = events->get_discrete_update_events();
auto num_notifications = [](const Context<double>& context) {
return context.get_tracker(SystemBase::xd_ticket())
.num_notifications_received();
};
const int64_t notifications_1 = num_notifications(ctx1);
const int64_t notifications_2 = num_notifications(ctx2);
// Fast forward to 2.0 sec and collect the update.
context_->SetTime(2.0);
const EventStatus status = diagram_.CalcDiscreteVariableUpdate(
*context_, discrete_events, updates.get());
EXPECT_TRUE(status.succeeded());
// Of course nothing should have been notified since nothing's changed yet.
EXPECT_EQ(num_notifications(ctx1), notifications_1);
EXPECT_EQ(num_notifications(ctx2), notifications_2);
// Selectively apply the update; only hold1 should get notified.
diagram_.ApplyDiscreteVariableUpdate(discrete_events, updates.get(),
context_.get());
// Sanity check that the update did occur!
EXPECT_EQ(17.0, ctx1.get_discrete_state(0)[0]);
EXPECT_EQ(1002.0, ctx2.get_discrete_state(0)[0]);
EXPECT_EQ(num_notifications(ctx1), notifications_1 + 1);
EXPECT_EQ(num_notifications(ctx2), notifications_2);
// Now apply the updates the dumb way. Everyone gets notified.
context_->get_mutable_discrete_state().SetFrom(*updates);
EXPECT_EQ(num_notifications(ctx1), notifications_1 + 2);
EXPECT_EQ(num_notifications(ctx2), notifications_2 + 1);
}
// A system with a single discrete variable that is initialized to the
// system's id as supplied at construction. A periodic update modifies the
// state in a way that lets us see whether the framework passed in the right
// state value to the handler.
class SystemWithDiscreteState : public LeafSystem<double> {
public:
SystemWithDiscreteState(int id, double update_period) : id_(id) {
// Just one discrete variable, initialized to id.
DeclareDiscreteState(Vector1d(id_));
if (update_period > 0.0) {
DeclarePeriodicDiscreteUpdateEvent(
update_period, 0,
&SystemWithDiscreteState::AddTimeToDiscreteVariable);
}
DeclarePerStepDiscreteUpdateEvent(
&SystemWithDiscreteState::IncrementCounter);
}
int get_id() const { return id_; }
int counter() const { return counter_; }
private:
// Discrete state is set to input state value + time. We expect that the
// initial value for discrete_state is the same as the value in context.
void AddTimeToDiscreteVariable(
const Context<double>& context,
DiscreteValues<double>* discrete_state) const {
ASSERT_EQ((*discrete_state)[0], context.get_discrete_state(0)[0]);
(*discrete_state)[0] += context.get_time();
}
EventStatus IncrementCounter(
const Context<double>&, DiscreteValues<double>*) const {
++counter_;
return EventStatus::Succeeded();
}
const int id_;
mutable int counter_{0};
};
class TwoDiscreteSystemDiagram : public Diagram<double> {
public:
enum { kSys1Id = 1, kSys2Id = 2 };
TwoDiscreteSystemDiagram() : Diagram<double>() {
DiagramBuilder<double> builder;
sys1_ = builder.template AddSystem<SystemWithDiscreteState>(kSys1Id, 2.);
sys2_ = builder.template AddSystem<SystemWithDiscreteState>(kSys2Id, 3.);
builder.BuildInto(this);
}
const SystemWithDiscreteState& get_sys(int i) const {
DRAKE_DEMAND(i == kSys1Id || i == kSys2Id);
return i == kSys1Id ? *sys1_ : *sys2_;
}
private:
SystemWithDiscreteState* sys1_{nullptr};
SystemWithDiscreteState* sys2_{nullptr};
};
// Check that a flat Diagram correctly aggregates the number of discrete
// state groups from its subsystems. Separately we'll check that nested
// Diagrams recurse properly to count up everything in the tree.
GTEST_TEST(DiscreteStateDiagramTest, NumDiscreteStateGroups) {
DiagramBuilder<double> builder;
builder.template AddSystem<SystemWithDiscreteState>(1, 2.);
const auto diagram = builder.Build();
const auto context = diagram->CreateDefaultContext();
EXPECT_EQ(diagram->num_discrete_state_groups(),
context->num_discrete_state_groups());
}
GTEST_TEST(DiscreteStateDiagramTest, IsDifferenceEquationSystem) {
// Two unique periods, two state groups.
DiagramBuilder<double> builder;
builder.template AddSystem<SystemWithDiscreteState>(1, 2.);
builder.template AddSystem<SystemWithDiscreteState>(2, 3.);
const auto two_period_diagram = builder.Build();
EXPECT_FALSE(two_period_diagram->IsDifferenceEquationSystem());
// One period, one discrete state group.
const double period = 0.1;
DiagramBuilder<double> builder2;
builder2.template AddSystem<SystemWithDiscreteState>(1, period);
const auto one_period_diagram = builder2.Build();
double test_period = -3.94;
EXPECT_TRUE(one_period_diagram->IsDifferenceEquationSystem(&test_period));
EXPECT_EQ(test_period, period);
// One unique period, but two discrete state groups.
DiagramBuilder<double> builder3;
builder3.template AddSystem<SystemWithDiscreteState>(1, period);
builder3.template AddSystem<SystemWithDiscreteState>(2, period);
const auto one_period_two_state_diagram = builder3.Build();
EXPECT_FALSE(one_period_two_state_diagram->IsDifferenceEquationSystem());
}
// Tests CalcDiscreteVariableUpdate() when there are multiple subsystems and
// only one has an event to handle (call that the "participating subsystem"). We
// want to verify that only the participating subsystem's State gets copied,
// that the copied value matches the current value in the context, and
// that the update gets performed properly. We also check that it works properly
// when multiple subsystems have events to handle.
GTEST_TEST(DiscreteStateDiagramTest, CalcDiscreteVariableUpdate) {
TwoDiscreteSystemDiagram diagram;
const int kSys1Id = TwoDiscreteSystemDiagram::kSys1Id;
const int kSys2Id = TwoDiscreteSystemDiagram::kSys2Id;
auto context = diagram.CreateDefaultContext();
context->SetTime(1.5);
// The discrete states should be initialized to their ids.
EXPECT_EQ(context->get_discrete_state(0)[0], kSys1Id);
EXPECT_EQ(context->get_discrete_state(1)[0], kSys2Id);
// First action time should be 2 sec, and only sys1 will be updating.
auto events = diagram.AllocateCompositeEventCollection();
EXPECT_EQ(diagram.CalcNextUpdateTime(*context, events.get()), 2.);
{
const auto& subevent_collection =
diagram.GetSubsystemCompositeEventCollection(diagram.get_sys(kSys1Id),
*events);
EXPECT_TRUE(subevent_collection.get_discrete_update_events().HasEvents());
}
{
const auto& subevent_collection =
diagram.GetSubsystemCompositeEventCollection(diagram.get_sys(kSys2Id),
*events);
EXPECT_FALSE(subevent_collection.get_discrete_update_events().HasEvents());
}
// Creates a temp state and sets it to some recognizable values.
std::unique_ptr<DiscreteValues<double>> x_buf =
diagram.AllocateDiscreteVariables();
x_buf->get_mutable_vector(0)[0] = 98.0;
x_buf->get_mutable_vector(1)[0] = 99.0;
// Fast forward to the event time, and record it for the test below.
double time = 2.0;
context->SetTime(time);
EventStatus status = diagram.CalcDiscreteVariableUpdate(
*context, events->get_discrete_update_events(), x_buf.get());
EXPECT_TRUE(status.succeeded());
// The non-participating sys2 state shouldn't have been copied (if it had
// it would now be 2). sys1's state should have been copied, replacing the
// 98 with a 1, then updated by adding time.
EXPECT_EQ(x_buf->get_vector(0)[0], kSys1Id + time); // Updated.
EXPECT_EQ(x_buf->get_vector(1)[0], 99.0); // Unchanged.
// Swaps in the new state, and the discrete data for sys1 should be updated.
diagram.ApplyDiscreteVariableUpdate(events->get_discrete_update_events(),
x_buf.get(), context.get());
EXPECT_EQ(context->get_discrete_state(0)[0], kSys1Id + time); // == 3
EXPECT_EQ(context->get_discrete_state(1)[0], kSys2Id);
// Sets time to 5.5, both systems should be updating at 6 sec. Note that
// CalcNextUpdateTime() clears the event collection.
context->SetTime(5.5);
EXPECT_EQ(diagram.CalcNextUpdateTime(*context, events.get()), 6.);
for (int i : {kSys1Id, kSys2Id}) {
const auto& subevent_collection =
diagram.GetSubsystemCompositeEventCollection(diagram.get_sys(i),
*events);
EXPECT_TRUE(subevent_collection.get_discrete_update_events().HasEvents());
}
// Fast forward to the new event time, and record it for the tests below.
time = 6.0;
context->SetTime(time);
status = diagram.CalcDiscreteVariableUpdate(
*context, events->get_discrete_update_events(), x_buf.get());
EXPECT_TRUE(status.succeeded());
// Both sys1 and sys2's discrete data should be updated.
diagram.ApplyDiscreteVariableUpdate(events->get_discrete_update_events(),
x_buf.get(), context.get());
EXPECT_EQ(context->get_discrete_state(0)[0], kSys1Id + 2 + time);
EXPECT_EQ(context->get_discrete_state(1)[0], kSys2Id + time);
}
// Tests that EvalUniquePeriodicDiscreteUpdate() rejects systems that don't
// have exactly one periodic timing that triggers discrete updates.
GTEST_TEST(DiscreteStateDiagramTest, EvalUniquePeriodicDiscreteUpdateErrors) {
TestPublishingSystem no_discrete_updates;
auto no_discrete_updates_context = no_discrete_updates.CreateDefaultContext();
DRAKE_EXPECT_THROWS_MESSAGE(
no_discrete_updates.EvalUniquePeriodicDiscreteUpdate(
*no_discrete_updates_context),
".*no periodic discrete update events.*");
// Two unique periods.
DiagramBuilder<double> two_period_builder;
two_period_builder.template AddSystem<SystemWithDiscreteState>(1, 2.0);
two_period_builder.template AddSystem<SystemWithDiscreteState>(2, 3.0);
const auto two_period_diagram = two_period_builder.Build();
auto two_period_context = two_period_diagram->CreateDefaultContext();
DRAKE_EXPECT_THROWS_MESSAGE(
two_period_diagram->EvalUniquePeriodicDiscreteUpdate(*two_period_context),
".*more than one periodic timing.*");
}
// Tests that EvalUniquePeriodicDiscreteUpdate()
// - properly copies the old discrete state before calling handlers,
// - executes _all_ discrete update events triggered by the unique timing,
// - ignores non-periodic discrete updates.
GTEST_TEST(DiscreteStateDiagramTest, EvalUniquePeriodicDiscreteUpdate) {
// Two discrete variables in different subsystems, initialized to 7 and 8,
// with periodic discrete updates that have identical period 5s. There is
// also a per-step discrete update event in each system whose handler
// increments a counter if triggered.
DiagramBuilder<double> builder;
auto* system0 = builder.template AddSystem<SystemWithDiscreteState>(7, 5.0);
auto* system1 = builder.template AddSystem<SystemWithDiscreteState>(8, 5.0);
// The third system doesn't have a periodic update at all.
auto* system2 = builder.template AddSystem<SystemWithDiscreteState>(9, 0.0);
const auto two_discretes = builder.Build();
auto context = two_discretes->CreateDefaultContext();
EXPECT_EQ(context->get_discrete_state(0)[0], 7.0);
EXPECT_EQ(context->get_discrete_state(1)[0], 8.0);
EXPECT_EQ(context->get_discrete_state(2)[0], 9.0);
// The update methods add time to the variable values.
context->SetTime(4.);
const DiscreteValues<double>& result =
two_discretes->EvalUniquePeriodicDiscreteUpdate(*context);
EXPECT_EQ(result.value(0)[0], 11.0); // updated
EXPECT_EQ(result.value(1)[0], 12.0); // updated
EXPECT_EQ(result.value(2)[0], 9.0); // just copied
// Emphasize that the original Context discrete state remains unchanged.
EXPECT_EQ(context->get_discrete_state(0)[0], 7.0);
EXPECT_EQ(context->get_discrete_state(1)[0], 8.0);
EXPECT_EQ(context->get_discrete_state(2)[0], 9.0);
// Verify that the per-step discrete update events didn't get executed at all.
EXPECT_EQ(system0->counter(), 0);
EXPECT_EQ(system1->counter(), 0);
EXPECT_EQ(system2->counter(), 0);
}
// Tests that a publish action is taken at 19 sec.
TEST_F(DiscreteStateTest, Publish) {
context_->SetTime(18.5);
auto events = diagram_.AllocateCompositeEventCollection();
double time = diagram_.CalcNextUpdateTime(*context_, events.get());
EXPECT_EQ(19.0, time);
EXPECT_TRUE(events->HasPublishEvents());
// Fast forward to 19.0 sec and do the publish.
EXPECT_EQ(false, diagram_.publisher()->published());
context_->SetTime(19.0);
const EventStatus status =
diagram_.Publish(*context_, events->get_publish_events());
EXPECT_TRUE(status.succeeded());
// Check that publication occurred.
EXPECT_EQ(true, diagram_.publisher()->published());
}
class ForcedPublishingSystemDiagramTest : public ::testing::Test {
public:
void SetUp() override {
context_ = diagram_.CreateDefaultContext();
}
protected:
ForcedPublishingSystemDiagram diagram_;
std::unique_ptr<Context<double>> context_;
};
GTEST_TEST(ContinuousStateDiagramTest, IsDifferentialEquationSystem) {
DiagramBuilder<double> builder;
builder.template AddSystem<Integrator>(1);
builder.template AddSystem<Integrator>(2);
const auto two_integrator_diagram = builder.Build();
EXPECT_TRUE(two_integrator_diagram->IsDifferentialEquationSystem());
DiagramBuilder<double> builder2;
builder2.template AddSystem<Integrator>(1);
builder2.template AddSystem<SystemWithDiscreteState>(1, 0.1);
const auto mixed_discrete_continuous_diagram = builder2.Build();
EXPECT_FALSE(
mixed_discrete_continuous_diagram->IsDifferentialEquationSystem());
}
// Tests that a forced publish is processed through the event handler.
TEST_F(ForcedPublishingSystemDiagramTest, ForcedPublish) {
auto* forced_publishing_system_one = diagram_.publishing_system_one();
auto* forced_publishing_system_two = diagram_.publishing_system_two();
EXPECT_FALSE(forced_publishing_system_one->published());
EXPECT_FALSE(forced_publishing_system_two->published());
diagram_.ForcedPublish(*context_);
EXPECT_TRUE(forced_publishing_system_one->published());
EXPECT_TRUE(forced_publishing_system_two->published());
}
class SystemWithAbstractState : public LeafSystem<double> {
public:
SystemWithAbstractState(int id, double update_period) : id_(id) {
DeclarePeriodicUnrestrictedUpdateEvent(
update_period, 0, &SystemWithAbstractState::CalcUnrestrictedUpdate);
DeclareAbstractState(Value<double>(id_));
// Verify that no periodic discrete updates are registered.
EXPECT_FALSE(this->GetUniquePeriodicDiscreteUpdateAttribute());
}
~SystemWithAbstractState() override {}
int get_id() const { return id_; }
private:
// Abstract state is set to input state value + time.
void CalcUnrestrictedUpdate(
const Context<double>& context,
State<double>* state) const {
double& state_num = state->get_mutable_abstract_state()
.get_mutable_value(0)
.get_mutable_value<double>();
// The initial value for state should match what's currently in the
// context.
ASSERT_EQ(state_num, context.get_abstract_state<double>(0));
state_num += context.get_time();
}
int id_{0};
};
class AbstractStateDiagram : public Diagram<double> {
public:
enum { kSys1Id = 1, kSys2Id = 2 };
AbstractStateDiagram() : Diagram<double>() {
DiagramBuilder<double> builder;
sys1_ = builder.template AddSystem<SystemWithAbstractState>(kSys1Id, 2.);
sys2_ = builder.template AddSystem<SystemWithAbstractState>(kSys2Id, 3.);
builder.BuildInto(this);
}
const SystemWithAbstractState& get_sys(int i) const {
DRAKE_DEMAND(i == kSys1Id || i == kSys2Id);
return i == kSys1Id ? *sys1_ : *sys2_;
}
SystemWithAbstractState* get_mutable_sys1() { return sys1_; }
SystemWithAbstractState* get_mutable_sys2() { return sys2_; }
private:
SystemWithAbstractState* sys1_{nullptr};
SystemWithAbstractState* sys2_{nullptr};
};
class AbstractStateDiagramTest : public ::testing::Test {
protected:
void SetUp() override { context_ = diagram_.CreateDefaultContext(); }
double get_sys1_abstract_data_as_double() {
const Context<double>& sys_context =
diagram_.GetSubsystemContext(*diagram_.get_mutable_sys1(), *context_);
return sys_context.get_abstract_state<double>(0);
}
double get_sys2_abstract_data_as_double() {
const Context<double>& sys_context =
diagram_.GetSubsystemContext(*diagram_.get_mutable_sys2(), *context_);
return sys_context.get_abstract_state<double>(0);
}
AbstractStateDiagram diagram_;
std::unique_ptr<Context<double>> context_;
};
// Check that we count the abstract states correctly for a flat Diagram.
// DiagramOfDiagramsTest below checks nested diagrams.
TEST_F(AbstractStateDiagramTest, NumAbstractStates) {
EXPECT_EQ(diagram_.num_abstract_states(), context_->num_abstract_states());
}
// Tests CalcUnrestrictedUpdate() when there are multiple subsystems and only
// one has an event to handle (call that the "participating subsystem"). We want
// to verify that only the participating subsystem's State gets copied, that the
// copied value matches the current value in the context, and that
// the update gets performed properly. We also check that it works properly
// when multiple subsystems have events to handle.
TEST_F(AbstractStateDiagramTest, CalcUnrestrictedUpdate) {
const int kSys1Id = AbstractStateDiagram::kSys1Id;
const int kSys2Id = AbstractStateDiagram::kSys2Id;
context_->SetTime(1.5);
// The abstract data should be initialized to their ids.
EXPECT_EQ(get_sys1_abstract_data_as_double(), kSys1Id);
EXPECT_EQ(get_sys2_abstract_data_as_double(), kSys2Id);
// First action time should be 2 sec, and only sys1 will be updating.
auto events = diagram_.AllocateCompositeEventCollection();
EXPECT_EQ(diagram_.CalcNextUpdateTime(*context_, events.get()), 2.);
{
const auto& subevent_collection =
diagram_.GetSubsystemCompositeEventCollection(
diagram_.get_sys(kSys1Id), *events);
EXPECT_TRUE(
subevent_collection.get_unrestricted_update_events().HasEvents());
}
{
const auto& subevent_collection =
diagram_.GetSubsystemCompositeEventCollection(
diagram_.get_sys(kSys2Id), *events);
EXPECT_FALSE(
subevent_collection.get_unrestricted_update_events().HasEvents());
}
// Creates a temp state and sets it to some recognizable values.
std::unique_ptr<State<double>> x_buf = context_->CloneState();
x_buf->get_mutable_abstract_state<double>(0) = 98.0;
x_buf->get_mutable_abstract_state<double>(1) = 99.0;
double time = 2.0;
context_->SetTime(time);
EventStatus status = diagram_.CalcUnrestrictedUpdate(
*context_, events->get_unrestricted_update_events(), x_buf.get());
EXPECT_TRUE(status.succeeded());
// The non-participating sys2 state shouldn't have been copied (if it had
// it would now be kSys2Id). sys1's state should have been copied, replacing
// the 98 with kSys1Id, then updated by adding time.
EXPECT_EQ(x_buf->get_abstract_state<double>(0), kSys1Id + time); // Updated.
EXPECT_EQ(x_buf->get_abstract_state<double>(1), 99.0); // Unchanged.
// The abstract data in the current context should be the same as before.
EXPECT_EQ(get_sys1_abstract_data_as_double(), kSys1Id);
EXPECT_EQ(get_sys2_abstract_data_as_double(), kSys2Id);
// Swaps in the new state, and the abstract data for sys0 should be updated.
diagram_.ApplyUnrestrictedUpdate(events->get_unrestricted_update_events(),
x_buf.get(), context_.get());
EXPECT_EQ(get_sys1_abstract_data_as_double(), kSys1Id + time); // == 3
EXPECT_EQ(get_sys2_abstract_data_as_double(), kSys2Id);
// Sets time to 5.5, both systems should be updating at 6 sec. Note that
// CalcNextUpdateTime() clears the event collection.
context_->SetTime(5.5);
EXPECT_EQ(diagram_.CalcNextUpdateTime(*context_, events.get()), 6.);
for (int i : {kSys1Id, kSys2Id}) {
const auto& subevent_collection =
diagram_.GetSubsystemCompositeEventCollection(
diagram_.get_sys(i), *events);
EXPECT_TRUE(
subevent_collection.get_unrestricted_update_events().HasEvents());
}
time = 6.0;
context_->SetTime(time);
status = diagram_.CalcUnrestrictedUpdate(
*context_, events->get_unrestricted_update_events(), x_buf.get());
EXPECT_TRUE(status.succeeded());
// Both sys1 and sys2's abstract data should be updated.
diagram_.ApplyUnrestrictedUpdate(events->get_unrestricted_update_events(),
x_buf.get(), context_.get());
EXPECT_EQ(get_sys1_abstract_data_as_double(), kSys1Id + 2.0 + time);
EXPECT_EQ(get_sys2_abstract_data_as_double(), kSys2Id + time);
}
// Tests that in a Diagram where multiple subsystems have abstract variables,
// an unrestricted update in one subsystem doesn't invalidate the other.
// Note that although we use the caching system to observe what gets
// invalidated, we are testing for proper Diagram behavior here; we're not
// testing the caching system.
TEST_F(AbstractStateDiagramTest, UnrestrictedUpdateNotificationsAreLocalized) {
const int kSys1Id = AbstractStateDiagram::kSys1Id;
const int kSys2Id = AbstractStateDiagram::kSys2Id;
Context<double>& ctx1 = diagram_.GetMutableSubsystemContext(
diagram_.get_sys(kSys1Id), context_.get());
Context<double>& ctx2 = diagram_.GetMutableSubsystemContext(
diagram_.get_sys(kSys2Id), context_.get());
// Allocate space to hold the updated state
std::unique_ptr<State<double>> updates = context_->CloneState();
// sys1 is due for an update at 2s, so only it should be included in the
// next update time event collection.
context_->SetTime(1.5);
// Request the next update time.
auto events = diagram_.AllocateCompositeEventCollection();
const double next_time = diagram_.CalcNextUpdateTime(*context_, events.get());
EXPECT_EQ(2.0, next_time);
EXPECT_TRUE(events->HasUnrestrictedUpdateEvents());
const auto& unrestricted_events = events->get_unrestricted_update_events();
// Unrestricted update will notify xc, xd, xa and composite x. We'll count
// xa notifications as representative. (We're not trying to prove here that
// notifications are sent correctly, just that notifications are *not* sent
// to uninvolved subsystems.)
auto num_notifications = [](const Context<double>& context) {
return context.get_tracker(SystemBase::xa_ticket())
.num_notifications_received();
};
const int64_t notifications_1 = num_notifications(ctx1);
const int64_t notifications_2 = num_notifications(ctx2);
// The abstract data should be initialized to their ids.
EXPECT_EQ(get_sys1_abstract_data_as_double(), kSys1Id);
EXPECT_EQ(get_sys2_abstract_data_as_double(), kSys2Id);
// Fast forward to 2.0 sec and collect the update.
context_->SetTime(next_time);
const EventStatus status = diagram_.CalcUnrestrictedUpdate(
*context_, unrestricted_events, updates.get());
EXPECT_TRUE(status.succeeded());
// Of course nothing should have been notified since nothing's changed yet.
EXPECT_EQ(num_notifications(ctx1), notifications_1);
EXPECT_EQ(num_notifications(ctx2), notifications_2);
// Selectively apply the update; only hold1 should get notified.
diagram_.ApplyUnrestrictedUpdate(unrestricted_events, updates.get(),
context_.get());
// Sanity check that the update actually occurred -- should have added time
// to sys1's abstract id.
EXPECT_EQ(get_sys1_abstract_data_as_double(), kSys1Id + next_time);
EXPECT_EQ(get_sys2_abstract_data_as_double(), kSys2Id);
EXPECT_EQ(num_notifications(ctx1), notifications_1 + 1);
EXPECT_EQ(num_notifications(ctx2), notifications_2);
// Now apply the updates the dumb way. Everyone gets notified.
context_->get_mutable_state().SetFrom(*updates);
EXPECT_EQ(num_notifications(ctx1), notifications_1 + 2);
EXPECT_EQ(num_notifications(ctx2), notifications_2 + 1);
}
/* Test diagram. Top level diagram (big_diagram) has 4 components:
a constant vector source, diagram0, int2, and diagram1. diagram0 has int0
and int1, and diagram1 has int3. Here's a picture:
+---------------------- big_diagram ----------------------+
| |
| +---- diagram0 ----+ |
| | | |
| | +-----------+ | |
| | | | | |
| +------|---> int0 +------->
| | | | | | |
| | | +-----------+ | |
| | | | |
| | | +-----------+ | |
| | | | | | |
| +------|---> int1 +------->
| | | | | | |
| | | +-----------+ | |
| +------------------+ | | | |
| | | | +------------------+ |
| | ConstantVector +--->| |
| | | | +-----------+ |
| +------------------+ | | | |
| +----------> int2 +------->
| | | | |
| | +-----------+ |
| | |
| | +---- diagram1 ----+ |
| | | | |
| | | +-----------+ | |
| | | | | | |
| +------|---> int3 +------->
| | | | | |
| | +-----------+ | |
| | | |
| +------------------+ |
| |
+---------------------------------------------------------+
*/
class NestedDiagramContextTest : public ::testing::Test {
protected:
void SetUp() override {
DiagramBuilder<double> big_diagram_builder;
integrator2_ = big_diagram_builder.AddSystem<Integrator<double>>(1);
integrator2_->set_name("int2");
{
DiagramBuilder<double> builder;
integrator0_ = builder.AddSystem<Integrator<double>>(1);
integrator0_->set_name("int0");
integrator1_ = builder.AddSystem<Integrator<double>>(1);
integrator1_->set_name("int1");
builder.ExportOutput(integrator0_->get_output_port());
builder.ExportOutput(integrator1_->get_output_port());
builder.ExportInput(integrator0_->get_input_port());
builder.ExportInput(integrator1_->get_input_port());
diagram0_ = big_diagram_builder.AddSystem(builder.Build());
diagram0_->set_name("diagram0");
}
{
DiagramBuilder<double> builder;
integrator3_ = builder.AddSystem<Integrator<double>>(1);
integrator3_->set_name("int3");
builder.ExportOutput(integrator3_->get_output_port());
builder.ExportInput(integrator3_->get_input_port());
diagram1_ = big_diagram_builder.AddSystem(builder.Build());
diagram1_->set_name("diagram1");
}
big_diagram_builder.ExportOutput(diagram0_->get_output_port(0));
big_diagram_builder.ExportOutput(diagram0_->get_output_port(1));
big_diagram_builder.ExportOutput(integrator2_->get_output_port());
big_diagram_builder.ExportOutput(diagram1_->get_output_port(0));
auto src = big_diagram_builder.AddSystem<ConstantVectorSource<double>>(1);
src->set_name("constant");
big_diagram_builder.Connect(src->get_output_port(),
integrator2_->get_input_port());
big_diagram_builder.Connect(src->get_output_port(),
diagram0_->get_input_port(0));
big_diagram_builder.Connect(src->get_output_port(),
diagram0_->get_input_port(1));
big_diagram_builder.Connect(src->get_output_port(),
diagram1_->get_input_port(0));
big_diagram_ = big_diagram_builder.Build();
big_diagram_->set_name("big_diagram");
big_context_ = big_diagram_->CreateDefaultContext();
big_output_ = big_diagram_->AllocateOutput();
// Make sure caching is on locally, even if it is off by default.
// Do not remove this line; we want to show that these tests function
// correctly with caching on. It is easier to pass with caching off!
big_context_->EnableCaching();
}
Integrator<double>* integrator0_;
Integrator<double>* integrator1_;
Integrator<double>* integrator2_;
Integrator<double>* integrator3_;
Diagram<double>* diagram0_;
Diagram<double>* diagram1_;
std::unique_ptr<Diagram<double>> big_diagram_;
std::unique_ptr<Context<double>> big_context_;
std::unique_ptr<SystemOutput<double>> big_output_;
};
// Check functioning and error checking of each method for extracting
// subcontexts.
TEST_F(NestedDiagramContextTest, GetSubsystemContext) {
big_diagram_->CalcOutput(*big_context_, big_output_.get());
EXPECT_EQ(big_output_->get_vector_data(0)->GetAtIndex(0), 0);
EXPECT_EQ(big_output_->get_vector_data(1)->GetAtIndex(0), 0);
EXPECT_EQ(big_output_->get_vector_data(2)->GetAtIndex(0), 0);
EXPECT_EQ(big_output_->get_vector_data(3)->GetAtIndex(0), 0);
big_diagram_->GetMutableSubsystemContext(*integrator0_, big_context_.get())
.get_mutable_continuous_state_vector()[0] = 1;
big_diagram_->GetMutableSubsystemContext(*integrator1_, big_context_.get())
.get_mutable_continuous_state_vector()[0] = 2;
big_diagram_->GetMutableSubsystemContext(*integrator2_, big_context_.get())
.get_mutable_continuous_state_vector()[0] = 3;
big_diagram_->GetMutableSubsystemContext(*integrator3_, big_context_.get())
.get_mutable_continuous_state_vector()[0] = 4;
// Checks states.
EXPECT_EQ(big_diagram_->GetSubsystemContext(*integrator0_, *big_context_)
.get_continuous_state_vector()[0],
1);
EXPECT_EQ(big_diagram_->GetSubsystemContext(*integrator1_, *big_context_)
.get_continuous_state_vector()[0],
2);
EXPECT_EQ(big_diagram_->GetSubsystemContext(*integrator2_, *big_context_)
.get_continuous_state_vector()[0],
3);
EXPECT_EQ(big_diagram_->GetSubsystemContext(*integrator3_, *big_context_)
.get_continuous_state_vector()[0],
4);
// Checks output.
big_diagram_->CalcOutput(*big_context_, big_output_.get());
EXPECT_EQ(big_output_->get_vector_data(0)->GetAtIndex(0), 1);
EXPECT_EQ(big_output_->get_vector_data(1)->GetAtIndex(0), 2);
EXPECT_EQ(big_output_->get_vector_data(2)->GetAtIndex(0), 3);
EXPECT_EQ(big_output_->get_vector_data(3)->GetAtIndex(0), 4);
// Starting with the root context, the subsystems should be able to find
// their own contexts.
// Integrator 1 is a child of a child.
EXPECT_EQ(integrator1_->GetMyContextFromRoot(*big_context_)
.get_continuous_state_vector()[0],
2);
// Integrator 2 is a direct child.
EXPECT_EQ(integrator2_->GetMyContextFromRoot(*big_context_)
.get_continuous_state_vector()[0],
3);
// Extract a sub-diagram context.
Context<double>& diagram0_context =
diagram0_->GetMyMutableContextFromRoot(&*big_context_);
// This should fail because this context is not a root context.
DRAKE_EXPECT_THROWS_MESSAGE(
integrator1_->GetMyContextFromRoot(diagram0_context),
".*context must be a root context.*");
// Should fail because integrator3 is not in diagram0.
DRAKE_EXPECT_THROWS_MESSAGE(
diagram0_->GetSubsystemContext(*integrator3_, diagram0_context),
".*Integrator.*int3.*not contained in.*Diagram.*diagram0.*");
// Modify through the sub-Diagram context, then read back from root.
Context<double>& integrator1_context =
diagram0_->GetMutableSubsystemContext(*integrator1_, &diagram0_context);
integrator1_context.get_mutable_continuous_state_vector()[0] = 17.;
EXPECT_EQ(integrator1_->GetMyContextFromRoot(*big_context_)
.get_continuous_state_vector()[0],
17.);
}
// Sets the continuous state of all the integrators through
// GetMutableSubsystemState(), and check that they are correctly set.
TEST_F(NestedDiagramContextTest, GetSubsystemState) {
big_diagram_->CalcOutput(*big_context_, big_output_.get());
EXPECT_EQ(big_output_->get_vector_data(0)->GetAtIndex(0), 0);
EXPECT_EQ(big_output_->get_vector_data(1)->GetAtIndex(0), 0);
EXPECT_EQ(big_output_->get_vector_data(2)->GetAtIndex(0), 0);
EXPECT_EQ(big_output_->get_vector_data(3)->GetAtIndex(0), 0);
State<double>& big_state = big_context_->get_mutable_state();
big_diagram_
->GetMutableSubsystemState(*integrator0_, &big_state)
.get_mutable_continuous_state()
.get_mutable_vector()[0] = 1;
big_diagram_
->GetMutableSubsystemState(*integrator1_, &big_state)
.get_mutable_continuous_state()
.get_mutable_vector()[0] = 2;
big_diagram_
->GetMutableSubsystemState(*integrator2_, &big_state)
.get_mutable_continuous_state()
.get_mutable_vector()[0] = 3;
big_diagram_
->GetMutableSubsystemState(*integrator3_, &big_state)
.get_mutable_continuous_state()
.get_mutable_vector()[0] = 4;
// Checks state.
EXPECT_EQ(big_diagram_->GetSubsystemState(*integrator0_, big_state)
.get_continuous_state().get_vector()[0],
1);
EXPECT_EQ(big_diagram_->GetSubsystemState(*integrator1_, big_state)
.get_continuous_state().get_vector()[0],
2);
EXPECT_EQ(big_diagram_->GetSubsystemState(*integrator2_, big_state)
.get_continuous_state().get_vector()[0],
3);
EXPECT_EQ(big_diagram_->GetSubsystemState(*integrator3_, big_state)
.get_continuous_state().get_vector()[0],
4);
// Checks output.
big_diagram_->CalcOutput(*big_context_, big_output_.get());
EXPECT_EQ(big_output_->get_vector_data(0)->GetAtIndex(0), 1);
EXPECT_EQ(big_output_->get_vector_data(1)->GetAtIndex(0), 2);
EXPECT_EQ(big_output_->get_vector_data(2)->GetAtIndex(0), 3);
EXPECT_EQ(big_output_->get_vector_data(3)->GetAtIndex(0), 4);
}
// Tests that ContextBase methods for affecting cache behavior propagate
// all the way through a nested Diagram. Since leaf output ports have cache
// entries in their corresponding subcontext, we'll pick one at the bottom
// and check its behavior.
TEST_F(NestedDiagramContextTest, CachingChangePropagation) {
const Context<double>& diagram1_subcontext =
big_diagram_->GetSubsystemContext(*diagram1_, *big_context_);
const Context<double>& integrator3_subcontext =
diagram1_->GetSubsystemContext(*integrator3_, diagram1_subcontext);
const OutputPort<double>& integrator3_output =
integrator3_->get_output_port();
auto& integrator3_leaf_output =
dynamic_cast<const LeafOutputPort<double>&>(integrator3_output);
auto& cache_entry = integrator3_leaf_output.cache_entry();
EXPECT_FALSE(cache_entry.is_cache_entry_disabled(integrator3_subcontext));
EXPECT_TRUE(cache_entry.is_out_of_date(integrator3_subcontext));
big_context_->DisableCaching();
EXPECT_TRUE(cache_entry.is_cache_entry_disabled(integrator3_subcontext));
EXPECT_TRUE(cache_entry.is_out_of_date(integrator3_subcontext));
big_context_->EnableCaching();
EXPECT_FALSE(cache_entry.is_cache_entry_disabled(integrator3_subcontext));
EXPECT_TRUE(cache_entry.is_out_of_date(integrator3_subcontext));
// Bring the cache entry up to date.
cache_entry.EvalAbstract(integrator3_subcontext);
EXPECT_FALSE(cache_entry.is_out_of_date(integrator3_subcontext));
big_context_->SetAllCacheEntriesOutOfDate();
EXPECT_TRUE(cache_entry.is_out_of_date(integrator3_subcontext));
}
/* Check that changes made directly to a subcontext still affect the
parent Diagram's behavior properly. Also, time and accuracy must be identical
in every subcontext of a Context tree. They are only permitted to change at the
root so they can be properly propagated down.
+-----------------------------------------------------+
| |
| +------------+ +-----------+ |
| | | | | |
u | u0 | | y0 u1 | | y1 | y (=x1)
Fixed ----------> integ0 +-------------> integ1 +-------->
value | | | | | |
| | x0 | | x1 | |
| +------------+ +-----------+ |
| | xdot={u0,u1,u2}
| +------------+ +-------->
| | | |
| u2 | | y2 |
| Fixed -------> integ2 +------> |
| value | | |
| | x2 | |
| +------------+ |
| |
| diagram x={x0,x1,x2} |
| xdot={u0,u1,u2} |
+-----------------------------------------------------+
Note that integ2's input port is invisible to the diagram, but a value change
to that hidden port should invalidate the diagram's composite derivative
calculation. */
GTEST_TEST(MutateSubcontextTest, DiagramRecalculatesOnSubcontextChange) {
DiagramBuilder<double> builder;
auto integ0 = builder.AddSystem<Integrator>(1); // (xdot = u; y = x)
auto integ1 = builder.AddSystem<Integrator>(1);
auto integ2 = builder.AddSystem<Integrator>(1);
builder.ExportInput(integ0->get_input_port());
builder.Cascade(*integ0, *integ1);
builder.ExportOutput(integ1->get_output_port());
auto diagram = builder.Build();
auto diagram_context = diagram->AllocateContext();
diagram_context->EnableCaching();
diagram->get_input_port(0).FixValue(diagram_context.get(), 1.5); // u(=u0)
// Hunt down the cache entry for the Diagram's derivative computation so we
// can verify that it gets invalidated and recomputed as we expect.
auto& derivative_tracker =
diagram_context->get_tracker(diagram->xcdot_ticket());
ASSERT_NE(derivative_tracker.cache_entry_value(), nullptr);
const CacheEntryValue& derivative_cache =
*derivative_tracker.cache_entry_value();
EXPECT_TRUE(derivative_cache.is_out_of_date());
// Record the derivative serial number so we can watch out for unnecessary
// extra computations.
int64_t expected_derivative_serial = derivative_cache.serial_number();
VectorXd init_state(3);
init_state << 5., 6., 7.; // x0(=y0=u1), x1(=y1), x2(=y2)
// Set the state from the diagram level, then evaluate the diagram
// output, which should have copied the second state value (x1). Also, this
// shouldn't complain even though input u2 is dangling since we don't need it
// for this computation.
diagram_context->SetContinuousState(init_state);
EXPECT_EQ(diagram->get_output_port(0).Eval<BasicVector<double>>(
*diagram_context)[0],
6.);
// That should not have caused derivative evaluations.
EXPECT_TRUE(derivative_cache.is_out_of_date());
EXPECT_EQ(derivative_cache.serial_number(), expected_derivative_serial);
// Must set the dangling input port to a value to evaluate derivatives.
Context<double>& context2 =
diagram->GetMutableSubsystemContext(*integ2, &*diagram_context);
FixedInputPortValue& u2_value =
integ2->get_input_port(0).FixValue(&context2, 0.75);
// The diagram derivatives should be (u0,u1,u2)=(u,x0,u2).
auto& eval_derivs =
diagram->EvalTimeDerivatives(*diagram_context);
++expected_derivative_serial;
EXPECT_EQ(eval_derivs[0], 1.5);
EXPECT_EQ(eval_derivs[1], 5.);
EXPECT_EQ(eval_derivs[2], 0.75);
EXPECT_FALSE(derivative_cache.is_out_of_date());
EXPECT_EQ(derivative_cache.serial_number(), expected_derivative_serial);
// Now try to sneak in a change to subcontext state variables and then ask for
// the diagram's output value and derivatives again.
Context<double>& context0 =
diagram->GetMutableSubsystemContext(*integ0, &*diagram_context);
Context<double>& context1 =
diagram->GetMutableSubsystemContext(*integ1, &*diagram_context);
VectorXd new_x0(1), new_x1(1);
new_x0 << 13.; new_x1 << 17.;
context0.SetContinuousState(new_x0);
context1.SetContinuousState(new_x1);
// Diagram should know to recopy x1 to the output port cache entry.
EXPECT_EQ(diagram->get_output_port(0).Eval<BasicVector<double>>(
*diagram_context)[0],
17.);
// Diagram derivatives should be out of date since they depend on x0.
EXPECT_TRUE(derivative_cache.is_out_of_date());
EXPECT_EQ(derivative_cache.serial_number(), expected_derivative_serial);
// Diagram should know that the time derivatives cache entry is out of date
// so initiate subsystem derivative calculations and pick up the changed x0.
// This will fail if subcontext *state* modifications aren't transmitted
// properly to the Diagram.
diagram->EvalTimeDerivatives(*diagram_context);
++expected_derivative_serial;
EXPECT_EQ(eval_derivs[0], 1.5);
EXPECT_EQ(eval_derivs[1], 13.);
EXPECT_EQ(eval_derivs[2], 0.75);
EXPECT_FALSE(derivative_cache.is_out_of_date());
EXPECT_EQ(derivative_cache.serial_number(), expected_derivative_serial);
// Re-evaluate derivatives now and verify that they weren't recomputed.
diagram->EvalTimeDerivatives(*diagram_context);
EXPECT_EQ(derivative_cache.serial_number(), expected_derivative_serial);
// Now let's try modifying the internal input port. That shouldn't have any
// effect on the Diagram output port, since that depends only on state and
// hasn't changed. However, input u2 is the derivative result for integ2 and
// that should be reflected in the diagram derivative result.
u2_value.GetMutableVectorData<double>()->SetAtIndex(0, 300.);
EXPECT_EQ(diagram->get_output_port(0).Eval<BasicVector<double>>(
*diagram_context)[0],
17.); // No change.
EXPECT_TRUE(derivative_cache.is_out_of_date());
diagram->EvalTimeDerivatives(*diagram_context);
++expected_derivative_serial;
EXPECT_EQ(eval_derivs[0], 1.5);
EXPECT_EQ(eval_derivs[1], 13.);
EXPECT_EQ(eval_derivs[2], 300.);
EXPECT_FALSE(derivative_cache.is_out_of_date());
EXPECT_EQ(derivative_cache.serial_number(), expected_derivative_serial);
// Time & accuracy changes are allowed at the root (diagram) level.
DRAKE_EXPECT_NO_THROW(diagram_context->SetTime(1.));
DRAKE_EXPECT_NO_THROW(
diagram_context->SetTimeAndContinuousState(2., init_state));
auto diagram_context_clone = diagram_context->Clone();
DRAKE_EXPECT_NO_THROW(
diagram_context->SetTimeStateAndParametersFrom(*diagram_context_clone));
DRAKE_EXPECT_NO_THROW(diagram_context->SetAccuracy(1e-6));
// Time & accuracy changes NOT allowed at child (leaf) level.
DRAKE_EXPECT_THROWS_MESSAGE(context0.SetTime(3.),
".*SetTime.*Time change allowed only.*root.*");
DRAKE_EXPECT_THROWS_MESSAGE(
context0.SetTimeAndContinuousState(4., new_x0),
".*SetTimeAndContinuousState.*Time change allowed only.*root.*");
DRAKE_EXPECT_THROWS_MESSAGE(
context0.SetTimeStateAndParametersFrom(context1),
".*SetTimeStateAndParametersFrom.*Time change allowed only.*root.*");
DRAKE_EXPECT_THROWS_MESSAGE(
context0.SetAccuracy(1e-7),
".*SetAccuracy.*Accuracy change allowed only.*root.*");
}
// Tests that an exception is thrown if the systems in a Diagram do not have
// unique names.
GTEST_TEST(NonUniqueNamesTest, NonUniqueNames) {
DiagramBuilder<double> builder;
const int kInputs = 2;
const int kSize = 1;
auto adder0 = builder.AddSystem<Adder<double>>(kInputs, kSize);
adder0->set_name("unoriginal");
auto adder1 = builder.AddSystem<Adder<double>>(kInputs, kSize);
adder1->set_name("unoriginal");
EXPECT_THROW(builder.Build(), std::runtime_error);
}
// Tests that systems with unset names can be added to a Diagram.
GTEST_TEST(NonUniqueNamesTest, DefaultEmptyNames) {
DiagramBuilder<double> builder;
const int kInputs = 2;
const int kSize = 1;
builder.AddSystem<Adder<double>>(kInputs, kSize);
builder.AddSystem<Adder<double>>(kInputs, kSize);
DRAKE_EXPECT_NO_THROW(builder.Build());
}
// Tests that an exception is thrown if a system is reset to an empty name
// *after* being added to the diagram builder.
GTEST_TEST(NonUniqueNamesTest, ForcedEmptyNames) {
DiagramBuilder<double> builder;
const int kInputs = 2;
const int kSize = 1;
builder.AddSystem<Adder<double>>(kInputs, kSize);
builder.AddSystem<Adder<double>>(kInputs, kSize)->set_name("");
EXPECT_THROW(builder.Build(), std::runtime_error);
}
// A system for testing per step actions. A system can add per-step events for
// each event type as selected.
class PerStepActionTestSystem : public LeafSystem<double> {
public:
PerStepActionTestSystem() {
DeclareDiscreteState(1);
DeclareAbstractState(Value<std::string>(""));
}
// Methods for adding events post-construction.
void AddPublishEvent() {
DeclarePerStepPublishEvent(&PerStepActionTestSystem::PublishHandler);
}
void AddDiscreteUpdateEvent() {
DeclarePerStepDiscreteUpdateEvent(
&PerStepActionTestSystem::DiscreteHandler);
}
void AddUnrestrictedUpdateEvent() {
DeclarePerStepUnrestrictedUpdateEvent(
&PerStepActionTestSystem::UnrestrictedHandler);
}
using LeafSystem<double>::DeclarePerStepEvent;
int publish_count() const { return publish_count_; }
private:
void SetDefaultState(const Context<double>& context,
State<double>* state) const override {
state->get_mutable_discrete_state()[0] = 0;
state->get_mutable_abstract_state<std::string>(0) = "wow";
}
// TODO(15465) When per-step event declaration sugar allows for callbacks
// whose result is "assumed to succeed", change these to void return types.
EventStatus DiscreteHandler(const Context<double>& context,
DiscreteValues<double>* discrete_state) const {
(*discrete_state)[0] = context.get_discrete_state(0)[0] + 1;
return EventStatus::Succeeded();
}
EventStatus UnrestrictedHandler(const Context<double>& context,
State<double>* state) const {
// Depends on discrete state (therefore order of event evaluation).
int int_num = static_cast<int>(context.get_discrete_state(0)[0]);
state->get_mutable_abstract_state<std::string>(0) =
"wow" + std::to_string(int_num);
return EventStatus::Succeeded();
}
EventStatus PublishHandler(const Context<double>& context) const {
++publish_count_;
return EventStatus::Succeeded();
}
// A hack to test publish calls easily as the Publish events have no access
// to writable memory anywhere in the context. This is an anti-pattern outside
// of unit tests.
mutable int publish_count_{0};
};
// Test that the diagram successfully dispatches events into its component
// systems. To that end, we create a diagram with a nested diagram and sibling
// leaf systems. Each leaf system has a unique set of events (None, discrete and
// and unrestricted, and unrestricted and publish, respectively). By invoking
// the various forced event-generating methods (CalcUnrestrictedUpdate(),
// CalcDiscreteVariableUpdate(), and Publish(), we can observe the results by
// observing the context for the system (and its for-the-unit-test, hacked
// internal state). The fact that these unit tests use events triggered by
// per-step events is wholly irrelevant -- at this tested level of the API, the
// trigger doesn't matter.
GTEST_TEST(DiagramEventEvaluation, Propagation) {
std::unique_ptr<Diagram<double>> sub_diagram;
PerStepActionTestSystem* sys0{};
PerStepActionTestSystem* sys1{};
PerStepActionTestSystem* sys2{};
// Sub diagram. Has sys0, and sys1.
// sys0 does not have any per step actions.
// sys1 has discrete and unrestricted updates.
{
DiagramBuilder<double> builder;
sys0 = builder.AddSystem<PerStepActionTestSystem>();
sys0->set_name("sys0");
sys1 = builder.AddSystem<PerStepActionTestSystem>();
sys1->set_name("sys1");
sys1->AddDiscreteUpdateEvent();
sys1->AddUnrestrictedUpdateEvent();
sub_diagram = builder.Build();
sub_diagram->set_name("sub_diagram");
}
DiagramBuilder<double> builder;
builder.AddSystem(std::move(sub_diagram));
sys2 = builder.AddSystem<PerStepActionTestSystem>();
sys2->set_name("sys2");
sys2->AddPublishEvent();
sys2->AddUnrestrictedUpdateEvent();
auto diagram = builder.Build();
auto context = diagram->CreateDefaultContext();
diagram->set_name("diagram");
auto tmp_discrete_state = diagram->AllocateDiscreteVariables();
std::unique_ptr<State<double>> tmp_state = context->CloneState();
auto events = diagram->AllocateCompositeEventCollection();
diagram->GetPerStepEvents(*context, events.get());
ASSERT_TRUE(events->HasEvents());
// Does unrestricted update first.
EventStatus status = diagram->CalcUnrestrictedUpdate(
*context, events->get_unrestricted_update_events(), tmp_state.get());
EXPECT_TRUE(status.succeeded());
context->get_mutable_state().SetFrom(*tmp_state);
// Does discrete updates second.
status = diagram->CalcDiscreteVariableUpdate(
*context, events->get_discrete_update_events(), tmp_discrete_state.get());
EXPECT_TRUE(status.succeeded());
context->get_mutable_discrete_state().SetFrom(*tmp_discrete_state);
// Publishes last.
status = diagram->Publish(*context, events->get_publish_events());
EXPECT_TRUE(status.succeeded());
// Only sys2 published once.
EXPECT_EQ(sys0->publish_count(), 0);
EXPECT_EQ(sys1->publish_count(), 0);
EXPECT_EQ(sys2->publish_count(), 1);
// sys0 doesn't have any updates; the state is in its initial state.
auto& sys0_context = diagram->GetSubsystemContext(*sys0, *context);
EXPECT_EQ(sys0_context.get_discrete_state(0)[0], 0);
EXPECT_EQ(sys0_context.get_abstract_state<std::string>(0), "wow");
EXPECT_EQ(sys0->publish_count(), 0);
// sys1 should have an unrestricted update then a discrete update.
auto& sys1_context = diagram->GetSubsystemContext(*sys1, *context);
EXPECT_EQ(sys1_context.get_discrete_state(0)[0], 1);
EXPECT_EQ(sys1_context.get_abstract_state<std::string>(0), "wow0");
EXPECT_EQ(sys1->publish_count(), 0);
// sys2 should have a unrestricted update then a publish.
auto& sys2_context = diagram->GetSubsystemContext(*sys2, *context);
EXPECT_EQ(sys2_context.get_discrete_state(0)[0], 0);
EXPECT_EQ(sys2_context.get_abstract_state<std::string>(0), "wow0");
EXPECT_EQ(sys2->publish_count(), 1);
}
// A System that has one of each kind of event, with independently settable
// return statuses. We'll use this to test whether Diagrams properly
// implement our policy for handling error returns for simultaneous events.
class EventStatusTestSystem : public LeafSystem<double> {
public:
EventStatusTestSystem() {
DeclareForcedUnrestrictedUpdateEvent(
&EventStatusTestSystem::UnrestrictedHandler);
DeclareForcedDiscreteUpdateEvent(&EventStatusTestSystem::DiscreteHandler);
DeclareForcedPublishEvent(&EventStatusTestSystem::PublishHandler);
}
void set_unrestricted_severity(EventStatus::Severity severity) {
unrestricted_severity_ = severity;
}
void set_discrete_severity(EventStatus::Severity severity) {
discrete_severity_ = severity;
}
void set_publish_severity(EventStatus::Severity severity) {
publish_severity_ = severity;
}
// Returns the list of events handled by all EventStatusTestSystem instances,
// and clears the list back to empty.
static std::vector<std::string> take_static_events() {
std::vector<std::string> result = events_singleton();
events_singleton().clear();
return result;
}
private:
static std::vector<std::string>& events_singleton() {
static never_destroyed<std::vector<std::string>> global(
std::vector<std::string>{});
return global.access();
}
EventStatus MakeStatus(std::string id, EventStatus::Severity severity) const {
events_singleton().push_back(fmt::format("{} {}", this->get_name(), id));
switch (severity) {
case EventStatus::kDidNothing:
return EventStatus::DidNothing();
case EventStatus::kSucceeded:
return EventStatus::Succeeded();
case EventStatus::kReachedTermination:
return EventStatus::ReachedTermination(
this, fmt::format("{} terminated", id));
case EventStatus::kFailed:
return EventStatus::Failed(this, fmt::format("{} failed", id));
}
DRAKE_UNREACHABLE();
}
EventStatus UnrestrictedHandler(const Context<double>&,
State<double>*) const {
return MakeStatus("unrestricted", unrestricted_severity_);
}
EventStatus DiscreteHandler(const Context<double>&,
DiscreteValues<double>*) const {
return MakeStatus("discrete", discrete_severity_);
}
EventStatus PublishHandler(const Context<double>&) const {
return MakeStatus("publish", publish_severity_);
}
// The corresponding handlers return whatever status is set here.
EventStatus::Severity unrestricted_severity_{EventStatus::kSucceeded};
EventStatus::Severity discrete_severity_{EventStatus::kSucceeded};
EventStatus::Severity publish_severity_{EventStatus::kSucceeded};
};
// Policy to verify:
// 1 events are handled in the order the subsystems were added
// 2 if all events succeed, all get executed and return succeeded
// 3ab if all events do nothing (a), all get executed and we return did_nothing;
// a mix of succeeded & did nothing (b) returns succeeded
// 4ab if an unrestricted (a) or discrete (b) update fails, we fail immediately
// and return a message attributing the error to the right subsystem
// 5 if a publish event fails, we continue to handle remaining publish events
// and then finally report the correct message for the first failure
// 6ab a reached_termination status doesn't prevent execution but reports
// the first detection (a), but is superseded by a later failure (b)
GTEST_TEST(DiagramEventEvaluation, EventStatusHandling) {
std::unique_ptr<Diagram<double>> sub_diagram0;
std::unique_ptr<Diagram<double>> sub_diagram1;
EventStatusTestSystem* sys[5] = {};
{ // Sub diagram 0 has sys0 & sys1.
DiagramBuilder<double> builder;
sys[0] = builder.AddSystem<EventStatusTestSystem>();
sys[0]->set_name("sys0");
sys[1] = builder.AddSystem<EventStatusTestSystem>();
sys[1]->set_name("sys1");
sub_diagram0 = builder.Build();
sub_diagram0->set_name("sub_diagram0");
}
{ // Sub diagram 1 has sys3 & sys4.
DiagramBuilder<double> builder;
sys[3] = builder.AddSystem<EventStatusTestSystem>();
sys[3]->set_name("sys3");
sys[4] = builder.AddSystem<EventStatusTestSystem>();
sys[4]->set_name("sys4");
sub_diagram1 = builder.Build();
sub_diagram1->set_name("sub_diagram1");
}
// Now build the diagram consisting of the two subdiagrams separated by
// one more leaf system:
// diagram
// sub_diagram0 sys2 sub_diagram1
// sys0 sys1 sys3 sys4
//
DiagramBuilder<double> builder;
builder.AddSystem(std::move(sub_diagram0));
sys[2] = builder.AddSystem<EventStatusTestSystem>();
sys[2]->set_name("sys2");
builder.AddSystem(std::move(sub_diagram1));
auto diagram = builder.Build();
diagram->set_name("diagram");
// We aren't looking for state updates; we just need a place to put the
// (ignored) outputs. We just need to know who got called when.
auto context = diagram->CreateDefaultContext();
State<double>& state = context->get_mutable_state();
DiscreteValues<double>& discrete_state = state.get_mutable_discrete_state();
auto calc_unrestricted_update = [&context, &state](const auto& dut) {
return dut->CalcUnrestrictedUpdate(
*context, *dut->AllocateForcedUnrestrictedUpdateEventCollection(),
&state);
};
auto calc_discrete_variable_update = [&context,
&discrete_state](const auto& dut) {
return dut->CalcDiscreteVariableUpdate(
*context, *dut->AllocateForcedDiscreteUpdateEventCollection(),
&discrete_state);
};
auto publish = [&context](const auto& dut) {
return dut->Publish(*context, *dut->AllocateForcedPublishEventCollection());
};
// The event logs should have these strings in this order, when everything
// succeeds. When failure cuts execution short, we still expect to see a
// prefix of the full arrays.
const std::string all_unrestricted[] = {
"sys0 unrestricted", "sys1 unrestricted", "sys2 unrestricted",
"sys3 unrestricted", "sys4 unrestricted"};
const std::string all_discrete[] = {
"sys0 discrete", "sys1 discrete", "sys2 discrete",
"sys3 discrete", "sys4 discrete"};
const std::string all_publish[] = {
"sys0 publish", "sys1 publish", "sys2 publish",
"sys3 publish", "sys4 publish"};
// Sets all events in all systems to the same severity.
auto reset_severity = [sys](EventStatus::Severity severity) {
for (EventStatusTestSystem* item : sys) {
item->set_unrestricted_severity(severity);
item->set_discrete_severity(severity);
item->set_publish_severity(severity);
}
};
auto take_static_events = &EventStatusTestSystem::take_static_events;
// Policy 1 & 2: Every handler returns success and should be invoked in order.
EventStatus unrestricted_status = calc_unrestricted_update(diagram);
EXPECT_TRUE(unrestricted_status.succeeded());
EXPECT_THAT(take_static_events(), ElementsAreArray(all_unrestricted));
EventStatus discrete_status = calc_discrete_variable_update(diagram);
EXPECT_TRUE(discrete_status.succeeded());
EXPECT_THAT(take_static_events(), ElementsAreArray(all_discrete));
EventStatus publish_status = publish(diagram);
EXPECT_TRUE(publish_status.succeeded());
EXPECT_THAT(take_static_events(), ElementsAreArray(all_publish));
// Policy 3ab: Unrestricted & publish handlers all return did_nothing, so
// their final status should be did_nothing. One of the discrete handlers
// succeeds so its final status should be succeeded. Order unchanged from
// above.
reset_severity(EventStatus::kDidNothing);
sys[3]->set_discrete_severity(EventStatus::kSucceeded);
unrestricted_status = calc_unrestricted_update(diagram);
EXPECT_TRUE(unrestricted_status.did_nothing());
EXPECT_THAT(take_static_events(), ElementsAreArray(all_unrestricted));
discrete_status = calc_discrete_variable_update(diagram);
EXPECT_TRUE(discrete_status.succeeded());
EXPECT_THAT(take_static_events(), ElementsAreArray(all_discrete));
publish_status = publish(diagram);
EXPECT_TRUE(publish_status.did_nothing());
EXPECT_THAT(take_static_events(), ElementsAreArray(all_publish));
// Policy 4a: sys[1] unrestricted fails. Nothing after should execute.
reset_severity(EventStatus::kSucceeded);
sys[1]->set_unrestricted_severity(EventStatus::kFailed);
unrestricted_status = calc_unrestricted_update(diagram);
EXPECT_TRUE(unrestricted_status.failed());
EXPECT_EQ(unrestricted_status.system(), sys[1]);
EXPECT_EQ(unrestricted_status.message(), "unrestricted failed");
EXPECT_THAT(take_static_events(),
ElementsAreArray(all_unrestricted, /* count = */ 2));
// Policy 4b: sys[2] discrete fails. Nothing after should execute.
reset_severity(EventStatus::kSucceeded);
sys[2]->set_discrete_severity(EventStatus::kFailed);
discrete_status = calc_discrete_variable_update(diagram);
EXPECT_TRUE(discrete_status.failed());
EXPECT_EQ(discrete_status.system(), sys[2]);
EXPECT_EQ(discrete_status.message(), "discrete failed");
EXPECT_THAT(take_static_events(),
ElementsAreArray(all_discrete, /* count = */ 3));
// Policy 5: sys[0] publish fails. All other publishes should execute
// but then the returned status is the sys[0] failure.
reset_severity(EventStatus::kSucceeded);
sys[0]->set_publish_severity(EventStatus::kFailed);
publish_status = publish(diagram);
EXPECT_TRUE(publish_status.failed());
EXPECT_EQ(publish_status.system(), sys[0]);
EXPECT_EQ(publish_status.message(), "publish failed");
EXPECT_THAT(take_static_events(), ElementsAreArray(all_publish));
// Policy 6a: sys[1] unrestricted and sys[3] unrestricted report termination.
// Everything executes and the sys[1] termination return is reported.
reset_severity(EventStatus::kSucceeded);
sys[1]->set_unrestricted_severity(EventStatus::kReachedTermination);
sys[3]->set_unrestricted_severity(EventStatus::kReachedTermination);
unrestricted_status = calc_unrestricted_update(diagram);
EXPECT_TRUE(unrestricted_status.reached_termination());
EXPECT_EQ(unrestricted_status.system(), sys[1]);
EXPECT_EQ(unrestricted_status.message(), "unrestricted terminated");
EXPECT_THAT(take_static_events(), ElementsAreArray(all_unrestricted));
// Policy 6b: sys[1] discrete reports termination, sys[3] fails.
// sys[4] is not executed, and the sys[3] failure is reported.
reset_severity(EventStatus::kSucceeded);
sys[1]->set_discrete_severity(EventStatus::kReachedTermination);
sys[3]->set_discrete_severity(EventStatus::kFailed);
discrete_status = calc_discrete_variable_update(diagram);
EXPECT_TRUE(discrete_status.failed());
EXPECT_EQ(discrete_status.system(), sys[3]);
EXPECT_EQ(discrete_status.message(), "discrete failed");
EXPECT_THAT(take_static_events(),
ElementsAreArray(all_discrete, /* count = */ 4));
}
class MyEventTestSystem : public LeafSystem<double> {
public:
// If p > 0, declares a periodic publish event with p. Otherwise, declares
// a per step publish event.
MyEventTestSystem(const std::string& name, double p) {
if (p > 0) {
DeclarePeriodicPublishEvent(p, 0.0, &MyEventTestSystem::PublishPeriodic);
// Verify that no periodic discrete updates are registered.
EXPECT_FALSE(this->GetUniquePeriodicDiscreteUpdateAttribute());
} else {
DeclarePerStepPublishEvent(&MyEventTestSystem::PublishPerStep);
}
set_name(name);
}
int get_periodic_count() const { return periodic_count_; }
int get_per_step_count() const { return per_step_count_; }
private:
void PublishPeriodic(const Context<double>&) const {
++periodic_count_;
}
// TODO(15465) When per-step event declaration sugar allows for callbacks
// whose result is "assumed to succeed", change this to void return.
EventStatus PublishPerStep(const Context<double>&) const {
++per_step_count_;
return EventStatus::Succeeded();
}
mutable int periodic_count_{0};
mutable int per_step_count_{0};
};
// Test the event functionality of the MyEventTestSystem before using it in the
// diagram.
GTEST_TEST(MyEventTest, MyEventTestLeaf) {
// Test both construction modes: periodic and per-step events.
for (double period : {0.2, 0.0}) {
MyEventTestSystem dut("sys", period);
auto events = dut.AllocateCompositeEventCollection();
auto periodic_events = dut.AllocateCompositeEventCollection();
auto per_step_events = dut.AllocateCompositeEventCollection();
auto context = dut.CreateDefaultContext();
EXPECT_EQ(events->get_system_id(), context->get_system_id());
// If period is zero, we still need to evaluate the per step events.
dut.GetPeriodicEvents(*context, periodic_events.get());
dut.GetPerStepEvents(*context, per_step_events.get());
events->AddToEnd(*periodic_events);
events->AddToEnd(*per_step_events);
const EventStatus status =
dut.Publish(*context, events->get_publish_events());
EXPECT_TRUE(status.succeeded());
EXPECT_EQ(dut.get_periodic_count(), period > 0 ? 1 : 0);
EXPECT_EQ(dut.get_per_step_count(), period > 0 ? 0 : 1);
}
}
// Builds a diagram with a sub diagram (has 3 MyEventTestSystem) and 2
// MyEventTestSystem. sys4 is configured to have a per-step event, and all
// the others have periodic publish events. Tests Diagram::CalcNextUpdateTime,
// and Diagram::GetPerStepEvents. The result should be sys1, sys2, sys3, sys4
// fired their proper callbacks.
GTEST_TEST(MyEventTest, MyEventTestDiagram) {
std::unique_ptr<Diagram<double>> sub_diagram;
std::vector<const MyEventTestSystem*> sys(5);
{
DiagramBuilder<double> builder;
// sys0's scheduled time is after the rest, so its trigger should not fire.
sys[0] = builder.AddSystem<MyEventTestSystem>("sys0", 0.2);
sys[1] = builder.AddSystem<MyEventTestSystem>("sys1", 0.1);
sys[2] = builder.AddSystem<MyEventTestSystem>("sys2", 0.1);
sub_diagram = builder.Build();
sub_diagram->set_name("sub_diagram");
}
DiagramBuilder<double> builder;
builder.AddSystem(std::move(sub_diagram));
sys[3] = builder.AddSystem<MyEventTestSystem>("sys3", 0.1);
sys[4] = builder.AddSystem<MyEventTestSystem>("sys4", 0.);
auto dut = builder.Build();
auto periodic_events = dut->AllocateCompositeEventCollection();
auto per_step_events = dut->AllocateCompositeEventCollection();
auto events = dut->AllocateCompositeEventCollection();
auto context = dut->CreateDefaultContext();
// Returns only the events that trigger at 0.1s.
double time = dut->CalcNextUpdateTime(*context, periodic_events.get());
dut->GetPerStepEvents(*context, per_step_events.get());
events->AddToEnd(*periodic_events);
events->AddToEnd(*per_step_events);
// FYI time not actually needed here; events to handle already selected.
context->SetTime(time);
EventStatus status = dut->Publish(*context, events->get_publish_events());
EXPECT_TRUE(status.succeeded());
// Sys0's period is larger, so it doesn't get evaluated.
EXPECT_EQ(sys[0]->get_periodic_count(), 0);
EXPECT_EQ(sys[0]->get_per_step_count(), 0);
// Sys1, 2, & 3, all have periodic events at `time`.
EXPECT_EQ(sys[1]->get_periodic_count(), 1);
EXPECT_EQ(sys[1]->get_per_step_count(), 0);
EXPECT_EQ(sys[2]->get_periodic_count(), 1);
EXPECT_EQ(sys[2]->get_per_step_count(), 0);
EXPECT_EQ(sys[3]->get_periodic_count(), 1);
EXPECT_EQ(sys[3]->get_per_step_count(), 0);
// Sys4 has only a per-step publish event, it got triggered by the explicit
// Publish() call above.
EXPECT_EQ(sys[4]->get_periodic_count(), 0);
EXPECT_EQ(sys[4]->get_per_step_count(), 1);
// Next, re-use this Diagram using GetPeriodicEvents() rather than
// CalcNextUpdateTime(). periodic_events should get cleared first so that
// it doesn't contain the ones leftover from the CalcNextUpdateTime() call.
// (If it doesn't get cleared some of the counts will be incremented twice.)
dut->GetPeriodicEvents(*context, periodic_events.get());
status = dut->Publish(*context, periodic_events->get_publish_events());
EXPECT_TRUE(status.succeeded());
EXPECT_EQ(sys[0]->get_periodic_count(), 1);
EXPECT_EQ(sys[0]->get_per_step_count(), 0);
EXPECT_EQ(sys[1]->get_periodic_count(), 2);
EXPECT_EQ(sys[1]->get_per_step_count(), 0);
EXPECT_EQ(sys[2]->get_periodic_count(), 2);
EXPECT_EQ(sys[2]->get_per_step_count(), 0);
EXPECT_EQ(sys[3]->get_periodic_count(), 2);
EXPECT_EQ(sys[3]->get_per_step_count(), 0);
EXPECT_EQ(sys[4]->get_periodic_count(), 0);
EXPECT_EQ(sys[4]->get_per_step_count(), 1);
}
template <typename T>
class ConstraintTestSystem : public LeafSystem<T> {
public:
ConstraintTestSystem()
: LeafSystem<T>(systems::SystemTypeTag<ConstraintTestSystem>{}) {
this->DeclareContinuousState(2);
this->DeclareEqualityConstraint(&ConstraintTestSystem::CalcState0Constraint,
1, "x0");
this->DeclareInequalityConstraint(
&ConstraintTestSystem::CalcStateConstraint,
{ Vector2d::Zero(), std::nullopt }, "x");
}
// Scalar-converting copy constructor.
template <typename U>
explicit ConstraintTestSystem(const ConstraintTestSystem<U>& system)
: ConstraintTestSystem() {}
// Expose some protected methods for testing.
using LeafSystem<T>::DeclareInequalityConstraint;
using LeafSystem<T>::DeclareEqualityConstraint;
void CalcState0Constraint(const Context<T>& context,
VectorX<T>* value) const {
*value = Vector1<T>(context.get_continuous_state_vector()[0]);
}
void CalcStateConstraint(const Context<T>& context, VectorX<T>* value) const {
*value = context.get_continuous_state_vector().CopyToVector();
}
private:
void DoCalcTimeDerivatives(const Context<T>& context,
ContinuousState<T>* derivatives) const override {
// xdot = -x.
derivatives->SetFromVector(-dynamic_cast<const BasicVector<T>&>(
context.get_continuous_state_vector())
.get_value());
}
};
GTEST_TEST(DiagramConstraintTest, SystemConstraintsTest) {
systems::DiagramBuilder<double> builder;
auto sys1 = builder.AddSystem<ConstraintTestSystem<double>>();
auto sys2 = builder.AddSystem<ConstraintTestSystem<double>>();
auto diagram = builder.Build();
EXPECT_EQ(diagram->num_constraints(), 4); // two from each system
auto context = diagram->CreateDefaultContext();
// Set sys1 context.
diagram->GetMutableSubsystemContext(*sys1, context.get())
.get_mutable_continuous_state_vector()
.SetFromVector(Vector2d(5.0, 7.0));
// Set sys2 context.
diagram->GetMutableSubsystemContext(*sys2, context.get())
.get_mutable_continuous_state_vector()
.SetFromVector(Vector2d(11.0, 12.0));
VectorXd value;
// Check system 1's x0 constraint.
const SystemConstraint<double>& constraint0 =
diagram->get_constraint(SystemConstraintIndex(0));
constraint0.Calc(*context, &value);
EXPECT_EQ(value.size(), 1);
EXPECT_EQ(value[0], 5.0);
EXPECT_TRUE(constraint0.is_equality_constraint());
std::string description = constraint0.description();
// Constraint description should end in the original description.
EXPECT_EQ(description.substr(description.size() - 2), "x0");
// Check system 1's x constraint
const SystemConstraint<double>& constraint1 =
diagram->get_constraint(SystemConstraintIndex(1));
constraint1.Calc(*context, &value);
EXPECT_EQ(value.size(), 2);
EXPECT_EQ(value[0], 5.0);
EXPECT_EQ(value[1], 7.0);
EXPECT_FALSE(constraint1.is_equality_constraint());
description = constraint1.description();
EXPECT_EQ(description.substr(description.size() - 1), "x");
// Check system 2's x0 constraint.
const SystemConstraint<double>& constraint2 =
diagram->get_constraint(SystemConstraintIndex(2));
constraint2.Calc(*context, &value);
EXPECT_EQ(value.size(), 1);
EXPECT_EQ(value[0], 11.0);
EXPECT_TRUE(constraint2.is_equality_constraint());
description = constraint2.description();
EXPECT_EQ(description.substr(description.size() - 2), "x0");
// Check system 2's x constraint
const SystemConstraint<double>& constraint3 =
diagram->get_constraint(SystemConstraintIndex(3));
constraint3.Calc(*context, &value);
EXPECT_EQ(value.size(), 2);
EXPECT_EQ(value[0], 11.0);
EXPECT_EQ(value[1], 12.0);
EXPECT_FALSE(constraint3.is_equality_constraint());
description = constraint3.description();
EXPECT_EQ(description.substr(description.size() - 1), "x");
// Check that constraints survive ToAutoDiffXd.
auto autodiff_diagram = diagram->ToAutoDiffXd();
EXPECT_EQ(autodiff_diagram->num_constraints(), 4);
auto autodiff_context = autodiff_diagram->CreateDefaultContext();
autodiff_context->SetTimeStateAndParametersFrom(*context);
const SystemConstraint<AutoDiffXd>& autodiff_constraint =
autodiff_diagram->get_constraint(SystemConstraintIndex(3));
VectorX<AutoDiffXd> autodiff_value;
autodiff_constraint.Calc(*autodiff_context, &autodiff_value);
EXPECT_EQ(autodiff_value[0].value(), 11.0);
// Check that constraints survive ToSymbolic.
auto symbolic_diagram = diagram->ToSymbolic();
EXPECT_EQ(symbolic_diagram->num_constraints(), 4);
auto symbolic_context = symbolic_diagram->CreateDefaultContext();
symbolic_context->SetTimeStateAndParametersFrom(*context);
const SystemConstraint<symbolic::Expression>& symbolic_constraint =
symbolic_diagram->get_constraint(SystemConstraintIndex(3));
VectorX<symbolic::Expression> symbolic_value;
symbolic_constraint.Calc(*symbolic_context, &symbolic_value);
EXPECT_EQ(symbolic_value[0], 11.0);
}
GTEST_TEST(DiagramParametersTest, ParameterTest) {
// Construct a diagram with multiple subsystems that have parameters.
systems::DiagramBuilder<double> builder;
auto pendulum1 =
builder.AddSystem<examples::pendulum::PendulumPlant<double>>();
auto pendulum2 =
builder.AddSystem<examples::pendulum::PendulumPlant<double>>();
auto constant_torque =
builder.AddSystem<ConstantVectorSource<double>>(Vector1d(1.0));
builder.Cascade(*constant_torque, *pendulum1);
builder.Cascade(*constant_torque, *pendulum2);
auto diagram = builder.Build();
auto context = diagram->CreateDefaultContext();
// Make sure the Diagram correctly reports its aggregate number of
// parameters.
EXPECT_EQ(diagram->num_numeric_parameter_groups(),
context->num_numeric_parameter_groups());
// Get pointers to the parameters.
auto params1 = dynamic_cast<examples::pendulum::PendulumParams<double>*>(
&diagram->GetMutableSubsystemContext(*pendulum1, context.get())
.get_mutable_numeric_parameter(0));
auto params2 = dynamic_cast<examples::pendulum::PendulumParams<double>*>(
&diagram->GetMutableSubsystemContext(*pendulum2, context.get())
.get_mutable_numeric_parameter(0));
const double original_damping = params1->damping();
const double new_damping = 5.0*original_damping;
EXPECT_EQ(params2->damping(), original_damping);
params1->set_damping(new_damping);
// Check that I didn't change params2.
EXPECT_EQ(params2->damping(), original_damping);
diagram->SetDefaultContext(context.get());
// Check that the original value is restored.
EXPECT_EQ(params1->damping(), original_damping);
params2->set_damping(new_damping);
diagram->SetDefaultParameters(*context, &context->get_mutable_parameters());
// Check that the original value is restored.
EXPECT_EQ(params2->damping(), original_damping);
}
// Note: this class is duplicated from leaf_system_test.
class RandomContextTestSystem : public LeafSystem<double> {
public:
RandomContextTestSystem() {
this->DeclareContinuousState(
BasicVector<double>(Vector2d(-1.0, -2.0)));
this->DeclareNumericParameter(
BasicVector<double>(Vector3d(1.0, 2.0, 3.0)));
}
void SetRandomState(const Context<double>& context, State<double>* state,
RandomGenerator* generator) const override {
std::normal_distribution<double> normal;
for (int i = 0; i < context.get_continuous_state_vector().size(); i++) {
state->get_mutable_continuous_state().get_mutable_vector().SetAtIndex(
i, normal(*generator));
}
}
void SetRandomParameters(const Context<double>& context,
Parameters<double>* params,
RandomGenerator* generator) const override {
std::uniform_real_distribution<double> uniform;
for (int i = 0; i < context.get_numeric_parameter(0).size(); i++) {
params->get_mutable_numeric_parameter(0).SetAtIndex(
i, uniform(*generator));
}
}
};
GTEST_TEST(RandomContextTest, SetRandomTest) {
DiagramBuilder<double> builder;
builder.AddSystem<RandomContextTestSystem>();
builder.AddSystem<RandomContextTestSystem>();
const auto diagram = builder.Build();
auto context = diagram->CreateDefaultContext();
// Back-up the numeric context values.
Vector4d state = context->get_continuous_state_vector().CopyToVector();
Vector3d params0 = context->get_numeric_parameter(0).CopyToVector();
Vector3d params1 = context->get_numeric_parameter(1).CopyToVector();
// Should return the (same) original values.
diagram->SetDefaultContext(context.get());
EXPECT_TRUE((state.array() ==
context->get_continuous_state_vector().CopyToVector().array())
.all());
EXPECT_TRUE((params0.array() ==
context->get_numeric_parameter(0).get_value().array())
.all());
EXPECT_TRUE((params1.array() ==
context->get_numeric_parameter(1).get_value().array())
.all());
RandomGenerator generator;
// Should return different values.
diagram->SetRandomContext(context.get(), &generator);
EXPECT_TRUE((state.array() !=
context->get_continuous_state_vector().CopyToVector().array())
.all());
EXPECT_TRUE((params0.array() !=
context->get_numeric_parameter(0).get_value().array())
.all());
EXPECT_TRUE((params1.array() !=
context->get_numeric_parameter(1).get_value().array())
.all());
// Update backup.
state = context->get_continuous_state_vector().CopyToVector();
params0 = context->get_numeric_parameter(0).CopyToVector();
params1 = context->get_numeric_parameter(1).CopyToVector();
// Should return different values (again).
diagram->SetRandomContext(context.get(), &generator);
EXPECT_TRUE((state.array() !=
context->get_continuous_state_vector().CopyToVector().array())
.all());
EXPECT_TRUE((params0.array() !=
context->get_numeric_parameter(0).get_value().array())
.all());
EXPECT_TRUE((params1.array() !=
context->get_numeric_parameter(1).get_value().array())
.all());
}
// Tests initialization works properly for all subsystems.
GTEST_TEST(InitializationTest, InitializationTest) {
DiagramBuilder<double> builder;
auto sys0 = builder.AddSystem<InitializationTestSystem>();
auto sys1 = builder.AddSystem<InitializationTestSystem>();
auto dut = builder.Build();
auto context = dut->CreateDefaultContext();
dut->ExecuteInitializationEvents(context.get());
EXPECT_TRUE(sys0->get_pub_init());
EXPECT_TRUE(sys0->get_dis_update_init());
EXPECT_TRUE(sys0->get_unres_update_init());
EXPECT_TRUE(sys1->get_pub_init());
EXPECT_TRUE(sys1->get_dis_update_init());
EXPECT_TRUE(sys1->get_unres_update_init());
}
// TODO(siyuan) add direct tests for EventCollection
// A System that does not override the default implicit time derivatives
// implementation.
class DefaultExplicitSystem : public LeafSystem<double> {
public:
DefaultExplicitSystem() { DeclareContinuousState(3); }
static Vector3d fixed_derivative() { return {1., 2., 3.}; }
private:
void DoCalcTimeDerivatives(const Context<double>& context,
ContinuousState<double>* derivatives) const final {
derivatives->SetFromVector(fixed_derivative());
}
};
// A System that _does_ override the default implicit time derivatives
// implementation, and also changes the residual size from its default.
class OverrideImplicitSystem : public DefaultExplicitSystem {
public:
OverrideImplicitSystem() {
DeclareImplicitTimeDerivativesResidualSize(1);
}
private:
void DoCalcImplicitTimeDerivativesResidual(
const systems::Context<double>& context,
const systems::ContinuousState<double>& proposed_derivatives,
EigenPtr<VectorX<double>> residual) const final {
EXPECT_EQ(residual->size(), 1);
(*residual)[0] = proposed_derivatives.CopyToVector().sum();
}
};
// A Diagram should concatenate the implicit time derivatives from its
// component subsystems, and tally up the size correctly.
GTEST_TEST(ImplicitTimeDerivatives, DiagramProcessing) {
const Vector3d derivs = DefaultExplicitSystem::fixed_derivative();
DiagramBuilder<double> builder;
builder.AddSystem<DefaultExplicitSystem>(); // 3 residuals
builder.AddSystem<OverrideImplicitSystem>(); // 1 residual
builder.AddSystem<DefaultExplicitSystem>(); // 3 more residuals
auto diagram = builder.Build();
auto context = diagram->CreateDefaultContext();
EXPECT_EQ(diagram->implicit_time_derivatives_residual_size(), 7);
VectorXd residual = diagram->AllocateImplicitTimeDerivativesResidual();
EXPECT_EQ(residual.size(), 7);
auto xdot = diagram->AllocateTimeDerivatives();
EXPECT_EQ(xdot->size(), 9); // 3 derivatives each subsystem
const auto xdot_vector = VectorXd::LinSpaced(9, 11., 19.);
xdot->SetFromVector(xdot_vector);
VectorXd expected_result(7);
expected_result.segment<3>(0) = xdot_vector.segment<3>(0) - derivs;
expected_result[3] = xdot_vector.segment<3>(3).sum();
expected_result.segment<3>(4) = xdot_vector.segment<3>(6) - derivs;
diagram->CalcImplicitTimeDerivativesResidual(*context, *xdot, &residual);
EXPECT_EQ(residual, expected_result);
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/value_to_abstract_value_test.cc | #include "drake/systems/framework/value_to_abstract_value.h"
#include <memory>
#include <type_traits>
#include <gtest/gtest.h>
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/systems/framework/test_utilities/my_vector.h"
namespace drake {
namespace systems {
namespace internal {
namespace {
// Define a collection of classes that exhibit all the copy/clone variants
// that ValueToAbstractValue is supposed to handle correctly.
class NotCopyableOrCloneable {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(NotCopyableOrCloneable)
explicit NotCopyableOrCloneable(double value) : value_{value} {}
double value() const { return value_; }
private:
double value_{};
};
class CopyConstructible {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(CopyConstructible)
explicit CopyConstructible(double value) : value_{value} {}
double value() const { return value_; }
private:
double value_{};
};
// When both copy and clone are around, we're supposed to prefer copy.
class CopyableAndCloneable {
public:
explicit CopyableAndCloneable(double value) : value_{value} {}
CopyableAndCloneable(const CopyableAndCloneable& src)
: value_(src.value()), was_copy_constructed_(true) {}
CopyableAndCloneable& operator=(const CopyableAndCloneable& src) = default;
std::unique_ptr<CopyableAndCloneable> Clone() const {
++num_clones_;
return std::make_unique<CopyableAndCloneable>(value());
}
double value() const { return value_; }
int num_clones() const { return num_clones_; }
bool was_copy_constructed() const { return was_copy_constructed_; }
private:
double value_{};
bool was_copy_constructed_{false};
mutable int num_clones_{0};
};
class JustCloneable {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(JustCloneable)
virtual ~JustCloneable() = default;
explicit JustCloneable(double value) : value_{value} {}
std::unique_ptr<JustCloneable> Clone() const { return DoClone(); }
double value() const { return value_; }
private:
virtual std::unique_ptr<JustCloneable> DoClone() const {
return std::make_unique<JustCloneable>(value_);
}
double value_{};
};
// This derived class is cloneable via its base class but doesn't have its own
// public Clone() method. The Value<T> we create for it should use the
// base class type for T.
class BaseClassCloneable : public JustCloneable {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(BaseClassCloneable)
BaseClassCloneable(std::string name, double value)
: JustCloneable(value), name_(std::move(name)) {}
std::string name() const { return name_; }
private:
std::unique_ptr<JustCloneable> DoClone() const final {
return std::make_unique<BaseClassCloneable>(name_, value());
}
std::string name_;
};
// This derived class is cloneable via its own public Clone() method. The
// Value<T> we create for it should use the derived class type for T.
class DerivedClassCloneable : public JustCloneable {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DerivedClassCloneable)
DerivedClassCloneable(std::string name, double value)
: JustCloneable(value), name_(std::move(name)) {}
std::unique_ptr<DerivedClassCloneable> Clone() const {
return std::make_unique<DerivedClassCloneable>(name_, value());
}
std::string name() const { return name_; }
private:
std::unique_ptr<JustCloneable> DoClone() const final {
return std::make_unique<DerivedClassCloneable>(name_, value());
}
std::string name_;
};
// Test each of the four ToAbstract() methods implemented for AbstractPolicy.
// For reference:
// (1) ToAbstract(AbstractValue) cloned directly without wrapping in Value<>
// (2) ToAbstract(const char*) special-cased shorthand for std::string
// (3) ToAbstract(Eigen object) must be a simple Eigen type
// (4) ToAbstract<V>(V) creates Value<V> for copyable or cloneable types V,
// or Value<B> if V's clone returns a base type B.
// Method (4) is supposed to prefer the copy constructor if it and Clone() are
// both available.
//
// No runtime errors occur with this policy. A compilation failure occurs
// if a non-copyable, non-cloneable type is provided.
GTEST_TEST(ValueToAbstractValue, AbstractPolicy) {
// All methods return std::unique_ptr<AbstractValue>.
using AbstractPolicy = ValueToAbstractValue;
// First check handling of given AbstractValue objects (signature (1)).
// Pass a value already of AbstractValue type.
Value<std::string> value_str("hello");
Value<double> value_double(1.25);
AbstractValue& absval_double = value_double;
const auto value_str_copy =
AbstractPolicy::ToAbstract("MyApi", value_str); // (1, with conversion)
const auto absval_double_copy =
AbstractPolicy::ToAbstract("MyApi", absval_double); // (1)
EXPECT_EQ(value_str_copy->get_value<std::string>(), "hello");
EXPECT_EQ(absval_double_copy->get_value<double>(), 1.25);
// Make sure we're not just looking at the same objects.
value_str.get_mutable_value() = "goodbye";
EXPECT_EQ(value_str_copy->get_value<std::string>(), "hello"); // no change
absval_double.get_mutable_value<double>() = 2.5;
EXPECT_EQ(absval_double_copy->get_value<double>(), 1.25); // no change
// Check char* sugar signature (2).
// char* values are stored in std::string AbstractValues.
const auto char_ptr_val = AbstractPolicy::ToAbstract("MyApi", "char*");
EXPECT_EQ(char_ptr_val->get_value<std::string>(), "char*"); // (2)
// Check signature (4) handling of simple objects.
const auto int_val = AbstractPolicy::ToAbstract("MyApi", 5); // (4)
EXPECT_EQ(int_val->get_value<int>(), 5);
const auto str_val =
AbstractPolicy::ToAbstract("MyApi", std::string("string")); // (4)
EXPECT_EQ(str_val->get_value<std::string>(), "string");
// Check signature (4) handling of objects that are: just copyable,
// just cloneable (to self or base class), and both copyable and cloneable.
const auto copyable_val = AbstractPolicy::ToAbstract(
"MyApi", CopyConstructible(1.25)); // (4, copy)
EXPECT_EQ(copyable_val->get_value<CopyConstructible>().value(), 1.25);
const auto cloneable_val =
AbstractPolicy::ToAbstract("MyApi", JustCloneable(0.75)); // (4, clone)
EXPECT_EQ(cloneable_val->get_value<JustCloneable>().value(), 0.75);
// Here ToAbstract() has to discover that the available Clone() method
// returns a base class-typed object (here a JustCloneable), rather than the
// concrete type we give it, so we have to store it in a Value<BaseType>.
const auto base_cloneable_val = AbstractPolicy::ToAbstract(
"MyApi",
BaseClassCloneable("base_cloneable", 1.5)); // (4, clone-to-base)
EXPECT_EQ(base_cloneable_val->get_value<JustCloneable>().value(), 1.5);
EXPECT_EQ(dynamic_cast<const BaseClassCloneable&>(
base_cloneable_val->get_value<JustCloneable>())
.name(),
"base_cloneable");
// Here ToAbstract() should discover that the available Clone() method
// returns the derived class-typed object, so we can store that directly
// in a Value<DerivedType>.
const auto derived_cloneable_val = AbstractPolicy::ToAbstract(
"MyApi", DerivedClassCloneable("derived_cloneable", 0.25)); // (4, clone)
EXPECT_EQ(derived_cloneable_val->get_value<DerivedClassCloneable>().value(),
0.25);
EXPECT_EQ(derived_cloneable_val->get_value<DerivedClassCloneable>().name(),
"derived_cloneable");
// When the value object is both copyable and cloneable, we expect the copy
// constructor to be used.
CopyableAndCloneable cc_value(2.25);
EXPECT_EQ(cc_value.num_clones(), 0);
EXPECT_FALSE(cc_value.was_copy_constructed());
const auto cc_val_abstract_copy =
AbstractPolicy::ToAbstract("MyApi", cc_value); // (4, prefer copy)
const auto& cc_val_copy =
cc_val_abstract_copy->get_value<CopyableAndCloneable>();
EXPECT_EQ(cc_val_copy.value(), 2.25);
EXPECT_EQ(cc_value.num_clones(), 0);
EXPECT_TRUE(cc_val_copy.was_copy_constructed());
EXPECT_EQ(cc_val_copy.num_clones(), 0);
// These are also (4) but should trigger a nice static_assert message if
// uncommented, similar to:
// static assertion failed: ValueToAbstractValue(): value type must be
// copy constructible or have an accessible Clone() method that returns
// std::unique_ptr.
// AbstractPolicy::ToAbstract("MyApi", NotCopyableOrCloneable(2.));
}
// AbstractPolicy should store vector objects as themselves, but Eigen vector
// expressions must get eval()'ed first and then stored as the eval() type.
GTEST_TEST(ValueToAbstractValue, AbstractPolicyOnVectors) {
using AbstractPolicy = ValueToAbstractValue;
const Eigen::Vector3d expected_vec(10., 20., 30.);
const double expected_scalar = 3.125;
// A scalar should not get turned into a Vector1.
const auto scalar_val =
AbstractPolicy::ToAbstract("MyApi", expected_scalar); // (4)
EXPECT_EQ(scalar_val->get_value<double>(), expected_scalar);
// An Eigen vector object can't be supplied directly.
DRAKE_EXPECT_THROWS_MESSAGE(
AbstractPolicy::ToAbstract("MyApi", expected_vec), // (3)
".*MyApi.*Eigen.*cannot automatically be stored.*Drake abstract "
"quantity.*");
// But providing the type explicitly works.
const auto vec3_val =
AbstractPolicy::ToAbstract("MyApi", Value<Eigen::Vector3d>(expected_vec));
EXPECT_EQ(vec3_val->get_value<Eigen::Vector3d>(), expected_vec);
// More complicated Eigen expressions should throw also.
const Eigen::Vector4d long_vec(.25, .5, .75, 1.);
DRAKE_EXPECT_THROWS_MESSAGE(
AbstractPolicy::ToAbstract("MyApi", long_vec.tail(3)), // (3)
".*MyApi.*Eigen.*cannot automatically be stored.*Drake abstract "
"quantity.*");
// A plain BasicVector is stored as a Value<BasicVector>, just as it is
// under the VectorPolicy.
const BasicVector<double> basic_vector3({7., 8., 9.});
const auto basic_vector_val =
AbstractPolicy::ToAbstract("MyApi", basic_vector3); // (4)
EXPECT_EQ(basic_vector_val->get_value<BasicVector<double>>().get_value(),
Eigen::Vector3d(7., 8., 9.));
// MyVector derives from BasicVector and has its own Clone() method
// that returns unique_ptr<MyVector>. Under the AbstractPolicy, this is
// handled like any other cloneable object by signature (4) and stored as
// Value<MyVector>. That's different from the VectorPolicy treatment.
const MyVector3d my_vector3(expected_vec);
auto my_vector3_val = AbstractPolicy::ToAbstract("MyApi", my_vector3); // (4)
const MyVector3d& my_vector3_from_abstract =
my_vector3_val->get_value<MyVector3d>();
EXPECT_EQ(my_vector3_from_abstract.get_value(), expected_vec);
}
// Test each of the five ToAbstract() methods implemented for VectorPolicy.
// For reference:
// (1) ToAbstract(Eigen::Ref) should convert to BasicVector.
// (2) ToAbstract(scalar) should be treated like and Eigen Vector1.
// (3) ToAbstract(BasicVector) special-cased to make concrete vector types work
// regardless of whether they overload Clone().
// (4) ToAbstract(AbstractValue) cloned directly without wrapping in Value<>,
// but must resolve to Value<BasicVector>.
// (5) ToAbstract<V>(V) issues an std::logic_error since only the above types
// are acceptable for vector objects.
// Test the non-vector signatures (4) and (5) here. These can produce runtime
// errors which should include the supplied API name. (All methods must take
// the name.)
GTEST_TEST(ValueToVectorValue, GenericObjects) {
// All methods return std::unique_ptr<AbstractValue>.
using VectorPolicy = ValueToVectorValue<double>;
// Check that AbstractValue objects are acceptable to signature (4) only if
// they resolve to Value<BasicVector>.
const Value<int> bad_val(1);
const Value<BasicVector<double>> good_val(Eigen::Vector3d(1., 2., 3.));
DRAKE_EXPECT_THROWS_MESSAGE(
VectorPolicy::ToAbstract("MyApi", bad_val),
".*MyApi.*AbstractValue.*type int is not.*vector quantity.*");
const auto good_val_copy = VectorPolicy::ToAbstract("MyApi", good_val);
EXPECT_EQ(good_val_copy->get_value<BasicVector<double>>().get_value(),
Eigen::Vector3d(1., 2., 3.));
// Non-vector objects should throw via signature (5).
DRAKE_EXPECT_THROWS_MESSAGE(VectorPolicy::ToAbstract("MyApi", 5),
".*MyApi.*type int is not.*vector quantity.*");
DRAKE_EXPECT_THROWS_MESSAGE(
VectorPolicy::ToAbstract("MyApi", std::string("string")),
".*MyApi.*type std::string is not.*vector quantity.*");
DRAKE_EXPECT_THROWS_MESSAGE(
VectorPolicy::ToAbstract("MyApi", CopyConstructible(1.25)),
".*MyApi.*CopyConstructible is not.*vector quantity.*");
DRAKE_EXPECT_THROWS_MESSAGE(
VectorPolicy::ToAbstract("MyApi", JustCloneable(0.75)),
".*MyApi.*JustCloneable is not.*vector quantity.*");
}
// Test signature (1), (2), and (3) which deal with Eigen vectors, scalars, and
// BasicVectors, respectively, under VectorPolicy. (Under AbstractPolicy,
// none of these get special treatment.)
GTEST_TEST(ValueToVectorValue, VectorPolicy) {
const Eigen::Vector3d expected_vec(10., 20., 30.);
const double expected_scalar = 3.125;
// VectorPolicy handles Eigen vector, scalar, and BasicVector-derived objects
// V by putting them in a Value<BasicVector>.
using VectorPolicy = ValueToVectorValue<double>;
// VectorPolicy puts a scalar into a 1-element Value<BasicVector<T>>, while
// AbstractPolicy simply puts it in a Value<T>.
auto scalar_val = VectorPolicy::ToAbstract("MyApi", expected_scalar); // (2)
EXPECT_EQ(scalar_val->get_value<BasicVector<double>>()[0], expected_scalar);
// Any Eigen vector type should be stored as a BasicVector.
auto vec3_val = VectorPolicy::ToAbstract("MyApi", expected_vec); // (1)
EXPECT_EQ(vec3_val->get_value<BasicVector<double>>().get_value(),
expected_vec);
// Pass a more complicated Eigen object; should still work.
const Eigen::Vector4d long_vec(.25, .5, .75, 1.);
auto tail3_val = VectorPolicy::ToAbstract("MyApi", long_vec.tail(3)); // (1)
EXPECT_EQ(tail3_val->get_value<BasicVector<double>>().get_value(),
Eigen::Vector3d(.5, .75, 1.));
auto segment2_val =
VectorPolicy::ToAbstract("MyApi", long_vec.segment<2>(1)); // (1)
EXPECT_EQ(segment2_val->get_value<BasicVector<double>>().get_value(),
Eigen::Vector2d(.5, .75));
// A plain BasicVector is stored as a Value<BasicVector>. It is handled
// by the BasicVector overload (3).
const BasicVector<double> basic_vector3({7., 8., 9.});
const auto basic_vector_val =
VectorPolicy::ToAbstract(__func__, basic_vector3); // (3)
EXPECT_EQ(basic_vector_val->get_value<BasicVector<double>>().get_value(),
Eigen::Vector3d(7., 8., 9.));
// MyVector derives from BasicVector and has its own Clone() method
// that returns unique_ptr<MyVector>. *Despite that*, under the VectorPolicy
// it should be stored as a Value<BasicVector>, which is why signature (3)
// exists for this policy. (AbstractPolicy would store this as a
// Value<MyVector>.) However, the concrete type must be preserved.
const MyVector3d my_vector3(expected_vec);
auto my_vector3_val = VectorPolicy::ToAbstract("MyApi", my_vector3); // (3)
const BasicVector<double>& basic_vector =
my_vector3_val->get_value<BasicVector<double>>();
EXPECT_EQ(basic_vector.get_value(), expected_vec);
// Check that the concrete type was preserved.
EXPECT_EQ(dynamic_cast<const MyVector3d&>(basic_vector).get_value(),
expected_vec);
}
} // namespace
} // namespace internal
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/leaf_system_test.cc | #include "drake/systems/framework/leaf_system.h"
#include <limits>
#include <memory>
#include <stdexcept>
#include <string>
#include <typeinfo>
#include <Eigen/Dense>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "drake/common/eigen_types.h"
#include "drake/common/random.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/test_utilities/is_dynamic_castable.h"
#include "drake/common/test_utilities/limit_malloc.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/context.h"
#include "drake/systems/framework/leaf_context.h"
#include "drake/systems/framework/system.h"
#include "drake/systems/framework/system_output.h"
#include "drake/systems/framework/test_utilities/initialization_test_system.h"
#include "drake/systems/framework/test_utilities/my_vector.h"
#include "drake/systems/framework/test_utilities/pack_value.h"
using Eigen::Vector2d;
using Eigen::Vector3d;
using Eigen::Vector4d;
using Eigen::VectorXd;
namespace drake {
namespace systems {
namespace {
// A shell System to test the default implementations.
template <typename T>
class TestSystem : public LeafSystem<T> {
public:
TestSystem() {
this->set_name("TestSystem");
this->DeclareNumericParameter(BasicVector<T>{13.0, 7.0});
this->DeclareAbstractParameter(Value<std::string>("parameter value"));
this->DeclareDiscreteState(3);
this->DeclareAbstractState(Value<int>(5));
this->DeclareAbstractState(Value<std::string>("second abstract state"));
}
~TestSystem() override {}
using LeafSystem<T>::DeclareContinuousState;
using LeafSystem<T>::DeclareDiscreteState;
using LeafSystem<T>::DeclareStateOutputPort;
using LeafSystem<T>::DeclareNumericParameter;
using LeafSystem<T>::DeclareVectorInputPort;
using LeafSystem<T>::DeclareAbstractInputPort;
using LeafSystem<T>::DeclareVectorOutputPort;
using LeafSystem<T>::DeclareAbstractOutputPort;
using LeafSystem<T>::DeclarePerStepEvent;
using LeafSystem<T>::DeclarePeriodicEvent;
void AddPeriodicUpdate() {
const double period = 10.0;
const double offset = 5.0;
this->DeclarePeriodicDiscreteUpdateEvent(
period, offset, &TestSystem<T>::NoopDiscreteUpdate);
std::optional<PeriodicEventData> periodic_attr =
this->GetUniquePeriodicDiscreteUpdateAttribute();
ASSERT_TRUE(periodic_attr);
EXPECT_EQ(periodic_attr.value().period_sec(), period);
EXPECT_EQ(periodic_attr.value().offset_sec(), offset);
}
void AddPeriodicUpdate(double period) {
const double offset = 0.0;
this->DeclarePeriodicDiscreteUpdateEvent(
period, offset, &TestSystem<T>::NoopDiscreteUpdate);
std::optional<PeriodicEventData> periodic_attr =
this->GetUniquePeriodicDiscreteUpdateAttribute();
ASSERT_TRUE(periodic_attr);
EXPECT_EQ(periodic_attr.value().period_sec(), period);
EXPECT_EQ(periodic_attr.value().offset_sec(), offset);
}
void AddPeriodicUpdate(double period, double offset) {
this->DeclarePeriodicDiscreteUpdateEvent(
period, offset, &TestSystem<T>::NoopDiscreteUpdate);
}
EventStatus NoopDiscreteUpdate(const Context<T>&, DiscreteValues<T>*) const {
return EventStatus::DidNothing();
}
void AddPeriodicUnrestrictedUpdate(double period, double offset) {
this->DeclarePeriodicUnrestrictedUpdateEvent(
period, offset, &TestSystem<T>::NoopUnrestritedUpdate);
}
EventStatus NoopUnrestritedUpdate(const Context<T>&, State<T>*) const {
return EventStatus::DidNothing();
}
void AddPublish(double period) {
const double offset = 0.0;
this->DeclarePeriodicPublishEvent(period, offset,
&TestSystem<T>::NoopPublish);
}
EventStatus NoopPublish(const Context<T>&) const {
return EventStatus::DidNothing();
}
void DoCalcTimeDerivatives(const Context<T>& context,
ContinuousState<T>* derivatives) const override {}
void CalcOutput(const Context<T>& context, BasicVector<T>* output) const {}
const BasicVector<T>& GetVanillaNumericParameters(
const Context<T>& context) const {
return this->GetNumericParameter(context, 0 /* index */);
}
BasicVector<T>& GetVanillaMutableNumericParameters(
Context<T>* context) const {
return this->GetMutableNumericParameter(context, 0 /* index */);
}
// First testing type: no event specified.
std::unique_ptr<WitnessFunction<T>> MakeWitnessWithoutEvent() const {
return this->MakeWitnessFunction(
"dummy1", WitnessFunctionDirection::kCrossesZero,
&TestSystem<double>::DummyWitnessFunction);
}
// Second testing type: event specified.
std::unique_ptr<WitnessFunction<T>> MakeWitnessWithEvent() const {
return this->MakeWitnessFunction(
"dummy2", WitnessFunctionDirection::kNone,
&TestSystem<double>::DummyWitnessFunction,
PublishEvent<double>());
}
// Third testing type: publish callback specified.
std::unique_ptr<WitnessFunction<T>> MakeWitnessWithPublish() const {
return this->MakeWitnessFunction(
"dummy3", WitnessFunctionDirection::kNone,
&TestSystem<double>::DummyWitnessFunction,
&TestSystem<double>::PublishCallback);
}
// Fourth testing type: discrete update callback specified.
std::unique_ptr<WitnessFunction<T>> MakeWitnessWithDiscreteUpdate() const {
return this->MakeWitnessFunction(
"dummy4", WitnessFunctionDirection::kNone,
&TestSystem<double>::DummyWitnessFunction,
&TestSystem<double>::DiscreteUpdateCallback);
}
// Fifth testing type: unrestricted update callback specified.
std::unique_ptr<WitnessFunction<T>>
MakeWitnessWithUnrestrictedUpdate() const {
return this->MakeWitnessFunction(
"dummy5", WitnessFunctionDirection::kNone,
&TestSystem<double>::DummyWitnessFunction,
&TestSystem<double>::UnrestrictedUpdateCallback);
}
// Sixth testing type: lambda function with no event specified.
std::unique_ptr<WitnessFunction<T>> DeclareLambdaWitnessWithoutEvent() const {
return this->MakeWitnessFunction(
"dummy6", WitnessFunctionDirection::kCrossesZero,
[](const Context<double>&) -> double { return 7.0; });
}
// Seventh testing type: lambda function with event specified.
std::unique_ptr<WitnessFunction<T>>
DeclareLambdaWitnessWithUnrestrictedUpdate() const {
return this->MakeWitnessFunction(
"dummy7", WitnessFunctionDirection::kPositiveThenNonPositive,
[](const Context<double>&) -> double { return 11.0; },
UnrestrictedUpdateEvent<double>());
}
// Indicates whether various callbacks have been called.
bool publish_callback_called() const { return publish_callback_called_; }
bool discrete_update_callback_called() const {
return discrete_update_callback_called_;
}
bool unrestricted_update_callback_called() const {
return unrestricted_update_callback_called_;
}
// Verifies that the forced publish events collection has been allocated.
bool forced_publish_events_collection_allocated() const {
return this->forced_publish_events_exist();
}
// Verifies that the forced discrete update events collection has been
// allocated.
bool forced_discrete_update_events_collection_allocated() const {
return this->forced_discrete_update_events_exist();
}
// Verifies that the forced unrestricted update events collection has been=
// allocated.
bool forced_unrestricted_update_events_collection_allocated() const {
return this->forced_unrestricted_update_events_exist();
}
// Gets the forced publish events collection.
const EventCollection<PublishEvent<double>>&
get_forced_publish_events_collection() const {
return this->get_forced_publish_events();
}
// Gets the forced discrete update events collection.
const EventCollection<DiscreteUpdateEvent<double>>&
get_forced_discrete_update_events_collection() const {
return this->get_forced_discrete_update_events();
}
// Gets the forced unrestricted update events collection.
const EventCollection<UnrestrictedUpdateEvent<double>>&
get_forced_unrestricted_update_events_collection() const {
return this->get_forced_unrestricted_update_events();
}
// Sets the forced publish events collection.
void set_forced_publish_events_collection(
std::unique_ptr<EventCollection<PublishEvent<double>>>
publish_events) {
this->set_forced_publish_events(std::move(publish_events));
}
// Sets the forced discrete_update events collection.
void set_forced_discrete_update_events_collection(
std::unique_ptr<EventCollection<DiscreteUpdateEvent<double>>>
discrete_update_events) {
this->set_forced_discrete_update_events(std::move(discrete_update_events));
}
// Sets the forced unrestricted_update events collection.
void set_forced_unrestricted_update_events_collection(
std::unique_ptr<EventCollection<UnrestrictedUpdateEvent<double>>>
unrestricted_update_events) {
this->set_forced_unrestricted_update_events(
std::move(unrestricted_update_events));
}
// Gets the mutable version of the forced publish events collection.
EventCollection<PublishEvent<double>>&
get_mutable_forced_publish_events_collection() {
return this->get_mutable_forced_publish_events();
}
private:
// This dummy witness function exists only to test that the
// MakeWitnessFunction() interface works as promised.
T DummyWitnessFunction(const Context<T>& context) const {
static int call_counter = 0;
return static_cast<T>(++call_counter);
}
// Publish callback function, which serves to test whether the appropriate
// MakeWitnessFunction() interface works as promised.
void PublishCallback(const Context<T>&, const PublishEvent<T>&) const {
publish_callback_called_ = true;
}
// Discrete update callback function, which serves to test whether the
// appropriate MakeWitnessFunction() interface works as promised.
void DiscreteUpdateCallback(const Context<T>&,
const DiscreteUpdateEvent<T>&, DiscreteValues<T>*) const {
discrete_update_callback_called_ = true;
}
// Unrestricted update callback function, which serves to test whether the
// appropriate MakeWitnessFunction() interface works as promised.
void UnrestrictedUpdateCallback(const Context<T>&,
const UnrestrictedUpdateEvent<T>&, State<T>*) const {
unrestricted_update_callback_called_ = true;
}
// Indicators for which callbacks have been called, made mutable as
// PublishCallback() cannot alter any state (the others are mutable for
// consistency with PublishCallback() and to avoid machinations with state
// that would otherwise be required).
mutable bool publish_callback_called_{false};
mutable bool discrete_update_callback_called_{false};
mutable bool unrestricted_update_callback_called_{false};
};
class LeafSystemTest : public ::testing::Test {
protected:
void SetUp() override {
event_info_ = system_.AllocateCompositeEventCollection();
leaf_info_ = dynamic_cast<const LeafCompositeEventCollection<double>*>(
event_info_.get());
// Make sure caching tests will work properly even if caching is off
// by default.
context_.EnableCaching();
}
double CalcNextUpdateTime() const {
// Unless there are an extreme number of concurrent events, calculating the
// next update time should not allocate.
test::LimitMalloc guard;
return system_.CalcNextUpdateTime(context_, event_info_.get());
}
TestSystem<double> system_;
std::unique_ptr<LeafContext<double>> context_ptr_ = system_.AllocateContext();
LeafContext<double>& context_ = *context_ptr_;
std::unique_ptr<CompositeEventCollection<double>> event_info_;
const LeafCompositeEventCollection<double>* leaf_info_;
};
TEST_F(LeafSystemTest, ForcedEventCollectionsTest) {
// Verify that all collections are allocated.
EXPECT_TRUE(system_.forced_publish_events_collection_allocated());
EXPECT_TRUE(system_.forced_discrete_update_events_collection_allocated());
EXPECT_TRUE(system_.forced_unrestricted_update_events_collection_allocated());
// Verify that we can set the publish collection.
auto forced_publishes =
std::make_unique<LeafEventCollection<PublishEvent<double>>>();
auto* forced_publishes_pointer = forced_publishes.get();
system_.set_forced_publish_events_collection(std::move(forced_publishes));
EXPECT_EQ(&system_.get_forced_publish_events_collection(),
forced_publishes_pointer);
EXPECT_EQ(&system_.get_mutable_forced_publish_events_collection(),
forced_publishes_pointer);
// Verify that we can set the discrete update collection.
auto forced_discrete_updates =
std::make_unique<LeafEventCollection<DiscreteUpdateEvent<double>>>();
auto* forced_discrete_updates_pointer = forced_discrete_updates.get();
system_.set_forced_discrete_update_events_collection(
std::move(forced_discrete_updates));
EXPECT_EQ(&system_.get_forced_discrete_update_events_collection(),
forced_discrete_updates_pointer);
// Verify that we can set the forced unrestricted update collection.
auto forced_unrestricted_updates =
std::make_unique<LeafEventCollection<UnrestrictedUpdateEvent<double>>>();
auto* forced_unrestricted_updates_pointer = forced_unrestricted_updates.get();
system_.set_forced_unrestricted_update_events_collection(
std::move(forced_unrestricted_updates));
EXPECT_EQ(&system_.get_forced_unrestricted_update_events_collection(),
forced_unrestricted_updates_pointer);
}
TEST_F(LeafSystemTest, DefaultPortNameTest) {
EXPECT_EQ(
system_.DeclareVectorInputPort(kUseDefaultName, BasicVector<double>(2))
.get_name(),
"u0");
EXPECT_EQ(
system_.DeclareAbstractInputPort(kUseDefaultName, Value<int>(1))
.get_name(),
"u1");
EXPECT_EQ(
system_.DeclareVectorOutputPort(kUseDefaultName,
&TestSystem<double>::CalcOutput)
.get_name(),
"y0");
EXPECT_EQ(
system_
.DeclareAbstractOutputPort(kUseDefaultName, BasicVector<double>(2),
&TestSystem<double>::CalcOutput)
.get_name(),
"y1");
}
TEST_F(LeafSystemTest, DeclareVectorPortsBySizeTest) {
const InputPort<double>& input =
system_.DeclareVectorInputPort("my_input", 2);
EXPECT_EQ(input.get_name(), "my_input");
EXPECT_EQ(input.size(), 2);
EXPECT_FALSE(input.is_random());
EXPECT_TRUE(system_
.DeclareVectorInputPort(kUseDefaultName, 3,
RandomDistribution::kUniform)
.is_random());
const OutputPort<double>& output = system_.DeclareVectorOutputPort(
"my_output", 3, &TestSystem<double>::CalcOutput);
EXPECT_EQ(output.get_name(), "my_output");
EXPECT_EQ(output.size(), 3);
const OutputPort<double>& output2 = system_.DeclareVectorOutputPort(
"my_output2", 2, [](const Context<double>&, BasicVector<double>*) {});
EXPECT_EQ(output2.get_name(), "my_output2");
EXPECT_EQ(output2.size(), 2);
}
// Tests that witness functions can be declared. Tests that witness functions
// stop Simulator at desired points (i.e., the raison d'être of a witness
// function) are done in diagram_test.cc and
// drake/systems/analysis/test/simulator_test.cc.
TEST_F(LeafSystemTest, WitnessDeclarations) {
auto witness1 = system_.MakeWitnessWithoutEvent();
ASSERT_TRUE(witness1);
EXPECT_EQ(witness1->description(), "dummy1");
EXPECT_EQ(witness1->direction_type(),
WitnessFunctionDirection::kCrossesZero);
EXPECT_FALSE(witness1->get_event());
EXPECT_EQ(witness1->CalcWitnessValue(context_), 1.0);
auto witness2 = system_.MakeWitnessWithEvent();
ASSERT_TRUE(witness2);
EXPECT_EQ(witness2->description(), "dummy2");
EXPECT_EQ(witness2->direction_type(), WitnessFunctionDirection::kNone);
EXPECT_TRUE(witness2->get_event());
EXPECT_EQ(witness2->get_event()->get_trigger_type(), TriggerType::kWitness);
EXPECT_EQ(witness2->CalcWitnessValue(context_), 2.0);
auto witness3 = system_.MakeWitnessWithPublish();
ASSERT_TRUE(witness3);
EXPECT_EQ(witness3->description(), "dummy3");
EXPECT_EQ(witness3->direction_type(),
WitnessFunctionDirection::kNone);
EXPECT_TRUE(witness3->get_event());
EXPECT_EQ(witness3->get_event()->get_trigger_type(), TriggerType::kWitness);
EXPECT_EQ(witness3->CalcWitnessValue(context_), 3.0);
auto pe = dynamic_cast<const PublishEvent<double>*>(witness3->get_event());
ASSERT_TRUE(pe);
pe->handle(system_, context_);
EXPECT_TRUE(system_.publish_callback_called());
auto witness4 = system_.MakeWitnessWithDiscreteUpdate();
ASSERT_TRUE(witness4);
EXPECT_EQ(witness4->description(), "dummy4");
EXPECT_EQ(witness4->direction_type(),
WitnessFunctionDirection::kNone);
EXPECT_TRUE(witness4->get_event());
EXPECT_EQ(witness4->get_event()->get_trigger_type(), TriggerType::kWitness);
EXPECT_EQ(witness4->CalcWitnessValue(context_), 4.0);
auto de = dynamic_cast<const DiscreteUpdateEvent<double>*>(
witness4->get_event());
ASSERT_TRUE(de);
de->handle(system_, context_, nullptr);
EXPECT_TRUE(system_.discrete_update_callback_called());
auto witness5 = system_.MakeWitnessWithUnrestrictedUpdate();
ASSERT_TRUE(witness5);
EXPECT_EQ(witness5->description(), "dummy5");
EXPECT_EQ(witness5->direction_type(),
WitnessFunctionDirection::kNone);
EXPECT_TRUE(witness5->get_event());
EXPECT_EQ(witness5->get_event()->get_trigger_type(), TriggerType::kWitness);
EXPECT_EQ(witness5->CalcWitnessValue(context_), 5.0);
auto ue = dynamic_cast<const UnrestrictedUpdateEvent<double>*>(
witness5->get_event());
ASSERT_TRUE(ue);
ue->handle(system_, context_, nullptr);
EXPECT_TRUE(system_.unrestricted_update_callback_called());
auto witness6 = system_.DeclareLambdaWitnessWithoutEvent();
ASSERT_TRUE(witness6);
EXPECT_EQ(witness6->description(), "dummy6");
EXPECT_EQ(witness6->direction_type(),
WitnessFunctionDirection::kCrossesZero);
EXPECT_EQ(witness6->CalcWitnessValue(context_), 7.0);
auto witness7 = system_.DeclareLambdaWitnessWithUnrestrictedUpdate();
ASSERT_TRUE(witness7);
EXPECT_EQ(witness7->description(), "dummy7");
EXPECT_EQ(witness7->direction_type(),
WitnessFunctionDirection::kPositiveThenNonPositive);
EXPECT_TRUE(witness7->get_event());
EXPECT_EQ(witness7->get_event()->get_trigger_type(), TriggerType::kWitness);
EXPECT_EQ(witness7->CalcWitnessValue(context_), 11.0);
ue = dynamic_cast<const UnrestrictedUpdateEvent<double>*>(
witness7->get_event());
ASSERT_TRUE(ue);
}
// Tests that if no update events are configured, none are reported.
TEST_F(LeafSystemTest, NoUpdateEvents) {
context_.SetTime(25.0);
double time = CalcNextUpdateTime();
EXPECT_EQ(std::numeric_limits<double>::infinity(), time);
EXPECT_TRUE(!leaf_info_->HasEvents());
}
// Tests that multiple periodic updates with the same periodic attribute are
// identified as unique.
TEST_F(LeafSystemTest, MultipleUniquePeriods) {
system_.AddPeriodicUpdate();
system_.AddPeriodicUpdate();
// Verify the size of the periodic events mapping.
auto mapping = system_.MapPeriodicEventsByTiming();
ASSERT_EQ(mapping.size(), 1);
EXPECT_EQ(mapping.begin()->second.size(), 2);
EXPECT_TRUE(system_.GetUniquePeriodicDiscreteUpdateAttribute());
}
// Tests that periodic updates with different periodic attributes are
// identified as non-unique.
TEST_F(LeafSystemTest, MultipleNonUniquePeriods) {
system_.AddPeriodicUpdate(1.0, 2.0);
system_.AddPeriodicUpdate(2.0, 3.0);
// Verify the size of the periodic events mapping.
auto mapping = system_.MapPeriodicEventsByTiming();
ASSERT_EQ(mapping.size(), 2);
EXPECT_FALSE(system_.GetUniquePeriodicDiscreteUpdateAttribute());
EXPECT_FALSE(system_.IsDifferenceEquationSystem());
}
// Tests that if the current time is smaller than the offset, the next
// update time is the offset.
TEST_F(LeafSystemTest, OffsetHasNotArrivedYet) {
context_.SetTime(2.0);
system_.AddPeriodicUpdate();
double time = CalcNextUpdateTime();
EXPECT_EQ(5.0, time);
const auto& events = leaf_info_->get_discrete_update_events().get_events();
EXPECT_EQ(events.size(), 1);
EXPECT_EQ(events.front()->get_trigger_type(), TriggerType::kPeriodic);
}
// Tests that if the current time is smaller than the offset, the next
// update time is the offset, DiscreteUpdate and UnrestrictedUpdate happen
// at the same time.
TEST_F(LeafSystemTest, EventsAtTheSameTime) {
context_.SetTime(2.0);
// Both actions happen at t = 5.
system_.AddPeriodicUpdate();
system_.AddPeriodicUnrestrictedUpdate(3, 5);
double time = CalcNextUpdateTime();
EXPECT_EQ(5.0, time);
{
const auto& events = leaf_info_->get_discrete_update_events().get_events();
EXPECT_EQ(events.size(), 1);
EXPECT_EQ(events.front()->get_trigger_type(), TriggerType::kPeriodic);
}
{
const auto& events =
leaf_info_->get_unrestricted_update_events().get_events();
EXPECT_EQ(events.size(), 1);
EXPECT_EQ(events.front()->get_trigger_type(), TriggerType::kPeriodic);
}
}
// Tests that if the current time is exactly the offset, the next
// update time is in the future.
TEST_F(LeafSystemTest, ExactlyAtOffset) {
context_.SetTime(5.0);
system_.AddPeriodicUpdate();
double time = CalcNextUpdateTime();
EXPECT_EQ(15.0, time);
const auto& events = leaf_info_->get_discrete_update_events().get_events();
EXPECT_EQ(events.size(), 1);
EXPECT_EQ(events.front()->get_trigger_type(), TriggerType::kPeriodic);
}
// Tests that if the current time is larger than the offset, the next
// update time is determined by the period.
TEST_F(LeafSystemTest, OffsetIsInThePast) {
context_.SetTime(23.0);
system_.AddPeriodicUpdate();
double time = CalcNextUpdateTime();
EXPECT_EQ(25.0, time);
const auto& events = leaf_info_->get_discrete_update_events().get_events();
EXPECT_EQ(events.size(), 1);
EXPECT_EQ(events.front()->get_trigger_type(), TriggerType::kPeriodic);
}
// Tests that if the current time is exactly an update time, the next update
// time is in the future.
TEST_F(LeafSystemTest, ExactlyOnUpdateTime) {
context_.SetTime(25.0);
system_.AddPeriodicUpdate();
double time = CalcNextUpdateTime();
EXPECT_EQ(35.0, time);
const auto& events = leaf_info_->get_discrete_update_events().get_events();
EXPECT_EQ(events.size(), 1);
EXPECT_EQ(events.front()->get_trigger_type(), TriggerType::kPeriodic);
}
// Tests periodic events' scheduling when its offset is zero.
TEST_F(LeafSystemTest, PeriodicUpdateZeroOffset) {
system_.AddPeriodicUpdate(2.0);
context_.SetTime(0.0);
double time = CalcNextUpdateTime();
EXPECT_EQ(2.0, time);
context_.SetTime(1.0);
time = CalcNextUpdateTime();
EXPECT_EQ(2.0, time);
context_.SetTime(2.1);
time = CalcNextUpdateTime();
EXPECT_EQ(4.0, time);
}
// Tests that if a LeafSystem has both a discrete update and a periodic Publish,
// the update actions are computed appropriately.
TEST_F(LeafSystemTest, UpdateAndPublish) {
system_.AddPeriodicUpdate(15.0);
system_.AddPublish(12.0);
// The publish event fires at 12sec.
context_.SetTime(9.0);
double time = CalcNextUpdateTime();
EXPECT_EQ(12.0, time);
{
const auto& events = leaf_info_->get_publish_events().get_events();
EXPECT_EQ(events.size(), 1);
EXPECT_EQ(events.front()->get_trigger_type(), TriggerType::kPeriodic);
}
// The update event fires at 15sec.
context_.SetTime(14.0);
time = CalcNextUpdateTime();
EXPECT_EQ(15.0, time);
{
const auto& events = leaf_info_->get_discrete_update_events().get_events();
EXPECT_EQ(events.size(), 1);
EXPECT_EQ(events.front()->get_trigger_type(), TriggerType::kPeriodic);
}
// Both events fire at 60sec.
context_.SetTime(59.0);
time = CalcNextUpdateTime();
EXPECT_EQ(60.0, time);
{
const auto& events = leaf_info_->get_discrete_update_events().get_events();
EXPECT_EQ(events.size(), 1);
EXPECT_EQ(events.front()->get_trigger_type(), TriggerType::kPeriodic);
}
{
const auto& events = leaf_info_->get_publish_events().get_events();
EXPECT_EQ(events.size(), 1);
EXPECT_EQ(events.front()->get_trigger_type(), TriggerType::kPeriodic);
}
}
// Tests that if the integrator has stopped on the k-th sample, and the current
// time for that sample is slightly less than k * period due to floating point
// rounding, the next sample time is (k + 1) * period.
TEST_F(LeafSystemTest, FloatingPointRoundingZeroPointZeroOneFive) {
context_.SetTime(0.015 * 11); // Slightly less than 0.165.
system_.AddPeriodicUpdate(0.015);
double time = CalcNextUpdateTime();
// 0.015 * 12 = 0.18.
EXPECT_NEAR(0.18, time, 1e-8);
}
// Tests that if the integrator has stopped on the k-th sample, and the current
// time for that sample is slightly less than k * period due to floating point
// rounding, the next sample time is (k + 1) * period.
TEST_F(LeafSystemTest, FloatingPointRoundingZeroPointZeroZeroTwoFive) {
context_.SetTime(0.0025 * 977); // Slightly less than 2.4425
system_.AddPeriodicUpdate(0.0025);
double time = CalcNextUpdateTime();
EXPECT_NEAR(2.445, time, 1e-8);
}
// Tests that discrete and abstract state dependency wiring is set up
// correctly.
TEST_F(LeafSystemTest, DiscreteAndAbstractStateTrackers) {
EXPECT_EQ(system_.num_discrete_state_groups(), 1);
std::unique_ptr<Context<double>> context = system_.CreateDefaultContext();
const DependencyTracker& xd_tracker =
context->get_tracker(system_.xd_ticket());
for (DiscreteStateIndex i(0); i < system_.num_discrete_state_groups(); ++i) {
const DependencyTracker& tracker =
context->get_tracker(system_.discrete_state_ticket(i));
EXPECT_TRUE(xd_tracker.HasPrerequisite(tracker));
EXPECT_TRUE(tracker.HasSubscriber(xd_tracker));
}
EXPECT_EQ(system_.num_abstract_states(), 2);
const DependencyTracker& xa_tracker =
context->get_tracker(system_.xa_ticket());
for (AbstractStateIndex i(0); i < system_.num_abstract_states(); ++i) {
const DependencyTracker& tracker =
context->get_tracker(system_.abstract_state_ticket(i));
EXPECT_TRUE(xa_tracker.HasPrerequisite(tracker));
EXPECT_TRUE(tracker.HasSubscriber(xa_tracker));
}
}
// Tests that the leaf system reserved the declared Parameters with default
// values, that they are modifiable, and that dependency wiring is set up
// correctly for them.
TEST_F(LeafSystemTest, NumericParameters) {
std::unique_ptr<Context<double>> context = system_.CreateDefaultContext();
const BasicVector<double>& vec =
system_.GetVanillaNumericParameters(*context);
EXPECT_EQ(13.0, vec[0]);
EXPECT_EQ(7.0, vec[1]);
BasicVector<double>& mutable_vec =
system_.GetVanillaMutableNumericParameters(context.get());
mutable_vec[1] = 42.0;
EXPECT_EQ(42.0, vec[1]);
EXPECT_EQ(system_.num_numeric_parameter_groups(), 1);
const DependencyTracker& pn_tracker =
context->get_tracker(system_.pn_ticket());
for (NumericParameterIndex i(0);
i < system_.num_numeric_parameter_groups(); ++i) {
const DependencyTracker& tracker =
context->get_tracker(system_.numeric_parameter_ticket(i));
EXPECT_TRUE(pn_tracker.HasPrerequisite(tracker));
EXPECT_TRUE(tracker.HasSubscriber(pn_tracker));
}
}
// Tests that the leaf system reserved the declared abstract Parameters with
// default values, that they are modifiable, and that dependency wiring is set
// up correctly for them.
TEST_F(LeafSystemTest, AbstractParameters) {
std::unique_ptr<Context<double>> context = system_.CreateDefaultContext();
const std::string& param = context->get_abstract_parameter(0 /*index*/)
.get_value<std::string>();
EXPECT_EQ(param, "parameter value");
std::string& mutable_param =
context->get_mutable_abstract_parameter(0 /*index*/)
.get_mutable_value<std::string>();
mutable_param = "modified parameter value";
EXPECT_EQ("modified parameter value", param);
EXPECT_EQ(system_.num_abstract_parameters(), 1);
const DependencyTracker& pa_tracker =
context->get_tracker(system_.pa_ticket());
for (AbstractParameterIndex i(0); i < system_.num_abstract_parameters();
++i) {
const DependencyTracker& tracker =
context->get_tracker(system_.abstract_parameter_ticket(i));
EXPECT_TRUE(pa_tracker.HasPrerequisite(tracker));
EXPECT_TRUE(tracker.HasSubscriber(pa_tracker));
}
}
// Tests that the leaf system reserved the declared misc continuous state.
TEST_F(LeafSystemTest, DeclareVanillaMiscContinuousState) {
system_.DeclareContinuousState(2);
// Tests num_continuous_states without a context.
EXPECT_EQ(2, system_.num_continuous_states());
std::unique_ptr<Context<double>> context = system_.CreateDefaultContext();
const ContinuousState<double>& xc = context->get_continuous_state();
EXPECT_EQ(2, xc.size());
EXPECT_EQ(0, xc.get_generalized_position().size());
EXPECT_EQ(0, xc.get_generalized_velocity().size());
EXPECT_EQ(2, xc.get_misc_continuous_state().size());
}
// Tests that the leaf system reserved the declared misc continuous state of
// interesting custom type.
TEST_F(LeafSystemTest, DeclareTypedMiscContinuousState) {
system_.DeclareContinuousState(MyVector2d());
// Tests num_continuous_states without a context.
EXPECT_EQ(2, system_.num_continuous_states());
std::unique_ptr<Context<double>> context = system_.CreateDefaultContext();
const ContinuousState<double>& xc = context->get_continuous_state();
// Check that type was preserved.
EXPECT_NE(nullptr, dynamic_cast<MyVector2d*>(
&context->get_mutable_continuous_state_vector()));
EXPECT_EQ(2, xc.size());
EXPECT_EQ(0, xc.get_generalized_position().size());
EXPECT_EQ(0, xc.get_generalized_velocity().size());
EXPECT_EQ(2, xc.get_misc_continuous_state().size());
}
// Tests that the leaf system reserved the declared continuous state with
// second-order structure.
TEST_F(LeafSystemTest, DeclareVanillaContinuousState) {
system_.DeclareContinuousState(4, 3, 2);
// Tests num_continuous_states without a context.
EXPECT_EQ(4 + 3 + 2, system_.num_continuous_states());
std::unique_ptr<Context<double>> context = system_.CreateDefaultContext();
const ContinuousState<double>& xc = context->get_continuous_state();
EXPECT_EQ(4 + 3 + 2, xc.size());
EXPECT_EQ(4, xc.get_generalized_position().size());
EXPECT_EQ(3, xc.get_generalized_velocity().size());
EXPECT_EQ(2, xc.get_misc_continuous_state().size());
}
// Tests that the leaf system reserved the declared continuous state with
// second-order structure of interesting custom type.
TEST_F(LeafSystemTest, DeclareTypedContinuousState) {
using MyVector9d = MyVector<double, 4 + 3 + 2>;
auto state_index = system_.DeclareContinuousState(MyVector9d(), 4, 3, 2);
// Tests num_continuous_states without a context.
EXPECT_EQ(4 + 3 + 2, system_.num_continuous_states());
std::unique_ptr<Context<double>> context = system_.CreateDefaultContext();
const ContinuousState<double>& xc = context->get_continuous_state();
// Check that type was preserved.
EXPECT_NE(nullptr, dynamic_cast<MyVector9d*>(
&context->get_mutable_continuous_state_vector()));
// Check that dimensions were preserved.
EXPECT_EQ(4 + 3 + 2, xc.size());
EXPECT_EQ(4, xc.get_generalized_position().size());
EXPECT_EQ(3, xc.get_generalized_velocity().size());
EXPECT_EQ(2, xc.get_misc_continuous_state().size());
// Check that the state retains its type when placed on an output port.
const auto& state_output_port = system_.DeclareStateOutputPort(
"state", state_index);
context = system_.CreateDefaultContext();
const Eigen::VectorXd ones = VectorXd::Ones(9);
context->SetContinuousState(ones);
EXPECT_EQ(state_output_port.Eval<MyVector9d>(*context).get_value(), ones);
}
TEST_F(LeafSystemTest, ContinuousStateBelongsWithSystem) {
// Successfully calc using a storage that was created by the system.
std::unique_ptr<ContinuousState<double>> derivatives =
system_.AllocateTimeDerivatives();
EXPECT_EQ(derivatives->get_system_id(), context_.get_system_id());
DRAKE_EXPECT_NO_THROW(
system_.CalcTimeDerivatives(context_, derivatives.get()));
// Successfully calc using storage that was indirectly created by the system.
auto temp_context = system_.AllocateContext();
ContinuousState<double>& temp_xc =
temp_context->get_mutable_continuous_state();
DRAKE_EXPECT_NO_THROW(
system_.CalcTimeDerivatives(context_, &temp_xc));
// Cannot ask other_system to calc into storage that was created by the
// original system.
TestSystem<double> other_system;
auto other_context = other_system.AllocateContext();
DRAKE_EXPECT_THROWS_MESSAGE(
other_system.CalcTimeDerivatives(*other_context, derivatives.get()),
".*::ContinuousState<double> was not created for.*::TestSystem.*");
}
TEST_F(LeafSystemTest, DeclarePerStepEvents) {
std::unique_ptr<Context<double>> context = system_.CreateDefaultContext();
system_.DeclarePerStepEvent(PublishEvent<double>());
system_.DeclarePerStepEvent(DiscreteUpdateEvent<double>());
system_.DeclarePerStepEvent(UnrestrictedUpdateEvent<double>());
system_.GetPerStepEvents(*context, event_info_.get());
{
const auto& events = leaf_info_->get_publish_events().get_events();
EXPECT_EQ(events.size(), 1);
EXPECT_EQ(events.front()->get_trigger_type(), TriggerType::kPerStep);
}
{
const auto& events = leaf_info_->get_discrete_update_events().get_events();
EXPECT_EQ(events.size(), 1);
EXPECT_EQ(events.front()->get_trigger_type(), TriggerType::kPerStep);
}
{
const auto& events =
leaf_info_->get_unrestricted_update_events().get_events();
EXPECT_EQ(events.size(), 1);
EXPECT_EQ(events.front()->get_trigger_type(), TriggerType::kPerStep);
}
}
TEST_F(LeafSystemTest, DeclarePeriodicEvents) {
std::unique_ptr<Context<double>> context = system_.CreateDefaultContext();
system_.DeclarePeriodicEvent(0.1, 0.0, PublishEvent<double>());
system_.DeclarePeriodicEvent(0.1, 0.0, DiscreteUpdateEvent<double>());
system_.DeclarePeriodicEvent(0.1, 0.0, UnrestrictedUpdateEvent<double>());
system_.GetPeriodicEvents(*context, event_info_.get());
{
const auto& events = leaf_info_->get_publish_events().get_events();
EXPECT_EQ(events.size(), 1);
EXPECT_EQ(events.front()->get_trigger_type(), TriggerType::kPeriodic);
}
{
const auto& events = leaf_info_->get_discrete_update_events().get_events();
EXPECT_EQ(events.size(), 1);
EXPECT_EQ(events.front()->get_trigger_type(), TriggerType::kPeriodic);
}
{
const auto& events =
leaf_info_->get_unrestricted_update_events().get_events();
EXPECT_EQ(events.size(), 1);
EXPECT_EQ(events.front()->get_trigger_type(), TriggerType::kPeriodic);
}
}
// A system that exercises the model_value-based input and output ports,
// as well as model-declared params.
class DeclaredModelPortsSystem : public LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DeclaredModelPortsSystem);
DeclaredModelPortsSystem() {
// Use these to validate the expected return type from each method.
InputPort<double>* in_port{nullptr};
LeafOutputPort<double>* out_port{nullptr};
in_port = &DeclareInputPort("input", kVectorValued, 1);
unused(in_port);
in_port = &DeclareVectorInputPort("vector_input", MyVector2d());
unused(in_port);
in_port = &DeclareAbstractInputPort("abstract_input", Value<int>(22));
unused(in_port);
in_port = &DeclareVectorInputPort("uniform", MyVector2d(),
RandomDistribution::kUniform);
unused(in_port);
in_port = &DeclareVectorInputPort("gaussian", MyVector2d(),
RandomDistribution::kGaussian);
unused(in_port);
// Output port 0 uses a BasicVector base class model.
out_port =
&DeclareVectorOutputPort("basic_vector", BasicVector<double>(3),
&DeclaredModelPortsSystem::CalcBasicVector3);
unused(out_port);
// Output port 1 uses a class derived from BasicVector.
out_port = &DeclareVectorOutputPort(
"my_vector", MyVector4d(), &DeclaredModelPortsSystem::CalcMyVector4d);
unused(out_port);
// Output port 2 uses a concrete string model.
out_port = &DeclareAbstractOutputPort(
"string", std::string("45"), &DeclaredModelPortsSystem::CalcString);
unused(out_port);
// Output port 3 uses the "Advanced" methods that take a model
// and a general calc function rather than a calc method.
out_port = &DeclareVectorOutputPort(
"advanced", BasicVector<double>(2),
[](const Context<double>&, BasicVector<double>* out) {
ASSERT_NE(out, nullptr);
EXPECT_EQ(out->size(), 2);
out->SetAtIndex(0, 10.);
out->SetAtIndex(1, 20.);
});
unused(out_port);
DeclareNumericParameter(*MyVector2d::Make(1.1, 2.2));
}
const BasicVector<double>& expected_basic() const { return expected_basic_; }
const MyVector4d& expected_myvector() const { return *expected_myvector_; }
private:
void CalcBasicVector3(const Context<double>&,
BasicVector<double>* out) const {
ASSERT_NE(out, nullptr);
EXPECT_EQ(out->size(), 3);
out->get_mutable_value() = expected_basic().get_value();
}
void CalcMyVector4d(const Context<double>&, MyVector4d* out) const {
ASSERT_NE(out, nullptr);
out->get_mutable_value() = expected_myvector().get_value();
}
void CalcAbstractString(const Context<double>&, AbstractValue* out) const {
ASSERT_NE(out, nullptr);
out->get_mutable_value<std::string>() = "abstract string";
}
void CalcString(const Context<double>&, std::string* out) const {
ASSERT_NE(out, nullptr);
*out = "concrete string";
}
const BasicVector<double> expected_basic_{1., .5, .25};
std::unique_ptr<MyVector4d> expected_myvector_{
MyVector4d::Make(4., 3., 2., 1.)};
};
// Tests that Declare{Vector,Abstract}{Input,Output}Port end up with the
// correct topology, and that the all_input_ports dependency tracker is
// properly subscribed to the input ports in an allocated context.
GTEST_TEST(ModelLeafSystemTest, ModelPortsTopology) {
DeclaredModelPortsSystem dut;
ASSERT_EQ(dut.num_input_ports(), 5);
ASSERT_EQ(dut.num_output_ports(), 4);
// Check that SystemBase port APIs work properly.
const InputPortBase& in3_base = dut.get_input_port_base(InputPortIndex(3));
EXPECT_EQ(in3_base.get_index(), 3);
const DependencyTicket in3_ticket = dut.input_port_ticket(InputPortIndex(3));
const DependencyTicket in4_ticket = dut.input_port_ticket(InputPortIndex(4));
EXPECT_TRUE(in3_ticket.is_valid() && in4_ticket.is_valid());
EXPECT_NE(in3_ticket, in4_ticket); // We don't know the actual values.
DRAKE_EXPECT_THROWS_MESSAGE(
dut.get_input_port_base(InputPortIndex(10)),
"System.*get_input_port_base().*no input port.*10.*only 5.*");
// Check DependencyTracker setup for input ports.
auto context = dut.AllocateContext();
const DependencyTracker& all_inputs_tracker =
context->get_tracker(dut.all_input_ports_ticket());
for (InputPortIndex i(0); i < dut.num_input_ports(); ++i) {
const DependencyTracker& tracker =
context->get_tracker(dut.input_port_ticket(i));
EXPECT_TRUE(all_inputs_tracker.HasPrerequisite(tracker));
EXPECT_TRUE(tracker.HasSubscriber(all_inputs_tracker));
}
const OutputPortBase& out2_base =
dut.get_output_port_base(OutputPortIndex(2));
EXPECT_EQ(out2_base.get_index(), 2);
const DependencyTicket out2_ticket =
dut.output_port_ticket(OutputPortIndex(2));
const DependencyTicket out3_ticket =
dut.output_port_ticket(OutputPortIndex(3));
EXPECT_TRUE(out2_ticket.is_valid() && out3_ticket.is_valid());
EXPECT_NE(out2_ticket, out3_ticket); // We don't know the actual values.
DRAKE_EXPECT_THROWS_MESSAGE(
dut.get_output_port_base(OutputPortIndex(7)),
"System.*get_output_port_base().*no output port.*7.*only 4.*");
const InputPort<double>& in0 = dut.get_input_port(0);
const InputPort<double>& in1 = dut.get_input_port(1);
const InputPort<double>& in2 = dut.get_input_port(2);
const InputPort<double>& in3 = dut.get_input_port(3);
const InputPort<double>& in4 = dut.get_input_port(4);
const OutputPort<double>& out0 = dut.get_output_port(0);
const OutputPort<double>& out1 = dut.get_output_port(1);
const OutputPort<double>& out2 = dut.get_output_port(2);
const OutputPort<double>& out3 = dut.get_output_port(3);
EXPECT_EQ(in0.get_data_type(), kVectorValued);
EXPECT_EQ(in1.get_data_type(), kVectorValued);
EXPECT_EQ(in2.get_data_type(), kAbstractValued);
EXPECT_EQ(in3.get_data_type(), kVectorValued);
EXPECT_EQ(in4.get_data_type(), kVectorValued);
EXPECT_EQ(out0.get_data_type(), kVectorValued);
EXPECT_EQ(out1.get_data_type(), kVectorValued);
EXPECT_EQ(out2.get_data_type(), kAbstractValued);
EXPECT_EQ(out3.get_data_type(), kVectorValued);
EXPECT_EQ(in0.size(), 1);
EXPECT_EQ(in1.size(), 2);
EXPECT_EQ(in3.size(), 2);
EXPECT_EQ(in4.size(), 2);
EXPECT_EQ(out0.size(), 3);
EXPECT_EQ(out1.size(), 4);
EXPECT_EQ(out3.size(), 2);
EXPECT_FALSE(in0.is_random());
EXPECT_FALSE(in1.is_random());
EXPECT_FALSE(in2.is_random());
EXPECT_TRUE(in3.is_random());
EXPECT_TRUE(in4.is_random());
EXPECT_FALSE(in0.get_random_type());
EXPECT_FALSE(in1.get_random_type());
EXPECT_FALSE(in2.get_random_type());
EXPECT_EQ(in3.get_random_type(), RandomDistribution::kUniform);
EXPECT_EQ(in4.get_random_type(), RandomDistribution::kGaussian);
}
// A system that incorrectly declares an input port.
class MissingModelAbstractInputSystem : public LeafSystem<double> {
public:
MissingModelAbstractInputSystem() {
this->DeclareInputPort("no_model_input", kAbstractValued, 0);
}
};
GTEST_TEST(ModelLeafSystemTest, MissingModelAbstractInput) {
MissingModelAbstractInputSystem dut;
dut.set_name("dut");
DRAKE_EXPECT_THROWS_MESSAGE(
dut.AllocateInputAbstract(dut.get_input_port(0)),
"System::AllocateInputAbstract\\(\\): a System with abstract input "
"ports must pass a model_value to DeclareAbstractInputPort; the "
"port\\[0\\] named 'no_model_input' did not do so \\(System ::dut\\)");
}
// Check that model inputs place validity checks on FixInput calls. (This is
// more of an acceptance test than a unit test. The relevant code is sprinkled
// across a few files.) Note that even the debug builds might not detect the
// kind of use-after-free errors that this test tries to expose; the dynamic
// analysis build configurations such as valgrind or msan might be needed in
// order to detect the errors.
GTEST_TEST(ModelLeafSystemTest, ModelInputGovernsFixedInput) {
// The Context checks must be able to outlive the System that created them.
auto dut = std::make_unique<DeclaredModelPortsSystem>();
dut->set_name("dut");
auto context = dut->CreateDefaultContext();
dut.reset();
// The first port should only accept a 1d vector.
context->FixInputPort(0, Value<BasicVector<double>>(
VectorXd::Constant(1, 0.0)));
DRAKE_EXPECT_THROWS_MESSAGE(
context->FixInputPort(0, Value<BasicVector<double>>(
VectorXd::Constant(2, 0.0))),
"System::FixInputPortTypeCheck\\(\\): expected value of type "
"drake::systems::BasicVector<double> with size=1 "
"for input port 'input' \\(index 0\\) but the actual type was "
"drake::systems::BasicVector<double> with size=2. "
"\\(System ::dut\\)");
DRAKE_EXPECT_THROWS_MESSAGE(
context->FixInputPort(0, Value<std::string>()),
"System::FixInputPortTypeCheck\\(\\): expected value of type "
"drake::Value<drake::systems::BasicVector<double>> "
"for input port 'input' \\(index 0\\) but the actual type was "
"drake::Value<std::string>. "
"\\(System ::dut\\)");
// The second port should only accept ints.
context->FixInputPort(2, Value<int>(11));
DRAKE_EXPECT_THROWS_MESSAGE(
context->FixInputPort(2, Value<std::string>()),
"System::FixInputPortTypeCheck\\(\\): expected value of type "
"int "
"for input port 'abstract_input' \\(index 2\\) but the actual type was "
"std::string. "
"\\(System ::dut\\)");
}
// Check that names can be assigned to the ports through all of the various
// APIs.
GTEST_TEST(ModelLeafSystemTest, ModelPortNames) {
DeclaredModelPortsSystem dut;
EXPECT_EQ(dut.get_input_port(0).get_name(), "input");
EXPECT_EQ(dut.get_input_port(1).get_name(), "vector_input");
EXPECT_EQ(dut.get_input_port(2).get_name(), "abstract_input");
EXPECT_EQ(dut.get_output_port(0).get_name(), "basic_vector");
EXPECT_EQ(dut.get_output_port(1).get_name(), "my_vector");
EXPECT_EQ(dut.get_output_port(2).get_name(), "string");
EXPECT_EQ(dut.get_output_port(3).get_name(), "advanced");
}
// Tests that the model values specified in Declare{...} are actually used by
// the corresponding Allocate{...} methods to yield correct types and values.
GTEST_TEST(ModelLeafSystemTest, ModelPortsInput) {
DeclaredModelPortsSystem dut;
// Check that BasicVector<double>(1) came out.
auto input0 = dut.AllocateInputVector(dut.get_input_port(0));
ASSERT_NE(input0, nullptr);
EXPECT_EQ(input0->size(), 1);
// Check that MyVector2d came out.
auto input1 = dut.AllocateInputVector(dut.get_input_port(1));
ASSERT_NE(input1, nullptr);
MyVector2d* downcast_input1 = dynamic_cast<MyVector2d*>(input1.get());
ASSERT_NE(downcast_input1, nullptr);
// Check that Value<int>(22) came out.
auto input2 = dut.AllocateInputAbstract(dut.get_input_port(2));
ASSERT_NE(input2, nullptr);
int downcast_input2{};
DRAKE_EXPECT_NO_THROW(downcast_input2 = input2->get_value<int>());
EXPECT_EQ(downcast_input2, 22);
}
// Tests that Declare{Vector,Abstract}OutputPort flow through to allocating the
// correct values.
GTEST_TEST(ModelLeafSystemTest, ModelPortsAllocOutput) {
DeclaredModelPortsSystem dut;
auto system_output = dut.AllocateOutput();
// Check that BasicVector<double>(3) came out.
auto output0 = system_output->get_vector_data(0);
ASSERT_NE(output0, nullptr);
EXPECT_EQ(output0->size(), 3);
// Check that MyVector4d came out.
auto output1 = system_output->GetMutableVectorData(1);
ASSERT_NE(output1, nullptr);
MyVector4d* downcast_output1 = dynamic_cast<MyVector4d*>(output1);
ASSERT_NE(downcast_output1, nullptr);
// Check that Value<string>("45") came out (even though we only specified
// a concrete string.
auto output2 = system_output->get_data(2);
ASSERT_NE(output2, nullptr);
std::string downcast_output2{};
DRAKE_EXPECT_NO_THROW(downcast_output2 = output2->get_value<std::string>());
EXPECT_EQ(downcast_output2, "45");
// Check that BasicVector<double>(2) came out.
auto output3 = system_output->get_vector_data(3);
ASSERT_NE(output3, nullptr);
EXPECT_EQ(output3->size(), 2);
}
// Tests that calculator functions were generated correctly for the
// model-based output ports.
GTEST_TEST(ModelLeafSystemTest, ModelPortsCalcOutput) {
DeclaredModelPortsSystem dut;
auto context = dut.CreateDefaultContext();
// Make sure caching is on locally, even if it is off by default.
context->EnableCaching();
// Calculate values for each output port and save copies of those values.
std::vector<std::unique_ptr<AbstractValue>> values;
for (OutputPortIndex i(0); i < 4; ++i) {
const OutputPort<double>& out = dut.get_output_port(i);
values.emplace_back(out.Allocate());
out.Calc(*context, values.back().get());
}
const auto& port2 = dut.get_output_port(OutputPortIndex(2));
const auto& cache2 =
dynamic_cast<const LeafOutputPort<double>&>(port2).cache_entry();
const auto& cacheval2 = cache2.get_cache_entry_value(*context);
EXPECT_EQ(cacheval2.serial_number(), 1);
EXPECT_TRUE(cache2.is_out_of_date(*context));
EXPECT_THROW(cache2.GetKnownUpToDate<std::string>(*context),
std::logic_error);
const std::string& str2_cached = port2.Eval<std::string>(*context);
EXPECT_EQ(str2_cached, "concrete string");
EXPECT_EQ(cacheval2.serial_number(), 2);
EXPECT_FALSE(cache2.is_out_of_date(*context));
EXPECT_EQ(cache2.GetKnownUpToDate<std::string>(*context),
"concrete string"); // Doesn't throw now.
// Check that setting time invalidates correctly. Note that the method
// *may* avoid invalidation if the time hasn't actually changed.
// Should invalidate time- and everything-dependents.
context->SetTime(context->get_time() + 1.);
EXPECT_TRUE(cache2.is_out_of_date(*context));
EXPECT_EQ(cacheval2.serial_number(), 2); // Unchanged since invalid.
(void)port2.template Eval<AbstractValue>(*context); // Recalculate.
EXPECT_FALSE(cache2.is_out_of_date(*context));
EXPECT_EQ(cacheval2.serial_number(), 3);
(void)port2.template Eval<AbstractValue>(*context); // Should do nothing.
EXPECT_EQ(cacheval2.serial_number(), 3);
// Should invalidate accuracy- and everything-dependents. Note that the
// method *may* avoid invalidation if the accuracy hasn't actually changed.
EXPECT_FALSE(context->get_accuracy()); // None set initially.
context->SetAccuracy(.000025); // This is a change.
EXPECT_TRUE(cache2.is_out_of_date(*context));
(void)port2.template Eval<AbstractValue>(*context); // Recalculate.
EXPECT_FALSE(cache2.is_out_of_date(*context));
EXPECT_EQ(cacheval2.serial_number(), 4);
// Downcast to concrete types.
const BasicVector<double>* vec0{};
const MyVector4d* vec1{};
const std::string* str2{};
const BasicVector<double>* vec3{};
DRAKE_EXPECT_NO_THROW(vec0 = &values[0]->get_value<BasicVector<double>>());
DRAKE_EXPECT_NO_THROW(vec1 = dynamic_cast<const MyVector4d*>(
&values[1]->get_value<BasicVector<double>>()));
DRAKE_EXPECT_NO_THROW(str2 = &values[2]->get_value<std::string>());
DRAKE_EXPECT_NO_THROW(vec3 = &values[3]->get_value<BasicVector<double>>());
// Check the calculated values.
EXPECT_EQ(vec0->get_value(), dut.expected_basic().get_value());
EXPECT_EQ(vec1->get_value(), dut.expected_myvector().get_value());
EXPECT_EQ(*str2, "concrete string");
EXPECT_EQ(vec3->get_value(), Vector2d(10., 20.));
}
// Tests that the leaf system reserved the declared parameters of interesting
// custom type.
GTEST_TEST(ModelLeafSystemTest, ModelNumericParams) {
DeclaredModelPortsSystem dut;
auto context = dut.CreateDefaultContext();
ASSERT_EQ(context->num_numeric_parameter_groups(), 1);
const BasicVector<double>& param = context->get_numeric_parameter(0);
// Check that type was preserved.
ASSERT_TRUE(is_dynamic_castable<const MyVector2d>(¶m));
EXPECT_EQ(2, param.size());
EXPECT_EQ(1.1, param[0]);
EXPECT_EQ(2.2, param[1]);
}
// Tests that various DeclareDiscreteState() signatures work correctly and
// that the model values get used in SetDefaultContext().
GTEST_TEST(ModelLeafSystemTest, ModelDiscreteState) {
class DeclaredModelDiscreteStateSystem : public LeafSystem<double> {
public:
// This should produce three discrete variable groups.
DeclaredModelDiscreteStateSystem() {
// Takes a BasicVector.
indexes_.push_back(
DeclareDiscreteState(MyVector2d(Vector2d(1., 2.))));
DeclareStateOutputPort("state", indexes_.back());
// Takes an Eigen vector.
indexes_.push_back(DeclareDiscreteState(Vector3d(3., 4., 5.)));
// Four state variables, initialized to zero.
indexes_.push_back(DeclareDiscreteState(4));
}
std::vector<DiscreteStateIndex> indexes_;
};
DeclaredModelDiscreteStateSystem dut;
EXPECT_EQ(dut.num_discrete_state_groups(), 3);
for (int i=0; i < static_cast<int>(dut.indexes_.size()); ++i)
EXPECT_TRUE(dut.indexes_[i] == i);
auto context = dut.CreateDefaultContext();
DiscreteValues<double>& xd = context->get_mutable_discrete_state();
EXPECT_EQ(xd.num_groups(), 3);
// Concrete type and value should have been preserved.
BasicVector<double>& xd0 = xd.get_mutable_vector(0);
EXPECT_TRUE(is_dynamic_castable<const MyVector2d>(&xd0));
EXPECT_EQ(xd0.get_value(), Vector2d(1., 2.));
EXPECT_EQ(dut.get_output_port().Eval<MyVector2d>(*context).get_value(),
Vector2d(1., 2.));
// Eigen vector should have been stored in a BasicVector-type object.
BasicVector<double>& xd1 = xd.get_mutable_vector(1);
EXPECT_EQ(typeid(xd1), typeid(BasicVector<double>));
EXPECT_EQ(xd1.get_value(), Vector3d(3., 4., 5.));
// Discrete state with no model should act as though it were given an
// all-zero Eigen vector model.
BasicVector<double>& xd2 = xd.get_mutable_vector(2);
EXPECT_EQ(typeid(xd2), typeid(BasicVector<double>));
EXPECT_EQ(xd2.get_value(), Vector4d(0., 0., 0., 0.));
// Now make changes, then see if SetDefaultContext() puts them back.
xd0.SetFromVector(Vector2d(9., 10.));
xd1.SetFromVector(Vector3d(11., 12., 13.));
xd2.SetFromVector(Vector4d(1., 2., 3., 4.));
// Ensure that the cache knows that the values have changed.
context->get_mutable_discrete_state();
// Of course that had to work, but let's just prove it ...
EXPECT_EQ(xd0.get_value(), Vector2d(9., 10.));
EXPECT_EQ(xd1.get_value(), Vector3d(11., 12., 13.));
EXPECT_EQ(xd2.get_value(), Vector4d(1., 2., 3., 4.));
EXPECT_EQ(dut.get_output_port().Eval<MyVector2d>(*context).get_value(),
Vector2d(9., 10.));
dut.SetDefaultContext(&*context);
EXPECT_EQ(xd0.get_value(), Vector2d(1., 2.));
EXPECT_EQ(xd1.get_value(), Vector3d(3., 4., 5.));
EXPECT_EQ(xd2.get_value(), Vector4d(0., 0., 0., 0.));
}
// Tests that DeclareAbstractState works expectedly.
GTEST_TEST(ModelLeafSystemTest, ModelAbstractState) {
class DeclaredModelAbstractStateSystem : public LeafSystem<double> {
public:
DeclaredModelAbstractStateSystem() {
DeclareAbstractState(Value<int>(1));
DeclareAbstractState(Value<std::string>("wow"));
DeclareStateOutputPort("state", AbstractStateIndex{1});
}
};
DeclaredModelAbstractStateSystem dut;
// Allocate the resources that were created on system construction.
auto context = dut.AllocateContext();
// Check that the allocations were made and with the correct type
DRAKE_EXPECT_NO_THROW(context->get_abstract_state<int>(0));
DRAKE_EXPECT_NO_THROW(context->get_abstract_state<std::string>(1));
EXPECT_EQ(dut.get_output_port().Eval<std::string>(*context), "wow");
// Mess with the abstract values on the context.
AbstractValues& values = context->get_mutable_abstract_state();
AbstractValue& value = values.get_mutable_value(1);
DRAKE_EXPECT_NO_THROW(value.set_value<std::string>("whoops"));
EXPECT_EQ(context->get_abstract_state<std::string>(1), "whoops");
EXPECT_EQ(dut.get_output_port().Eval<std::string>(*context), "whoops");
// Ask it to reset to the defaults specified on system construction.
dut.SetDefaultContext(context.get());
EXPECT_EQ(context->get_abstract_state<int>(0), 1);
EXPECT_EQ(context->get_abstract_state<std::string>(1), "wow");
// Just create a default context directly.
auto default_context = dut.CreateDefaultContext();
EXPECT_EQ(default_context->get_abstract_state<int>(0), 1);
EXPECT_EQ(default_context->get_abstract_state<std::string>(1), "wow");
}
// A system that exercises the non-model based output port declarations.
// These include declarations that take only a calculator function and use
// default construction for allocation, and those that take an explicit
// allocator as a class method or general function.
// A BasicVector subclass with an initializing default constructor that
// sets it to (100,200).
class DummyVec2 : public BasicVector<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DummyVec2)
DummyVec2(double e0, double e1) : BasicVector<double>(2) {
SetAtIndex(0, e0);
SetAtIndex(1, e1);
}
DummyVec2() : DummyVec2(100., 200.) {}
private:
// Note that the actual data is copied by the BasicVector base class.
DummyVec2* DoClone() const override { return new DummyVec2; }
};
// This bare struct is used to verify that we value-initialize output ports.
struct SomePOD {
int some_int;
double some_double;
};
class DeclaredNonModelOutputSystem : public LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DeclaredNonModelOutputSystem);
DeclaredNonModelOutputSystem() {
// Use this to validate the expected return type from each method.
LeafOutputPort<double>* port{nullptr};
// Output port 0 default-constructs a class derived from BasicVector as
// its allocator.
port = &DeclareVectorOutputPort(
kUseDefaultName, &DeclaredNonModelOutputSystem::CalcDummyVec2);
unused(port);
// Output port 1 default-constructs a string as its allocator.
port = &DeclareAbstractOutputPort(
kUseDefaultName, &DeclaredNonModelOutputSystem::CalcString);
unused(port);
// Output port 2 uses the "Advanced" method for abstract ports, providing
// explicit non-member functors for allocator and calculator.
port = &DeclareAbstractOutputPort(
kUseDefaultName,
[]() { return AbstractValue::Make<int>(-2); },
[](const Context<double>&, AbstractValue* out) {
ASSERT_NE(out, nullptr);
int* int_out{};
DRAKE_EXPECT_NO_THROW(int_out = &out->get_mutable_value<int>());
*int_out = 321;
});
unused(port);
// Output port 3 uses a default-constructed bare struct which should be
// value-initialized.
port = &DeclareAbstractOutputPort(
kUseDefaultName, &DeclaredNonModelOutputSystem::CalcPOD);
unused(port);
}
int calc_dummy_vec2_calls() const { return count_calc_dummy_vec2_; }
int calc_string_calls() const { return count_calc_string_; }
int calc_POD_calls() const { return count_calc_POD_; }
private:
void CalcDummyVec2(const Context<double>&, DummyVec2* out) const {
++count_calc_dummy_vec2_;
ASSERT_NE(out, nullptr);
EXPECT_EQ(out->size(), 2);
out->get_mutable_value() = Vector2d(-100., -200);
}
// Explicit allocator method.
std::string MakeString() const {
return std::string("freshly made");
}
void CalcString(const Context<double>&, std::string* out) const {
++count_calc_string_;
ASSERT_NE(out, nullptr);
*out = "calc'ed string";
}
void CalcPOD(const Context<double>&, SomePOD* out) const {
++count_calc_POD_;
ASSERT_NE(out, nullptr);
*out = {-10, 3.25};
}
// Call counters for caching checks.
mutable int count_calc_dummy_vec2_{0};
mutable int count_calc_string_{0};
mutable int count_calc_POD_{0};
};
// Tests that non-model based Declare{Vector,Abstract}OutputPort generate the
// expected output port allocators, and that their Calc and Eval functions work.
GTEST_TEST(NonModelLeafSystemTest, NonModelPortsOutput) {
DeclaredNonModelOutputSystem dut;
auto context = dut.CreateDefaultContext();
auto system_output = dut.AllocateOutput(); // Invokes all allocators.
// Make sure caching is on locally, even if it is off by default.
context->EnableCaching();
// Check topology.
EXPECT_EQ(dut.num_input_ports(), 0);
ASSERT_EQ(dut.num_output_ports(), 4);
auto& out0 = dut.get_output_port(0);
auto& out1 = dut.get_output_port(1);
auto& out2 = dut.get_output_port(2);
auto& out3 = dut.get_output_port(3);
EXPECT_EQ(out0.get_data_type(), kVectorValued);
EXPECT_EQ(out1.get_data_type(), kAbstractValued);
EXPECT_EQ(out2.get_data_type(), kAbstractValued);
EXPECT_EQ(out3.get_data_type(), kAbstractValued);
// Sanity check output port prerequisites. Leaf ports should not designate
// a subsystem since they are resolved internally. We don't know the right
// dependency ticket, but at least it should be valid.
for (OutputPortIndex i(0); i < dut.num_output_ports(); ++i) {
internal::OutputPortPrerequisite prereq =
dut.get_output_port(i).GetPrerequisite();
EXPECT_FALSE(prereq.child_subsystem.has_value());
EXPECT_TRUE(prereq.dependency.is_valid());
}
// Check that DummyVec2 came out, default constructed to (100,200).
auto output0 = system_output->GetMutableVectorData(0);
ASSERT_NE(output0, nullptr);
EXPECT_EQ(output0->size(), 2);
auto out0_dummy = dynamic_cast<DummyVec2*>(output0);
EXPECT_NE(out0_dummy, nullptr);
EXPECT_EQ(out0_dummy->get_value(), Vector2d(100., 200.));
out0.Calc(*context, system_output->GetMutableData(0));
EXPECT_EQ(out0_dummy->get_value(), Vector2d(-100., -200.));
EXPECT_EQ(dut.calc_dummy_vec2_calls(), 1);
EXPECT_EQ(out0.Eval<BasicVector<double>>(*context).get_value(),
out0_dummy->get_value());
EXPECT_EQ(dut.calc_dummy_vec2_calls(), 2);
out0.Eval<BasicVector<double>>(*context);
EXPECT_EQ(dut.calc_dummy_vec2_calls(), 2); // Should have been cached.
// Check that Value<string>() came out, default initialized to empty.
auto output1 = system_output->GetMutableData(1);
ASSERT_NE(output1, nullptr);
const std::string* downcast_output1{};
DRAKE_EXPECT_NO_THROW(downcast_output1 = &output1->get_value<std::string>());
EXPECT_TRUE(downcast_output1->empty());
out1.Calc(*context, output1);
EXPECT_EQ(*downcast_output1, "calc'ed string");
EXPECT_EQ(dut.calc_string_calls(), 1);
EXPECT_EQ(out1.Eval<std::string>(*context), *downcast_output1);
EXPECT_EQ(dut.calc_string_calls(), 2);
out1.Eval<std::string>(*context);
EXPECT_EQ(dut.calc_string_calls(), 2); // Should have been cached.
// Check that Value<int> came out, default initialized to -2.
auto output2 = system_output->GetMutableData(2);
ASSERT_NE(output2, nullptr);
const int* downcast_output2{};
DRAKE_EXPECT_NO_THROW(downcast_output2 = &output2->get_value<int>());
EXPECT_EQ(*downcast_output2, -2);
out2.Calc(*context, output2);
EXPECT_EQ(*downcast_output2, 321);
// Check that Value<SomePOD>{} came out, value initialized. Note that this
// is not a perfect test since the values *could* come out zero by accident
// even if the value initializer had not been called. Better than nothing!
auto output3 = system_output->GetMutableData(3);
ASSERT_NE(output3, nullptr);
const SomePOD* downcast_output3{};
DRAKE_EXPECT_NO_THROW(downcast_output3 = &output3->get_value<SomePOD>());
EXPECT_EQ(downcast_output3->some_int, 0);
EXPECT_EQ(downcast_output3->some_double, 0.0);
out3.Calc(*context, output3);
EXPECT_EQ(downcast_output3->some_int, -10);
EXPECT_EQ(downcast_output3->some_double, 3.25);
EXPECT_EQ(dut.calc_POD_calls(), 1);
const auto& eval_out = out3.Eval<SomePOD>(*context);
EXPECT_EQ(eval_out.some_int, -10);
EXPECT_EQ(eval_out.some_double, 3.25);
EXPECT_EQ(dut.calc_POD_calls(), 2);
out3.Eval<SomePOD>(*context);
EXPECT_EQ(dut.calc_POD_calls(), 2); // Should have been cached.
}
// Tests that zero-sized vectors can be declared and used.
GTEST_TEST(ZeroSizeSystemTest, AcceptanceTest) {
TestSystem<double> dut;
// Input.
auto& in0 = dut.DeclareVectorInputPort(
kUseDefaultName, BasicVector<double>(0));
EXPECT_EQ(in0.get_data_type(), kVectorValued);
EXPECT_EQ(in0.size(), 0);
// Output.
auto& out0 = dut.DeclareVectorOutputPort(
kUseDefaultName, BasicVector<double>(0),
[](const Context<double>&, BasicVector<double>*) {});
EXPECT_EQ(out0.get_data_type(), kVectorValued);
EXPECT_EQ(out0.size(), 0);
// State.
dut.DeclareContinuousState(0);
const auto& disc0 = dut.DeclareDiscreteState(0);
// Parameters.
const auto& param0 = dut.DeclareNumericParameter(BasicVector<double>(0));
auto context = dut.CreateDefaultContext();
EXPECT_EQ(context->get_continuous_state_vector().size(), 0);
EXPECT_EQ(context->get_discrete_state(disc0).size(), 0);
EXPECT_EQ(context->get_numeric_parameter(param0).size(), 0);
}
// Tests both that an unrestricted update callback is called and that
// modifications to state dimension are caught.
TEST_F(LeafSystemTest, CallbackAndInvalidUpdates) {
// Create 9, 1, and 3 dimensional continuous, discrete, and abstract state
// vectors.
// This needs to be a LeafContext for access to init_ methods.
auto context = dynamic_pointer_cast_or_throw<LeafContext<double>>(
system_.CreateDefaultContext());
context->init_continuous_state(std::make_unique<ContinuousState<double>>(
std::make_unique<BasicVector<double>>(9), 3, 3, 3));
context->init_discrete_state(std::make_unique<DiscreteValues<double>>(
std::make_unique<BasicVector<double>>(1)));
std::vector<std::unique_ptr<AbstractValue>> abstract_data;
abstract_data.push_back(PackValue(3));
abstract_data.push_back(PackValue(5));
abstract_data.push_back(PackValue(7));
context->init_abstract_state(
std::make_unique<AbstractValues>(std::move(abstract_data)));
// Copy the state.
std::unique_ptr<State<double>> x = context->CloneState();
// Create an unrestricted update callback that just copies the state.
LeafCompositeEventCollection<double> leaf_events;
{
UnrestrictedUpdateEvent<double> event(
TriggerType::kPeriodic,
[](const System<double>&, const Context<double>& c,
const Event<double>&, State<double>* s) {
s->SetFrom(*c.CloneState());
return EventStatus::Succeeded();
});
event.AddToComposite(&leaf_events);
}
const EventStatus status = system_.CalcUnrestrictedUpdate(
*context, leaf_events.get_unrestricted_update_events(), x.get());
EXPECT_TRUE(status.succeeded());
// Change the function to change the continuous state dimension.
// Call the unrestricted update function again, now verifying that an
// exception is thrown.
leaf_events.Clear();
{
UnrestrictedUpdateEvent<double> event(
TriggerType::kPeriodic,
[](const System<double>&, const Context<double>& c,
const Event<double>&, State<double>* s) {
s->SetFrom(*c.CloneState());
s->set_continuous_state(std::make_unique<ContinuousState<double>>(
std::make_unique<BasicVector<double>>(4), 4, 0, 0));
return EventStatus::Succeeded();
});
event.AddToComposite(&leaf_events);
}
// Call the unrestricted update function, verifying that an exception
// is thrown.
DRAKE_EXPECT_THROWS_MESSAGE(
system_.CalcUnrestrictedUpdate(
*context, leaf_events.get_unrestricted_update_events(), x.get()),
".*dimensions cannot be changed.*");
// Restore the continuous state (size).
x->set_continuous_state(std::make_unique<ContinuousState<double>>(
std::make_unique<BasicVector<double>>(9), 3, 3, 3));
// Change the event to indicate to change the discrete state dimension.
leaf_events.Clear();
{
UnrestrictedUpdateEvent<double> event(
TriggerType::kPeriodic,
[](const System<double>&, const Context<double>& c,
const Event<double>&, State<double>* s) {
std::vector<std::unique_ptr<BasicVector<double>>> disc_data;
s->SetFrom(*c.CloneState());
disc_data.push_back(std::make_unique<BasicVector<double>>(1));
disc_data.push_back(std::make_unique<BasicVector<double>>(1));
s->set_discrete_state(
std::make_unique<DiscreteValues<double>>(std::move(disc_data)));
return EventStatus::Succeeded();
});
event.AddToComposite(&leaf_events);
}
// Call the unrestricted update function again, again verifying that an
// exception is thrown.
DRAKE_EXPECT_THROWS_MESSAGE(
system_.CalcUnrestrictedUpdate(
*context, leaf_events.get_unrestricted_update_events(), x.get()),
".*dimensions cannot be changed.*");
// Restore the discrete state (size).
x->set_discrete_state(std::make_unique<DiscreteValues<double>>(
std::make_unique<BasicVector<double>>(1)));
// Change the event to indicate to change the abstract state dimension.
leaf_events.Clear();
{
UnrestrictedUpdateEvent<double> event(
TriggerType::kPeriodic,
[](const System<double>&, const Context<double>& c,
const Event<double>&, State<double>* s) {
s->SetFrom(*c.CloneState());
s->set_abstract_state(std::make_unique<AbstractValues>());
return EventStatus::Succeeded();
});
event.AddToComposite(&leaf_events);
}
// Call the unrestricted update function again, again verifying that an
// exception is thrown.
DRAKE_EXPECT_THROWS_MESSAGE(
system_.CalcUnrestrictedUpdate(
*context, leaf_events.get_unrestricted_update_events(), x.get()),
".*dimensions cannot be changed.*");
}
// Tests that the next update time is computed correctly for LeafSystems
// templated on AutoDiffXd. Protects against regression on #4431.
GTEST_TEST(AutodiffLeafSystemTest, NextUpdateTimeAutodiff) {
TestSystem<AutoDiffXd> system;
std::unique_ptr<Context<AutoDiffXd>> context = system.CreateDefaultContext();
context->SetTime(21.0);
system.AddPeriodicUpdate();
auto event_info = system.AllocateCompositeEventCollection();
auto time = system.CalcNextUpdateTime(*context, event_info.get());
EXPECT_EQ(25.0, time);
}
// A LeafSystem that uses the default direct-feedthrough implementation without
// symbolic sparsity analysis. The only sparsity that is (optionally) used is
// the output port cache prerequisites. (The particular unit that employs this
// system chooses those prerequisites.)
class DefaultFeedthroughSystem : public LeafSystem<double> {
public:
DefaultFeedthroughSystem() {}
~DefaultFeedthroughSystem() override {}
InputPortIndex AddVectorInputPort(int size) {
return this->DeclareVectorInputPort(kUseDefaultName, size).get_index();
}
template <typename Name = UseDefaultName>
InputPortIndex AddAbstractInputPort(Name name = kUseDefaultName) {
return this->DeclareAbstractInputPort(name, Value<std::string>{})
.get_index();
}
OutputPortIndex AddAbstractOutputPort(
std::optional<std::set<DependencyTicket>> prerequisites_of_calc = {}) {
// Dummies.
auto alloc = []() { return AbstractValue::Make<int>(); };
auto calc = [](const ContextBase&, AbstractValue*) {};
if (prerequisites_of_calc) {
return this->DeclareAbstractOutputPort(
kUseDefaultName, alloc, calc, *prerequisites_of_calc).get_index();
} else {
// The DeclareAbstractOutputPort API's default value for the
// prerequisites_of_calc is everything (i.e., "all_sources_ticket()").
return this->DeclareAbstractOutputPort(
kUseDefaultName, alloc, calc).get_index();
}
}
// Elevate helper methods to be public.
using LeafSystem<double>::accuracy_ticket;
using LeafSystem<double>::all_input_ports_ticket;
using LeafSystem<double>::all_parameters_ticket;
using LeafSystem<double>::all_sources_ticket;
using LeafSystem<double>::all_state_ticket;
using LeafSystem<double>::configuration_ticket;
using LeafSystem<double>::input_port_ticket;
using LeafSystem<double>::kinematics_ticket;
using LeafSystem<double>::nothing_ticket;
using LeafSystem<double>::time_ticket;
};
GTEST_TEST(FeedthroughTest, DefaultWithNoInputsOrOutputs) {
DefaultFeedthroughSystem system;
EXPECT_FALSE(system.HasAnyDirectFeedthrough());
// No ports implies no pairs reported for direct feedthrough.
const std::multimap<int, int> expected;
EXPECT_EQ(system.GetDirectFeedthroughs(), expected);
}
GTEST_TEST(FeedthroughTest, DefaultWithBothInputsAndOutputs) {
DefaultFeedthroughSystem system;
system.AddAbstractInputPort();
system.AddAbstractOutputPort();
EXPECT_TRUE(system.HasAnyDirectFeedthrough());
EXPECT_TRUE(system.HasDirectFeedthrough(0));
EXPECT_TRUE(system.HasDirectFeedthrough(0, 0));
// Confirm all pairs are returned.
const std::multimap<int, int> expected{{0, 0}};
EXPECT_EQ(system.GetDirectFeedthroughs(), expected);
}
GTEST_TEST(FeedthroughTest, DefaultWithInputsOnly) {
DefaultFeedthroughSystem system;
system.AddAbstractInputPort();
EXPECT_FALSE(system.HasAnyDirectFeedthrough());
// No output ports implies no pairs reported for direct feedthrough.
const std::multimap<int, int> expected;
EXPECT_EQ(system.GetDirectFeedthroughs(), expected);
}
GTEST_TEST(FeedthroughTest, DefaultWithOutputsOnly) {
DefaultFeedthroughSystem system;
system.AddAbstractOutputPort();
EXPECT_FALSE(system.HasAnyDirectFeedthrough());
EXPECT_FALSE(system.HasDirectFeedthrough(0));
// No input ports implies no pairs reported for direct feedthrough.
const std::multimap<int, int> expected;
EXPECT_EQ(system.GetDirectFeedthroughs(), expected);
}
GTEST_TEST(FeedthroughTest, DefaultWithPrerequisites) {
DefaultFeedthroughSystem system;
const auto input_port_index0 = system.AddAbstractInputPort();
const auto input_port_index1 = system.AddAbstractInputPort();
const std::vector<DependencyTicket> feedthrough_tickets{
system.input_port_ticket(input_port_index0),
system.input_port_ticket(input_port_index1),
system.all_input_ports_ticket(),
system.all_sources_ticket(),
};
const std::vector<DependencyTicket> non_feedthrough_tickets{
system.nothing_ticket(),
system.time_ticket(),
system.accuracy_ticket(),
system.all_state_ticket(),
system.all_parameters_ticket(),
system.configuration_ticket(),
system.kinematics_ticket(),
};
for (const auto& ticket : non_feedthrough_tickets) {
const auto output_port_index = system.AddAbstractOutputPort({{ ticket }});
EXPECT_FALSE(system.HasDirectFeedthrough(output_port_index));
}
for (const auto& ticket : feedthrough_tickets) {
const auto output_port_index = system.AddAbstractOutputPort({{ ticket }});
EXPECT_TRUE(system.HasDirectFeedthrough(output_port_index));
}
}
// With multiple input and output ports, all input ports are thought to feed
// through to all output ports.
GTEST_TEST(FeedthroughTest, DefaultWithMultipleIoPorts) {
const int input_count = 3;
const int output_count = 4;
std::multimap<int, int> expected;
DefaultFeedthroughSystem system;
for (int i = 0; i < input_count; ++i) {
system.AddAbstractInputPort();
for (int o = 0; o < output_count; ++o) {
if (i == 0) system.AddAbstractOutputPort();
expected.emplace(i, o);
}
}
EXPECT_TRUE(system.HasAnyDirectFeedthrough());
for (int o = 0; o < output_count; ++o) {
EXPECT_TRUE(system.HasDirectFeedthrough(o));
for (int i = 0; i < input_count; ++i) {
EXPECT_TRUE(system.HasDirectFeedthrough(i, o));
}
}
// No sparsity matrix means all inputs feedthrough to all outputs.
auto feedthrough_pairs = system.GetDirectFeedthroughs();
EXPECT_EQ(feedthrough_pairs, expected);
}
// SymbolicSparsitySystem has the same sparsity matrix as ManualSparsitySystem,
// but the matrix can be inferred from the symbolic form.
template <typename T>
class SymbolicSparsitySystem : public LeafSystem<T> {
public:
explicit SymbolicSparsitySystem(bool use_default_prereqs = true)
: SymbolicSparsitySystem(SystemTypeTag<SymbolicSparsitySystem>{},
use_default_prereqs) {}
// Scalar-converting copy constructor.
template <typename U>
SymbolicSparsitySystem(const SymbolicSparsitySystem<U>& source)
: SymbolicSparsitySystem<T>(source.is_using_default_prereqs()) {
source.count_conversion();
}
// Note that this object was used as the source for a scalar conversion.
void count_conversion() const { ++num_conversions_; }
int num_conversions() const { return num_conversions_; }
bool is_using_default_prereqs() const { return use_default_prereqs_; }
protected:
explicit SymbolicSparsitySystem(SystemScalarConverter converter,
bool use_default_prereqs = true)
: LeafSystem<T>(std::move(converter)),
use_default_prereqs_(use_default_prereqs) {
const int kSize = 1;
this->DeclareInputPort(kUseDefaultName, kVectorValued, kSize);
this->DeclareInputPort(kUseDefaultName, kVectorValued, kSize);
if (is_using_default_prereqs()) {
// Don't specify prerequisites; we'll have to perform symbolic analysis
// to determine whether there is feedthrough.
this->DeclareVectorOutputPort(kUseDefaultName, BasicVector<T>(kSize),
&SymbolicSparsitySystem::CalcY0);
this->DeclareVectorOutputPort(kUseDefaultName, BasicVector<T>(kSize),
&SymbolicSparsitySystem::CalcY1);
} else {
// Explicitly specify the prerequisites for the code in CalcY0() and
// CalcY1() below. No need for further analysis to determine feedthrough.
this->DeclareVectorOutputPort(
kUseDefaultName, BasicVector<T>(kSize),
&SymbolicSparsitySystem::CalcY0,
{this->input_port_ticket(InputPortIndex(1))});
this->DeclareVectorOutputPort(
kUseDefaultName, BasicVector<T>(kSize),
&SymbolicSparsitySystem::CalcY1,
{this->input_port_ticket(InputPortIndex(0))});
}
}
private:
void CalcY0(const Context<T>& context,
BasicVector<T>* y0) const {
const auto& u1 = this->get_input_port(1).Eval(context);
y0->set_value(u1);
}
void CalcY1(const Context<T>& context,
BasicVector<T>* y1) const {
const auto& u0 = this->get_input_port(0).Eval(context);
y1->set_value(u0);
}
const bool use_default_prereqs_;
// Count how many times this object was used as the _source_ for the
// conversion constructor.
mutable int num_conversions_{0};
};
// The sparsity reporting should be the same no matter which scalar type the
// original system has been instantiated with.
using FeedthroughTestScalars = ::testing::Types<
double,
AutoDiffXd,
symbolic::Expression>;
template <typename T>
class FeedthroughTypedTest : public ::testing::Test {};
TYPED_TEST_SUITE(FeedthroughTypedTest, FeedthroughTestScalars);
// The sparsity of a System should be inferred from its symbolic form.
TYPED_TEST(FeedthroughTypedTest, SymbolicSparsityDefaultPrereqs) {
using T = TypeParam;
const SymbolicSparsitySystem<T> system;
// Both the output ports have direct feedthrough from some input.
EXPECT_TRUE(system.HasAnyDirectFeedthrough());
EXPECT_TRUE(system.HasDirectFeedthrough(0));
EXPECT_TRUE(system.HasDirectFeedthrough(1));
// Check the entire matrix.
EXPECT_FALSE(system.HasDirectFeedthrough(0, 0));
EXPECT_TRUE(system.HasDirectFeedthrough(0, 1));
EXPECT_TRUE(system.HasDirectFeedthrough(1, 0));
EXPECT_FALSE(system.HasDirectFeedthrough(1, 1));
// Confirm the exact set of desired pairs are returned.
std::multimap<int, int> expected;
expected.emplace(1, 0);
expected.emplace(0, 1);
EXPECT_EQ(system.GetDirectFeedthroughs(), expected);
// Since we didn't provide prerequisites for the output ports, each of the 8
// calls above should have required a scalar conversion to symbolic unless
// T was already symbolic.
int expected_conversions = 8;
if constexpr (std::is_same_v<T, symbolic::Expression>) {
expected_conversions = 0;
}
EXPECT_EQ(system.num_conversions(), expected_conversions);
}
// Repeat the above test using explicitly-specified prerequisites to avoid
// having to convert to symbolic form.
TYPED_TEST(FeedthroughTypedTest, SymbolicSparsityExplicitPrereqs) {
using T = TypeParam;
const SymbolicSparsitySystem<T> system(false); // Use explicit prereqs.
// Both the output ports have direct feedthrough from some input.
EXPECT_TRUE(system.HasAnyDirectFeedthrough());
EXPECT_TRUE(system.HasDirectFeedthrough(0));
EXPECT_TRUE(system.HasDirectFeedthrough(1));
// Check the entire matrix.
EXPECT_FALSE(system.HasDirectFeedthrough(0, 0));
EXPECT_TRUE(system.HasDirectFeedthrough(0, 1));
EXPECT_TRUE(system.HasDirectFeedthrough(1, 0));
EXPECT_FALSE(system.HasDirectFeedthrough(1, 1));
// Confirm the exact set of desired pairs are returned.
std::multimap<int, int> expected;
expected.emplace(1, 0);
expected.emplace(0, 1);
EXPECT_EQ(system.GetDirectFeedthroughs(), expected);
// Shouldn't have been any conversions required above.
const int expected_conversions = 0;
EXPECT_EQ(system.num_conversions(), expected_conversions);
}
// This system only supports T = symbolic::Expression; it does not support
// scalar conversion.
class NoScalarConversionSymbolicSparsitySystem
: public SymbolicSparsitySystem<symbolic::Expression> {
public:
NoScalarConversionSymbolicSparsitySystem()
: SymbolicSparsitySystem<symbolic::Expression>(
SystemScalarConverter{}) {}
};
// The sparsity of a System should be inferred from its symbolic form, even
// when the system does not support scalar conversion.
GTEST_TEST(FeedthroughTest, SymbolicSparsityWithoutScalarConversion) {
const NoScalarConversionSymbolicSparsitySystem system;
// Confirm the exact set of desired pairs are returned.
std::multimap<int, int> expected;
expected.emplace(1, 0);
expected.emplace(0, 1);
EXPECT_EQ(system.GetDirectFeedthroughs(), expected);
}
// Sanity check ToScalarTypeMaybe, to show which type conversions
// should or should not succeed.
GTEST_TEST(LeafSystemScalarConverterTest, TemplateSupportedConversions) {
SymbolicSparsitySystem<double> dut;
EXPECT_EQ(dut.ToScalarTypeMaybe<double>(), nullptr);
EXPECT_NE(dut.ToScalarTypeMaybe<AutoDiffXd>(), nullptr);
EXPECT_NE(dut.ToScalarTypeMaybe<symbolic::Expression>(), nullptr);
auto autodiff = dut.ToScalarTypeMaybe<AutoDiffXd>();
ASSERT_NE(autodiff, nullptr);
EXPECT_NE(autodiff->ToScalarTypeMaybe<double>(), nullptr);
EXPECT_EQ(autodiff->ToScalarTypeMaybe<AutoDiffXd>(), nullptr);
EXPECT_NE(autodiff->ToScalarTypeMaybe<symbolic::Expression>(), nullptr);
auto symbolic = dut.ToScalarTypeMaybe<symbolic::Expression>();
ASSERT_NE(symbolic, nullptr);
EXPECT_NE(symbolic->ToScalarTypeMaybe<double>(), nullptr);
EXPECT_NE(symbolic->ToScalarTypeMaybe<AutoDiffXd>(), nullptr);
EXPECT_EQ(symbolic->ToScalarTypeMaybe<symbolic::Expression>(), nullptr);
}
// Sanity check the default implementation of ToAutoDiffXd, for cases that
// should succeed.
GTEST_TEST(LeafSystemScalarConverterTest, AutoDiffYes) {
SymbolicSparsitySystem<double> dut;
dut.set_name("special_name");
// Static method automatically downcasts.
std::unique_ptr<SymbolicSparsitySystem<AutoDiffXd>> clone =
System<double>::ToAutoDiffXd(dut);
ASSERT_NE(clone, nullptr);
EXPECT_EQ(clone->get_name(), "special_name");
clone = System<double>::ToScalarType<AutoDiffXd>(dut);
ASSERT_NE(clone, nullptr);
EXPECT_EQ(clone->get_name(), "special_name");
// Instance method that reports failures via exception.
EXPECT_NE(dut.ToAutoDiffXd(), nullptr);
EXPECT_NE(dut.ToScalarType<AutoDiffXd>(), nullptr);
// Instance method that reports failures via nullptr.
auto maybe = dut.ToAutoDiffXdMaybe();
ASSERT_NE(maybe, nullptr);
EXPECT_EQ(maybe->get_name(), "special_name");
maybe = dut.ToScalarTypeMaybe<AutoDiffXd>();
ASSERT_NE(maybe, nullptr);
EXPECT_EQ(maybe->get_name(), "special_name");
// Spot check the specific converter object.
EXPECT_TRUE((
dut.get_system_scalar_converter().IsConvertible<AutoDiffXd, double>()));
EXPECT_FALSE((
dut.get_system_scalar_converter().IsConvertible<double, double>()));
}
// Sanity check the default implementation of ToAutoDiffXd, for cases that
// should fail.
GTEST_TEST(LeafSystemScalarConverterTest, AutoDiffNo) {
TestSystem<double> dut;
// Static method.
EXPECT_THROW(System<double>::ToAutoDiffXd(dut), std::exception);
EXPECT_THROW(System<double>::ToScalarType<AutoDiffXd>(dut), std::exception);
// Instance method that reports failures via exception.
EXPECT_THROW(dut.ToAutoDiffXd(), std::exception);
EXPECT_THROW(dut.ToScalarType<AutoDiffXd>(), std::exception);
// Instance method that reports failures via nullptr.
EXPECT_EQ(dut.ToAutoDiffXdMaybe(), nullptr);
EXPECT_EQ(dut.ToScalarTypeMaybe<AutoDiffXd>(), nullptr);
}
// Sanity check the default implementation of ToSymbolic, for cases that
// should succeed.
GTEST_TEST(LeafSystemScalarConverterTest, SymbolicYes) {
SymbolicSparsitySystem<double> dut;
dut.set_name("special_name");
// Static method automatically downcasts.
std::unique_ptr<SymbolicSparsitySystem<symbolic::Expression>> clone =
System<double>::ToSymbolic(dut);
ASSERT_NE(clone, nullptr);
EXPECT_EQ(clone->get_name(), "special_name");
clone = System<double>::ToScalarType<symbolic::Expression>(dut);
ASSERT_NE(clone, nullptr);
EXPECT_EQ(clone->get_name(), "special_name");
// Instance method that reports failures via exception.
EXPECT_NE(dut.ToSymbolic(), nullptr);
EXPECT_NE(dut.ToScalarType<symbolic::Expression>(), nullptr);
// Instance method that reports failures via nullptr.
auto maybe = dut.ToSymbolicMaybe();
ASSERT_NE(maybe, nullptr);
EXPECT_EQ(maybe->get_name(), "special_name");
maybe = dut.ToScalarTypeMaybe<symbolic::Expression>();
ASSERT_NE(maybe, nullptr);
EXPECT_EQ(maybe->get_name(), "special_name");
}
// Sanity check the default implementation of ToSymbolic, for cases that
// should fail.
GTEST_TEST(LeafSystemScalarConverterTest, SymbolicNo) {
TestSystem<double> dut;
// Static method.
EXPECT_THROW(System<double>::ToSymbolic(dut), std::exception);
EXPECT_THROW(System<double>::ToScalarType<symbolic::Expression>(dut),
std::exception);
// Instance method that reports failures via exception.
EXPECT_THROW(dut.ToSymbolic(), std::exception);
EXPECT_THROW(dut.ToScalarType<symbolic::Expression>(), std::exception);
// Instance method that reports failures via nullptr.
EXPECT_EQ(dut.ToSymbolicMaybe(), nullptr);
EXPECT_EQ(dut.ToScalarTypeMaybe<symbolic::Expression>(), nullptr);
}
// Check all scenarios of Clone() passing. The SymbolicSparsitySystem supports
// all scalar type conversions, so Clone() should always succeed.
GTEST_TEST(LeafSystemCloneTest, Supported) {
auto dut_double = std::make_unique<SymbolicSparsitySystem<double>>();
dut_double->set_name("dut_double");
auto context_double = dut_double->CreateDefaultContext();
auto copy_double = dut_double->Clone();
ASSERT_NE(copy_double, nullptr);
EXPECT_EQ(copy_double->get_name(), "dut_double");
DRAKE_EXPECT_THROWS_MESSAGE(copy_double->ValidateContext(*context_double),
"[^]*Context-System mismatch[^]*");
auto dut_autodiff = std::make_unique<SymbolicSparsitySystem<AutoDiffXd>>();
dut_autodiff->set_name("dut_autodiff");
auto context_autodiff = dut_autodiff->CreateDefaultContext();
auto copy_autodiff = dut_autodiff->Clone();
ASSERT_NE(copy_autodiff, nullptr);
EXPECT_EQ(copy_autodiff->get_name(), "dut_autodiff");
DRAKE_EXPECT_THROWS_MESSAGE(copy_autodiff->ValidateContext(*context_autodiff),
"[^]*Context-System mismatch[^]*");
auto dut_symbolic =
std::make_unique<SymbolicSparsitySystem<symbolic::Expression>>();
dut_symbolic->set_name("dut_symbolic");
auto context_symbolic = dut_symbolic->CreateDefaultContext();
auto copy_symbolic = dut_symbolic->Clone();
ASSERT_NE(copy_symbolic, nullptr);
EXPECT_EQ(copy_symbolic->get_name(), "dut_symbolic");
DRAKE_EXPECT_THROWS_MESSAGE(copy_symbolic->ValidateContext(*context_symbolic),
"[^]*Context-System mismatch[^]*");
}
// Check that the static Clone(foo) preserves the subtype.
GTEST_TEST(LeafSystemCloneTest, SupportedStatic) {
SymbolicSparsitySystem<double> dut;
std::unique_ptr<SymbolicSparsitySystem<double>> copy =
System<double>::Clone(dut);
ASSERT_NE(copy, nullptr);
}
// This system can only convert from a scalar type of double.
template <typename T>
class FromDoubleSystem final : public LeafSystem<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(FromDoubleSystem);
// Default constructor declares support for scalar conversion.
FromDoubleSystem() : LeafSystem<T>(SystemTypeTag<FromDoubleSystem>{}) {}
// Scalar-conversion constructor (with a dummy arg to avoid ambiguity).
explicit FromDoubleSystem(const FromDoubleSystem<double>& other,
int dummy = 0)
: FromDoubleSystem() {}
};
} // namespace
namespace scalar_conversion {
template <> struct Traits<FromDoubleSystem> : public FromDoubleTraits {};
} // namespace scalar_conversion
namespace {
// Check the message from a Clone() failing. These particular tests excercise
// the current set of conditions that prevent cloning. If we enhance Clone()
// to be more capable they might start passing, in which case we should update
// the test to cover whatever remaining circumstances don't support cloning.
GTEST_TEST(LeafSystemCloneTest, Unsupported) {
// The TestSystem does not support scalar conversion, so it cannot be cloned.
DRAKE_EXPECT_THROWS_MESSAGE(TestSystem<double>{}.Clone(),
".*does not support Clon.*");
// Systems that allow double -> autodiff but not vice versa cannot be cloned.
DRAKE_EXPECT_THROWS_MESSAGE(FromDoubleSystem<double>{}.Clone(),
".*does not support Clon.*");
}
GTEST_TEST(GraphvizTest, Attributes) {
DefaultFeedthroughSystem system;
system.set_name("<hello&world>");
const std::string dot = system.GetGraphvizString();
// Check that left-to-right ranking is imposed.
EXPECT_THAT(dot, ::testing::HasSubstr("rankdir=LR"));
// Check that NiceTypeName provides a bold class header.
EXPECT_THAT(dot, ::testing::HasSubstr("<B>DefaultFeedthroughSystem</B>"));
// Check that HTML special characters the name were replaced.
EXPECT_THAT(dot, ::testing::HasSubstr("name=<hello&world>"));
}
GTEST_TEST(GraphvizTest, Ports) {
DefaultFeedthroughSystem system;
system.AddVectorInputPort(/* size = */ 0);
system.AddAbstractInputPort(/*name = */ "<force&torque>");
system.AddAbstractOutputPort();
const std::string dot = system.GetGraphvizString();
EXPECT_THAT(dot, ::testing::HasSubstr("PORT=\"u0\""));
EXPECT_THAT(dot, ::testing::HasSubstr("PORT=\"u1\""));
EXPECT_THAT(dot, ::testing::HasSubstr("PORT=\"y0\""));
// Check that HTML special characters port names were replaced.
EXPECT_THAT(dot, ::testing::HasSubstr("<force&torque>"));
}
GTEST_TEST(GraphvizTest, Split) {
DefaultFeedthroughSystem system;
system.AddAbstractInputPort();
system.AddAbstractOutputPort();
// By default, the graph does not use "split" mode.
std::string dot = system.GetGraphvizString();
EXPECT_THAT(dot, ::testing::Not(::testing::HasSubstr("(split)")));
// When requested, it does use "split" mode;
std::map<std::string, std::string> options;
options.emplace("split", "I/O");
dot = system.GetGraphvizString({}, options);
EXPECT_THAT(dot, ::testing::HasSubstr("(split)"));
}
// The custom context type for the CustomContextSystem.
template <typename T>
class CustomContext : public LeafContext<T> {};
// CustomContextSystem has a LeafContext-derived custom context type. This
// confirms that the appropriate context type is generated..
template <typename T>
class CustomContextSystem : public LeafSystem<T> {
protected:
std::unique_ptr<LeafContext<T>> DoMakeLeafContext() const override {
return std::make_unique<CustomContext<T>>();
}
};
GTEST_TEST(CustomContextTest, AllocatedContext) {
CustomContextSystem<double> system;
auto allocated = system.AllocateContext();
ASSERT_TRUE(is_dynamic_castable<CustomContext<double>>(allocated.get()));
auto defaulted = system.CreateDefaultContext();
ASSERT_TRUE(is_dynamic_castable<CustomContext<double>>(defaulted.get()));
}
// Specializes BasicVector to add inequality constraints.
template <typename T, int bias>
class ConstraintBasicVector final : public BasicVector<T> {
public:
static constexpr int kSize = 3;
ConstraintBasicVector() : BasicVector<T>(VectorX<T>::Zero(kSize)) {}
BasicVector<T>* DoClone() const override { return new ConstraintBasicVector; }
void GetElementBounds(VectorXd* lower,
VectorXd* upper) const override {
const double kInf = std::numeric_limits<double>::infinity();
*lower = Vector3d(bias, -kInf, -kInf);
*upper = Vector3d::Constant(kInf);
}
};
class ConstraintTestSystem : public LeafSystem<double> {
public:
ConstraintTestSystem() { DeclareContinuousState(2); }
// Expose some protected methods for testing.
using LeafSystem<double>::DeclareContinuousState;
using LeafSystem<double>::DeclareDiscreteState;
using LeafSystem<double>::DeclareEqualityConstraint;
using LeafSystem<double>::DeclareInequalityConstraint;
using LeafSystem<double>::DeclareNumericParameter;
using LeafSystem<double>::DeclareVectorInputPort;
using LeafSystem<double>::DeclareVectorOutputPort;
void CalcState0Constraint(const Context<double>& context,
VectorXd* value) const {
*value = Vector1d(context.get_continuous_state_vector()[0]);
}
void CalcStateConstraint(const Context<double>& context,
VectorXd* value) const {
*value = context.get_continuous_state_vector().CopyToVector();
}
void CalcOutput(
const Context<double>& context,
ConstraintBasicVector<double, 44>* output) const {
output->SetFromVector(VectorXd::Constant(output->size(), 4.0));
}
private:
void DoCalcTimeDerivatives(
const Context<double>& context,
ContinuousState<double>* derivatives) const override {
// xdot = -x.
derivatives->SetFromVector(-dynamic_cast<const BasicVector<double>&>(
context.get_continuous_state_vector())
.get_value());
}
};
// Tests adding constraints implemented as methods inside the System class.
GTEST_TEST(SystemConstraintTest, ClassMethodTest) {
ConstraintTestSystem dut;
EXPECT_EQ(dut.num_constraints(), 0);
EXPECT_EQ(dut.DeclareEqualityConstraint(
&ConstraintTestSystem::CalcState0Constraint, 1, "x0"),
0);
EXPECT_EQ(dut.num_constraints(), 1);
EXPECT_EQ(
dut.DeclareInequalityConstraint(
&ConstraintTestSystem::CalcStateConstraint,
{ Vector2d::Zero(), std::nullopt },
"x"),
1);
EXPECT_EQ(dut.num_constraints(), 2);
auto context = dut.CreateDefaultContext();
context->get_mutable_continuous_state_vector().SetFromVector(
Vector2d(5.0, 7.0));
EXPECT_EQ(dut.get_constraint(SystemConstraintIndex(0)).size(), 1);
EXPECT_EQ(dut.get_constraint(SystemConstraintIndex(1)).size(), 2);
VectorXd value;
dut.get_constraint(SystemConstraintIndex(0)).Calc(*context, &value);
EXPECT_EQ(value.rows(), 1);
EXPECT_EQ(value[0], 5.0);
dut.get_constraint(SystemConstraintIndex(1)).Calc(*context, &value);
EXPECT_EQ(value.rows(), 2);
EXPECT_EQ(value[0], 5.0);
EXPECT_EQ(value[1], 7.0);
EXPECT_TRUE(
dut.get_constraint(SystemConstraintIndex(0)).is_equality_constraint());
EXPECT_EQ(dut.get_constraint(SystemConstraintIndex(0)).description(), "x0");
EXPECT_FALSE(
dut.get_constraint(SystemConstraintIndex(1)).is_equality_constraint());
EXPECT_EQ(dut.get_constraint(SystemConstraintIndex(1)).description(), "x");
}
// Tests adding constraints implemented as function handles (lambda functions).
GTEST_TEST(SystemConstraintTest, FunctionHandleTest) {
ConstraintTestSystem dut;
EXPECT_EQ(dut.num_constraints(), 0);
ContextConstraintCalc<double> calc0 = [](
const Context<double>& context, VectorXd* value) {
*value = Vector1d(context.get_continuous_state_vector()[1]);
};
EXPECT_EQ(dut.DeclareInequalityConstraint(calc0,
{ Vector1d::Zero(), std::nullopt },
"x1_lower"),
0);
EXPECT_EQ(dut.num_constraints(), 1);
ContextConstraintCalc<double> calc1 = [](
const Context<double>& context, VectorXd* value) {
*value =
Vector2d(context.get_continuous_state_vector()[1],
context.get_continuous_state_vector()[0]);
};
EXPECT_EQ(dut.DeclareInequalityConstraint(calc1,
{ std::nullopt, Vector2d(2, 3) }, "x_upper"), 1);
auto context = dut.CreateDefaultContext();
context->get_mutable_continuous_state_vector().SetFromVector(
Vector2d(5.0, 7.0));
VectorXd value;
const SystemConstraint<double>& inequality_constraint0 =
dut.get_constraint(SystemConstraintIndex(0));
inequality_constraint0.Calc(*context, &value);
EXPECT_EQ(value.rows(), 1);
EXPECT_EQ(value[0], 7.0);
EXPECT_FALSE(inequality_constraint0.is_equality_constraint());
EXPECT_EQ(inequality_constraint0.description(), "x1_lower");
const SystemConstraint<double>& inequality_constraint1 =
dut.get_constraint(SystemConstraintIndex(1));
inequality_constraint1.Calc(*context, &value);
EXPECT_EQ(value.rows(), 2);
EXPECT_EQ(value[0], 7.0);
EXPECT_EQ(value[1], 5.0);
EXPECT_FALSE(inequality_constraint1.is_equality_constraint());
EXPECT_EQ(inequality_constraint1.description(), "x_upper");
EXPECT_EQ(dut.DeclareEqualityConstraint(calc0, 1, "x1eq"), 2);
EXPECT_EQ(dut.num_constraints(), 3);
const SystemConstraint<double>& equality_constraint =
dut.get_constraint(SystemConstraintIndex(2));
equality_constraint.Calc(*context, &value);
EXPECT_EQ(value.rows(), 1);
EXPECT_EQ(value[0], 7.0);
EXPECT_TRUE(equality_constraint.is_equality_constraint());
EXPECT_EQ(equality_constraint.description(), "x1eq");
}
// Tests constraints implied by BasicVector subtypes.
GTEST_TEST(SystemConstraintTest, ModelVectorTest) {
ConstraintTestSystem dut;
EXPECT_EQ(dut.num_constraints(), 0);
// Declaring a constrained model vector parameter should add constraints.
// We want `vec[0] >= 11` on the parameter vector.
using ParameterVector = ConstraintBasicVector<double, 11>;
dut.DeclareNumericParameter(ParameterVector{});
ASSERT_EQ(dut.num_constraints(), 1);
using Index = SystemConstraintIndex;
const SystemConstraint<double>& constraint0 = dut.get_constraint(Index{0});
const double kInf = std::numeric_limits<double>::infinity();
EXPECT_TRUE(CompareMatrices(constraint0.lower_bound(), Vector1d(11)));
EXPECT_TRUE(CompareMatrices(constraint0.upper_bound(), Vector1d(kInf)));
EXPECT_FALSE(constraint0.is_equality_constraint());
EXPECT_THAT(constraint0.description(), ::testing::ContainsRegex(
"^parameter 0 of type .*ConstraintBasicVector<double,11>$"));
// Declaring constrained model continuous state should add constraints.
// We want `vec[0] >= 22` on the state vector.
using StateVector = ConstraintBasicVector<double, 22>;
dut.DeclareContinuousState(StateVector{}, 0, 0, StateVector::kSize);
EXPECT_EQ(dut.num_constraints(), 2);
const SystemConstraint<double>& constraint1 = dut.get_constraint(Index{1});
EXPECT_TRUE(CompareMatrices(constraint1.lower_bound(), Vector1d(22)));
EXPECT_TRUE(CompareMatrices(constraint1.upper_bound(), Vector1d(kInf)));
EXPECT_FALSE(constraint1.is_equality_constraint());
EXPECT_THAT(constraint1.description(), ::testing::ContainsRegex(
"^continuous state of type .*ConstraintBasicVector<double,22>$"));
// Declaring a constrained model vector input should add constraints.
// We want `vec[0] >= 33` on the input vector.
using InputVector = ConstraintBasicVector<double, 33>;
dut.DeclareVectorInputPort(kUseDefaultName, InputVector{});
EXPECT_EQ(dut.num_constraints(), 3);
const SystemConstraint<double>& constraint2 = dut.get_constraint(Index{2});
EXPECT_TRUE(CompareMatrices(constraint2.lower_bound(), Vector1d(33)));
EXPECT_TRUE(CompareMatrices(constraint2.upper_bound(), Vector1d(kInf)));
EXPECT_FALSE(constraint2.is_equality_constraint());
EXPECT_THAT(constraint2.description(), ::testing::ContainsRegex(
"^input 0 of type .*ConstraintBasicVector<double,33>$"));
// Declaring a constrained model vector output should add constraints.
// We want `vec[0] >= 44` on the output vector.
dut.DeclareVectorOutputPort(
kUseDefaultName, &ConstraintTestSystem::CalcOutput);
EXPECT_EQ(dut.num_constraints(), 4);
const SystemConstraint<double>& constraint3 = dut.get_constraint(Index{3});
EXPECT_TRUE(CompareMatrices(constraint3.lower_bound(), Vector1d(44)));
EXPECT_TRUE(CompareMatrices(constraint3.upper_bound(), Vector1d(kInf)));
EXPECT_FALSE(constraint3.is_equality_constraint());
EXPECT_THAT(constraint3.description(), ::testing::ContainsRegex(
"^output 0 of type .*ConstraintBasicVector<double,44>$"));
// Declaring constrained model discrete state should add constraints.
// We want `vec[0] >= 55` on the state vector.
using DiscreteStateVector = ConstraintBasicVector<double, 55>;
dut.DeclareDiscreteState(DiscreteStateVector{});
EXPECT_EQ(dut.num_constraints(), 5);
const SystemConstraint<double>& constraint4 = dut.get_constraint(Index{4});
EXPECT_TRUE(CompareMatrices(constraint4.lower_bound(), Vector1d(55)));
EXPECT_TRUE(CompareMatrices(constraint4.upper_bound(), Vector1d(kInf)));
EXPECT_FALSE(constraint4.is_equality_constraint());
EXPECT_THAT(constraint4.description(), ::testing::ContainsRegex(
"^discrete state of type .*ConstraintBasicVector<double,55>$"));
// We'll work through the Calc results all at the end, so that we don't
// change the shape of the System and Context while we're Calc'ing.
auto context = dut.CreateDefaultContext();
// `param0[0] >= 11.0` with `param0[0] == 1.0` produces `1.0 >= 11.0`.
context->get_mutable_numeric_parameter(0)[0] = 1.0;
VectorXd value0;
constraint0.Calc(*context, &value0);
EXPECT_TRUE(CompareMatrices(value0, Vector1<double>::Constant(1.0)));
// `xc[0] >= 22.0` with `xc[0] == 2.0` produces `2.0 >= 22.0`.
context->get_mutable_continuous_state_vector()[0] = 2.0;
VectorXd value1;
constraint1.Calc(*context, &value1);
EXPECT_TRUE(CompareMatrices(value1, Vector1<double>::Constant(2.0)));
// `u0[0] >= 33.0` with `u0[0] == 3.0` produces `3.0 >= 33.0`.
InputVector input;
input[0] = 3.0;
dut.get_input_port(0).FixValue(&*context, input);
VectorXd value2;
constraint2.Calc(*context, &value2);
EXPECT_TRUE(CompareMatrices(value2, Vector1<double>::Constant(3.0)));
// `y0[0] >= 44.0` with `y0[0] == 4.0` produces `4.0 >= 44.0`.
VectorXd value3;
constraint3.Calc(*context, &value3);
EXPECT_TRUE(CompareMatrices(value3, Vector1<double>::Constant(4.0)));
}
// Note: this class is duplicated in diagram_test.
class RandomContextTestSystem : public LeafSystem<double> {
public:
RandomContextTestSystem() {
this->DeclareContinuousState(
BasicVector<double>(Vector2d(-1.0, -2.0)));
this->DeclareNumericParameter(
BasicVector<double>(Vector3d(1.0, 2.0, 3.0)));
}
void SetRandomState(const Context<double>& context, State<double>* state,
RandomGenerator* generator) const override {
std::normal_distribution<double> normal;
for (int i = 0; i < context.get_continuous_state_vector().size(); i++) {
state->get_mutable_continuous_state().get_mutable_vector().SetAtIndex(
i, normal(*generator));
}
}
void SetRandomParameters(const Context<double>& context,
Parameters<double>* params,
RandomGenerator* generator) const override {
std::uniform_real_distribution<double> uniform;
for (int i = 0; i < context.get_numeric_parameter(0).size(); i++) {
params->get_mutable_numeric_parameter(0).SetAtIndex(
i, uniform(*generator));
}
}
};
GTEST_TEST(RandomContextTest, SetRandomTest) {
RandomContextTestSystem system;
auto context = system.CreateDefaultContext();
// Back-up the numeric context values.
Vector2d state = context->get_continuous_state_vector().CopyToVector();
Vector3d params = context->get_numeric_parameter(0).CopyToVector();
// Should return the (same) original values.
system.SetDefaultContext(context.get());
EXPECT_TRUE((state.array() ==
context->get_continuous_state_vector().CopyToVector().array())
.all());
EXPECT_TRUE(
(params.array() == context->get_numeric_parameter(0).get_value().array())
.all());
RandomGenerator generator;
// Should return different values.
system.SetRandomContext(context.get(), &generator);
EXPECT_TRUE((state.array() !=
context->get_continuous_state_vector().CopyToVector().array())
.all());
EXPECT_TRUE(
(params.array() != context->get_numeric_parameter(0).get_value().array())
.all());
// Update backup.
state = context->get_continuous_state_vector().CopyToVector();
params = context->get_numeric_parameter(0).CopyToVector();
// Should return different values (again).
system.SetRandomContext(context.get(), &generator);
EXPECT_TRUE((state.array() !=
context->get_continuous_state_vector().CopyToVector().array())
.all());
EXPECT_TRUE(
(params.array() != context->get_numeric_parameter(0).get_value().array())
.all());
}
// Tests initialization works properly for a leaf system. This flavor checks
// the event functions individually.
GTEST_TEST(InitializationTest, ManualEventProcessing) {
InitializationTestSystem dut;
auto context = dut.CreateDefaultContext();
auto discrete_updates = dut.AllocateDiscreteVariables();
auto state = context->CloneState();
auto init_events = dut.AllocateCompositeEventCollection();
EXPECT_EQ(init_events->get_system_id(), context->get_system_id());
dut.GetInitializationEvents(*context, init_events.get());
EventStatus status = dut.Publish(*context, init_events->get_publish_events());
EXPECT_TRUE(status.succeeded());
status = dut.CalcDiscreteVariableUpdate(*context,
init_events->get_discrete_update_events(),
discrete_updates.get());
EXPECT_TRUE(status.succeeded());
status = dut.CalcUnrestrictedUpdate(
*context, init_events->get_unrestricted_update_events(), state.get());
EXPECT_TRUE(status.succeeded());
EXPECT_TRUE(dut.get_pub_init());
EXPECT_TRUE(dut.get_dis_update_init());
EXPECT_TRUE(dut.get_unres_update_init());
}
// Tests initialization works properly for a leaf system. This flavor checks
// the built-in System function for initialization.
GTEST_TEST(InitializationTest, DefaultEventProcessing) {
InitializationTestSystem dut;
auto context = dut.CreateDefaultContext();
dut.ExecuteInitializationEvents(context.get());
EXPECT_TRUE(dut.get_pub_init());
EXPECT_TRUE(dut.get_dis_update_init());
EXPECT_TRUE(dut.get_unres_update_init());
EXPECT_EQ(context->get_discrete_state_vector()[0], 1.23);
EXPECT_TRUE(context->get_abstract_state<bool>(0));
}
// This class uses every one of the functions that declare events.
class EventSugarTestSystem : public LeafSystem<double> {
public:
explicit EventSugarTestSystem(EventStatus::Severity desired_status =
EventStatus::kSucceeded)
: desired_status_(desired_status) {
DeclareInitializationPublishEvent(
&EventSugarTestSystem::MyPublishHandler);
DeclareInitializationDiscreteUpdateEvent(
&EventSugarTestSystem::MyDiscreteUpdateHandler);
DeclareInitializationUnrestrictedUpdateEvent(
&EventSugarTestSystem::MyUnrestrictedUpdateHandler);
DeclarePerStepPublishEvent(
&EventSugarTestSystem::MyPublishHandler);
DeclarePerStepDiscreteUpdateEvent(
&EventSugarTestSystem::MyDiscreteUpdateHandler);
DeclarePerStepUnrestrictedUpdateEvent(
&EventSugarTestSystem::MyUnrestrictedUpdateHandler);
DeclarePeriodicPublishEvent(kPeriod, kOffset,
&EventSugarTestSystem::MyPublishHandler);
DeclarePeriodicDiscreteUpdateEvent(kPeriod, kOffset,
&EventSugarTestSystem::MyDiscreteUpdateHandler);
DeclarePeriodicUnrestrictedUpdateEvent(kPeriod, kOffset,
&EventSugarTestSystem::MyUnrestrictedUpdateHandler);
// Two forced publish callbacks (to ensure that they are additive).
DeclareForcedPublishEvent(&EventSugarTestSystem::MyPublishHandler);
DeclareForcedPublishEvent(&EventSugarTestSystem::MySecondPublishHandler);
// Two forced discrete update callbacks (to ensure that they are
// additive).
DeclareForcedDiscreteUpdateEvent(
&EventSugarTestSystem::MyDiscreteUpdateHandler);
DeclareForcedDiscreteUpdateEvent(
&EventSugarTestSystem::MySecondDiscreteUpdateHandler);
// Two forced unrestricted update callbacks (to ensure that they are
// additive).
DeclareForcedUnrestrictedUpdateEvent(
&EventSugarTestSystem::MyUnrestrictedUpdateHandler);
DeclareForcedUnrestrictedUpdateEvent(
&EventSugarTestSystem::MySecondUnrestrictedUpdateHandler);
// These variants don't require an EventStatus return.
DeclarePeriodicPublishEvent(kPeriod, kOffset,
&EventSugarTestSystem::MySuccessfulPublishHandler);
DeclarePeriodicDiscreteUpdateEvent(kPeriod, kOffset,
&EventSugarTestSystem::MySuccessfulDiscreteUpdateHandler);
DeclarePeriodicUnrestrictedUpdateEvent(kPeriod, kOffset,
&EventSugarTestSystem::MySuccessfulUnrestrictedUpdateHandler);
}
const double kPeriod = 0.125;
const double kOffset = 0.25;
int num_publish() const {return num_publish_;}
int num_second_publish_handler_publishes() const {
return num_second_publish_handler_publishes_;
}
int num_discrete_update() const {return num_discrete_update_;}
int num_second_discrete_update() const {return num_second_discrete_update_;}
int num_unrestricted_update() const {return num_unrestricted_update_;}
int num_second_unrestricted_update() const {
return num_second_unrestricted_update_;
}
private:
EventStatus MyPublishHandler(const Context<double>& context) const {
MySuccessfulPublishHandler(context);
return MakeStatus();
}
EventStatus MySecondPublishHandler(const Context<double>& context) const {
++num_second_publish_handler_publishes_;
return MakeStatus();
}
EventStatus MyDiscreteUpdateHandler(
const Context<double>& context,
DiscreteValues<double>* discrete_state) const {
MySuccessfulDiscreteUpdateHandler(context, &*discrete_state);
return MakeStatus();
}
EventStatus MySecondDiscreteUpdateHandler(
const Context<double>& context,
DiscreteValues<double>* discrete_state) const {
++num_second_discrete_update_;
return MakeStatus();
}
EventStatus MyUnrestrictedUpdateHandler(const Context<double>& context,
State<double>* state) const {
MySuccessfulUnrestrictedUpdateHandler(context, &*state);
return MakeStatus();
}
EventStatus MySecondUnrestrictedUpdateHandler(const Context<double>& context,
State<double>* state) const {
++num_second_unrestricted_update_;
return MakeStatus();
}
void MySuccessfulPublishHandler(const Context<double>&) const {
++num_publish_;
}
void MySuccessfulDiscreteUpdateHandler(const Context<double>&,
DiscreteValues<double>*) const {
++num_discrete_update_;
}
void MySuccessfulUnrestrictedUpdateHandler(const Context<double>&,
State<double>*) const {
++num_unrestricted_update_;
}
EventStatus MakeStatus() const {
switch (desired_status_) {
case EventStatus::kDidNothing:
return EventStatus::DidNothing();
case EventStatus::kSucceeded:
return EventStatus::Succeeded();
case EventStatus::kReachedTermination:
return EventStatus::ReachedTermination(this, "Terminated");
case EventStatus::kFailed:
return EventStatus::Failed(this, "Something bad happened");
}
DRAKE_UNREACHABLE();
}
const EventStatus::Severity desired_status_;
mutable int num_publish_{0};
mutable int num_second_publish_handler_publishes_{0};
mutable int num_discrete_update_{0};
mutable int num_second_discrete_update_{0};
mutable int num_unrestricted_update_{0};
mutable int num_second_unrestricted_update_{0};
};
GTEST_TEST(EventSugarTest, EventsAreRegistered) {
EventSugarTestSystem dut;
auto context = dut.CreateDefaultContext();
auto init_events = dut.AllocateCompositeEventCollection();
dut.GetInitializationEvents(*context, &*init_events);
EXPECT_TRUE(init_events->HasPublishEvents());
EXPECT_TRUE(init_events->HasDiscreteUpdateEvents());
EXPECT_TRUE(init_events->HasUnrestrictedUpdateEvents());
auto per_step_events = dut.AllocateCompositeEventCollection();
dut.GetPerStepEvents(*context, &*per_step_events);
EXPECT_TRUE(per_step_events->HasPublishEvents());
EXPECT_TRUE(per_step_events->HasDiscreteUpdateEvents());
EXPECT_TRUE(per_step_events->HasUnrestrictedUpdateEvents());
auto periodic_events = dut.AllocateCompositeEventCollection();
dut.GetPeriodicEvents(*context, &*periodic_events);
EXPECT_TRUE(periodic_events->HasPublishEvents());
EXPECT_TRUE(periodic_events->HasDiscreteUpdateEvents());
EXPECT_TRUE(periodic_events->HasUnrestrictedUpdateEvents());
auto timed_events = dut.AllocateCompositeEventCollection();
double next_event_time = dut.CalcNextUpdateTime(*context, &*timed_events);
EXPECT_EQ(next_event_time, 0.25);
EXPECT_TRUE(timed_events->HasPublishEvents());
EXPECT_TRUE(timed_events->HasDiscreteUpdateEvents());
EXPECT_TRUE(timed_events->HasUnrestrictedUpdateEvents());
}
GTEST_TEST(EventSugarTest, HandlersGetCalled) {
EventSugarTestSystem dut;
auto context = dut.CreateDefaultContext();
auto discrete_state = dut.AllocateDiscreteVariables();
auto state = context->CloneState();
auto all_events = dut.AllocateCompositeEventCollection();
dut.GetInitializationEvents(*context, &*all_events);
auto per_step_events = dut.AllocateCompositeEventCollection();
dut.GetPerStepEvents(*context, &*per_step_events);
all_events->AddToEnd(*per_step_events);
auto periodic_events = dut.AllocateCompositeEventCollection();
dut.GetPeriodicEvents(*context, &*periodic_events);
all_events->AddToEnd(*periodic_events);
EventStatus status = dut.CalcUnrestrictedUpdate(
*context, all_events->get_unrestricted_update_events(), &*state);
EXPECT_TRUE(status.succeeded());
dut.CalcForcedUnrestrictedUpdate(*context, &*state);
status = dut.CalcDiscreteVariableUpdate(
*context, all_events->get_discrete_update_events(), &*discrete_state);
EXPECT_TRUE(status.succeeded());
dut.CalcForcedDiscreteVariableUpdate(*context, &*discrete_state);
status = dut.Publish(*context, all_events->get_publish_events());
EXPECT_TRUE(status.succeeded());
dut.ForcedPublish(*context);
EXPECT_EQ(dut.num_publish(), 5);
EXPECT_EQ(dut.num_second_publish_handler_publishes(), 1);
EXPECT_EQ(dut.num_discrete_update(), 5);
EXPECT_EQ(dut.num_second_discrete_update(), 1);
EXPECT_EQ(dut.num_unrestricted_update(), 5);
EXPECT_EQ(dut.num_second_unrestricted_update(), 1);
}
// Verify that user-initiated event APIs throw on handler failure.
GTEST_TEST(EventSugarTest, ForcedEventsThrowOnFailure) {
EventSugarTestSystem dut(EventStatus::kFailed);
dut.set_name("dut");
auto context = dut.CreateDefaultContext();
DRAKE_EXPECT_THROWS_MESSAGE(
dut.ForcedPublish(*context),
"ForcedPublish.*event handler.*"
"EventSugarTestSystem.*dut.*failed.*Something bad happened.*");
auto discrete_state = dut.AllocateDiscreteVariables();
DRAKE_EXPECT_THROWS_MESSAGE(
dut.CalcForcedDiscreteVariableUpdate(*context, &*discrete_state),
"CalcForcedDiscreteVariableUpdate.*event handler.*"
"EventSugarTestSystem.*dut.*failed.*Something bad happened.*");
auto state = context->CloneState();
DRAKE_EXPECT_THROWS_MESSAGE(
dut.CalcForcedUnrestrictedUpdate(*context, &*state),
"CalcForcedUnrestrictedUpdate.*event handler.*"
"EventSugarTestSystem.*dut.*failed.*Something bad happened.*");
DRAKE_EXPECT_THROWS_MESSAGE(
dut.ExecuteInitializationEvents(&*context),
"ExecuteInitializationEvents.*event handler.*"
"EventSugarTestSystem.*dut.*failed.*Something bad happened.*");
}
// Verify that user-initiated event APIs don't throw for any status less
// than failure (including "reached termination").
GTEST_TEST(EventSugarTest, ForcedEventsDontThrowWhenNoFailure) {
EventSugarTestSystem successful(EventStatus::kSucceeded);
EventSugarTestSystem terminating(EventStatus::kReachedTermination);
auto successful_context = successful.CreateDefaultContext();
auto terminating_context = terminating.CreateDefaultContext();
EXPECT_NO_THROW(successful.ForcedPublish(*successful_context));
EXPECT_NO_THROW(terminating.ForcedPublish(*terminating_context));
auto successful_discrete_state = successful.AllocateDiscreteVariables();
auto terminating_discrete_state = terminating.AllocateDiscreteVariables();
EXPECT_NO_THROW(successful.CalcForcedDiscreteVariableUpdate(
*successful_context, &*successful_discrete_state));
EXPECT_NO_THROW(terminating.CalcForcedDiscreteVariableUpdate(
*terminating_context, &*terminating_discrete_state));
auto successful_state = successful_context->CloneState();
auto terminating_state = terminating_context->CloneState();
EXPECT_NO_THROW(successful.CalcForcedUnrestrictedUpdate(*successful_context,
&*successful_state));
EXPECT_NO_THROW(terminating.CalcForcedUnrestrictedUpdate(
*terminating_context, &*terminating_state));
EXPECT_NO_THROW(successful.ExecuteInitializationEvents(&*successful_context));
EXPECT_NO_THROW(
terminating.ExecuteInitializationEvents(&*terminating_context));
}
// A System that does not override the default implicit time derivatives
// implementation.
class DefaultExplicitSystem : public LeafSystem<double> {
public:
DefaultExplicitSystem() { DeclareContinuousState(3); }
void RedeclareResidualSize(int n) {
DeclareImplicitTimeDerivativesResidualSize(n);
}
static Vector3d fixed_derivative() { return {1., 2., 3.}; }
private:
void DoCalcTimeDerivatives(const Context<double>& context,
ContinuousState<double>* derivatives) const final {
derivatives->SetFromVector(fixed_derivative());
}
// No override for the implicit derivatives method.
};
// A System that _does_ override the default implicit time derivatives
// implementation, and also changes the residual size from its default.
class OverrideImplicitSystem : public DefaultExplicitSystem {
public:
OverrideImplicitSystem() {
DeclareImplicitTimeDerivativesResidualSize(1);
}
void RedeclareResidualSize(int n) {
DeclareImplicitTimeDerivativesResidualSize(n);
}
private:
void DoCalcImplicitTimeDerivativesResidual(
const systems::Context<double>& context,
const systems::ContinuousState<double>& proposed_derivatives,
EigenPtr<VectorX<double>> residual) const final {
EXPECT_EQ(residual->size(), 1);
(*residual)[0] = proposed_derivatives.CopyToVector().sum();
}
};
GTEST_TEST(ImplicitTimeDerivatives, DefaultImplementation) {
const Vector3d derivs = DefaultExplicitSystem::fixed_derivative();
DefaultExplicitSystem dut;
auto context = dut.CreateDefaultContext();
auto xdot = dut.AllocateTimeDerivatives();
// Check that SystemBase method returns the default size.
EXPECT_EQ(dut.implicit_time_derivatives_residual_size(), 3);
// Proposing the actual derivative should yield a zero residual.
xdot->SetFromVector(derivs);
// Make sure the vector type returned by the allocator works.
VectorXd residual = dut.AllocateImplicitTimeDerivativesResidual();
EXPECT_EQ(residual.size(), 3);
dut.CalcImplicitTimeDerivativesResidual(*context, *xdot, &residual);
EXPECT_EQ(residual, Vector3d::Zero()); // Yes, exactly.
// To make sure the method isn't just returning zero, try the reverse
// case which should have the actual derivative as a residual.
xdot->SetFromVector(Vector3d::Zero());
dut.CalcImplicitTimeDerivativesResidual(*context, *xdot, &residual);
EXPECT_EQ(residual, -derivs); // Exact.
// The residual should be acceptable as long as it is some mutable
// Eigen object of the right shape.
// A fixed-size residual should work.
Vector3d residual3;
dut.CalcImplicitTimeDerivativesResidual(*context, *xdot, &residual3);
EXPECT_EQ(residual3, -derivs);
// Some complicated Eigen mutable object should also work.
VectorXd buffer(VectorXd::Zero(5));
auto segment = buffer.segment(1, 3); // Some kind of block object.
VectorXd expected_residual(VectorXd::Zero(5));
expected_residual.segment(1, 3) = -derivs;
dut.CalcImplicitTimeDerivativesResidual(*context, *xdot, &segment);
EXPECT_EQ(buffer, expected_residual);
// Let's change the declared residual size, pass in a matching vector,
// and verify that the default implementation complains properly.
dut.RedeclareResidualSize(4);
Vector4d residual4;
DRAKE_EXPECT_THROWS_MESSAGE(
dut.CalcImplicitTimeDerivativesResidual(*context, *xdot, &residual4),
"System::DoCalcImplicitTimeDerivativesResidual.*"
"default implementation requires.*residual size.*4.*"
"matches.*state variables.*3.*must override.*");
// And if the residual matches the state size but not the declared size,
// we should get stopped by the NVI public method.
DRAKE_EXPECT_THROWS_MESSAGE(
dut.CalcImplicitTimeDerivativesResidual(*context, *xdot, &residual3),
".*CalcImplicitTimeDerivativesResidual.*"
"expected residual.*size 4 but got.*size 3.*\n"
"Use AllocateImplicitTimeDerivativesResidual.*");
}
GTEST_TEST(ImplicitTimeDerivatives, OverrideImplementation) {
OverrideImplicitSystem dut;
auto context = dut.CreateDefaultContext();
auto xdot = dut.AllocateTimeDerivatives();
EXPECT_EQ(xdot->size(), 3);
// Check that SystemBase method returns the adjusted size.
EXPECT_EQ(dut.implicit_time_derivatives_residual_size(), 1);
// Make sure the vector size returned by the allocator reflects the change.
VectorXd residual = dut.AllocateImplicitTimeDerivativesResidual();
EXPECT_EQ(residual.size(), 1);
residual[0] = 99.; // So we can make sure it gets changed.
// "Residual" just sums the proposed derivative xdot.
xdot->SetFromVector(Vector3d(10., 20., 30.));
dut.CalcImplicitTimeDerivativesResidual(*context, *xdot, &residual);
EXPECT_EQ(residual[0], 60.);
// (No need to re-test the acceptable Eigen output types as we did in
// the previous test since both go through the same public NVI method.)
// Check that a wrong-sized residual gets a nice message.
Vector3d bad_residual;
DRAKE_EXPECT_THROWS_MESSAGE(
dut.CalcImplicitTimeDerivativesResidual(*context, *xdot, &bad_residual),
".*CalcImplicitTimeDerivativesResidual.*"
"expected residual.*size 1 but got.*size 3.*\n"
"Use AllocateImplicitTimeDerivativesResidual.*");
}
// Check that declaring an illegal residual size just resets size back to the
// default (that is, the same size as the time derivatives).
GTEST_TEST(ImplicitTimeDerivatives, ResetToDefaultResidualSize) {
OverrideImplicitSystem dut;
EXPECT_EQ(dut.implicit_time_derivatives_residual_size(), 1);
dut.RedeclareResidualSize(0);
EXPECT_EQ(dut.implicit_time_derivatives_residual_size(), 3);
dut.RedeclareResidualSize(1); // Non-default.
EXPECT_EQ(dut.implicit_time_derivatives_residual_size(), 1);
dut.RedeclareResidualSize(-29);
EXPECT_EQ(dut.implicit_time_derivatives_residual_size(), 3);
}
// Simulator::AdvanceTo() could miss an event that was triggered by a
// DoCalcNextUpdateTime() override that returned a finite next-trigger time but
// no Event object to handle the event. See issues #12620 and #14644.
//
// PR #14663 redefined this as an error -- an Event must be returned if there
// is a finite trigger time. That PR also replaced an assert with a real error
// message in the case the time is returned NaN; we check that here also.
//
// Note that this is really just a System test, but we need a LeafSystem
// to satisfy all the uninteresting pure virtuals.
GTEST_TEST(SystemTest, MissedEventIssue12620) {
class TriggerTimeButNoEventSystem : public LeafSystem<double> {
public:
explicit TriggerTimeButNoEventSystem(double trigger_time)
: trigger_time_(trigger_time) {
this->set_name("MyTriggerSystem");
}
private:
void DoCalcNextUpdateTime(const Context<double>& context,
CompositeEventCollection<double>*,
double* next_update_time) const final {
*next_update_time = trigger_time_;
// Don't push anything to the EventCollection.
}
const double trigger_time_;
};
// First test returns NaN, which should be detected.
TriggerTimeButNoEventSystem nan_system(NAN);
auto nan_context = nan_system.AllocateContext();
auto events = nan_system.AllocateCompositeEventCollection();
nan_context->SetTime(0.25);
DRAKE_EXPECT_THROWS_MESSAGE(
nan_system.CalcNextUpdateTime(*nan_context, events.get()),
".*CalcNextUpdateTime.*TriggerTimeButNoEventSystem.*MyTriggerSystem.*"
"time=0.25.*no update time.*NaN.*Return infinity.*");
// Second test returns a trigger time but no Event object.
TriggerTimeButNoEventSystem trigger_system(0.375);
auto trigger_context = trigger_system.AllocateContext();
events = trigger_system.AllocateCompositeEventCollection();
trigger_context->SetTime(0.25);
DRAKE_EXPECT_THROWS_MESSAGE(
trigger_system.CalcNextUpdateTime(*trigger_context, events.get()),
".*CalcNextUpdateTime.*TriggerTimeButNoEventSystem.*MyTriggerSystem.*"
"time=0.25.*update time 0.375.*empty Event collection.*"
"at least one Event object must be provided.*");
}
// Check that a DoCalcNextUpdateTime() override that fails to set the update
// time at all gets an error message. (This is detected as a returned time of
// NaN because calling code initializes the time that way.)
GTEST_TEST(SystemTest, ForgotToSetTheUpdateTime) {
class ForgotToSetTimeSystem : public LeafSystem<double> {
public:
ForgotToSetTimeSystem() { this->set_name("MyForgetfulSystem"); }
private:
void DoCalcNextUpdateTime(const Context<double>& context,
CompositeEventCollection<double>*,
double* next_update_time) const final {
// Oops -- forgot to set the time.
}
};
ForgotToSetTimeSystem forgot_system;
auto forgot_context = forgot_system.AllocateContext();
auto events = forgot_system.AllocateCompositeEventCollection();
forgot_context->SetTime(0.25);
DRAKE_EXPECT_THROWS_MESSAGE(
forgot_system.CalcNextUpdateTime(*forgot_context, events.get()),
".*CalcNextUpdateTime.*ForgotToSetTimeSystem.*MyForgetfulSystem.*"
"time=0.25.*no update time.*NaN.*Return infinity.*");
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/thread_sanitizer_test.cc | #include <future>
#include <memory>
#include "gtest/gtest.h"
#include "drake/common/drake_assert.h"
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/systems/framework/context.h"
#include "drake/systems/framework/vector_system.h"
// The purpose of this test is to provide TSan (ThreadSanitizer) some material
// to study. The test cases exercise legitimate ways to use Drake with multiple
// threads and should pass TSan cleanly. One of these tests was shown
// to fail prior to removing the shared mutable static in PR #15564.
namespace drake {
namespace systems {
namespace {
// Simple system to use in thread-safety testing.
class TestVectorSystem : public VectorSystem<double> {
public:
TestVectorSystem() : VectorSystem(0, 1) {
// Discrete state is initialized to zero.
this->DeclareDiscreteState(1);
}
private:
void DoCalcVectorOutput(
const Context<double>& context,
const Eigen::VectorBlock<const VectorX<double>>& input,
const Eigen::VectorBlock<const VectorX<double>>& state,
Eigen::VectorBlock<VectorX<double>>* output) const override {
*output = state;
}
};
// Test that exercises read and write use of per-thread contexts.
// Failed prior to PR #15564.
GTEST_TEST(ThreadSanitizerTest, PerThreadContextTest) {
// Make test system.
auto system = std::make_unique<TestVectorSystem>();
// Make two contexts.
auto context_A = system->CreateDefaultContext();
auto context_B = system->CreateDefaultContext();
// Define read & write operation on a context.
const auto context_rw_operation = [](Context<double>* system_context) {
Eigen::VectorXd state_vector =
system_context->get_discrete_state_vector().get_value();
// Ensure that we are actually making a change here so the write can't
// be elided.
DRAKE_DEMAND(state_vector[0] == 0.0);
state_vector[0] = 1.0;
system_context->SetDiscreteState(state_vector);
};
// Dispatch parallel read & write operations on separate contexts.
std::future<void> context_A_rw_operation = std::async(
std::launch::async, context_rw_operation, context_A.get());
std::future<void> context_B_rw_operation = std::async(
std::launch::async, context_rw_operation, context_B.get());
// Wait for operations to complete, and ensure they don't throw.
DRAKE_EXPECT_NO_THROW(context_A_rw_operation.get());
DRAKE_EXPECT_NO_THROW(context_B_rw_operation.get());
}
// Test that exercises read-only use of a shared context between threads.
GTEST_TEST(ThreadSanitizerTest, SharedFrozenContextTest) {
// Make test system.
auto system = std::make_unique<TestVectorSystem>();
// Make a context.
auto context = system->CreateDefaultContext();
// Define a read-only operation on a context.
const auto context_ro_operation = [](Context<double>* system_context) {
const Eigen::VectorXd state_vector =
system_context->get_discrete_state_vector().get_value();
return state_vector;
};
// Freeze context.
context->FreezeCache();
// Dispatch parallel read operations on the same context.
std::future<Eigen::VectorXd> context_ro_operation_1 = std::async(
std::launch::async, context_ro_operation, context.get());
std::future<Eigen::VectorXd> context_ro_operation_2 = std::async(
std::launch::async, context_ro_operation, context.get());
// Wait for operations to complete, and ensure they don't throw.
DRAKE_EXPECT_NO_THROW(context_ro_operation_1.get());
DRAKE_EXPECT_NO_THROW(context_ro_operation_2.get());
// Thaw context.
context->UnfreezeCache();
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/system_output_test.cc | #include "drake/systems/framework/system_output.h"
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/is_dynamic_castable.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/test_utilities/my_vector.h"
namespace drake {
namespace systems {
// Construction and add_port() calls here are permitted only because this test
// class has been granted friend access to SystemOutput. Otherwise a
// SystemOutput<T> object can only be created by a System<T> object, or by
// copying an existing SystemOutput object.
class SystemOutputTest : public ::testing::Test {
protected:
void SetUp() override {
// Vector output port 0 is just a BasicVector<double>.
const BasicVector<double> vec{5, 25};
output_.add_port(AbstractValue::Make(vec));
// Vector output port 1 is derived from BasicVector<double>. The concrete
// type should be preserved when copying.
auto my_vec = MyVector3d::Make(125, 625, 3125);
auto my_basic_vec =
std::make_unique<Value<BasicVector<double>>>(std::move(my_vec));
output_.add_port(std::move(my_basic_vec));
// Abstract output port 2 is a string.
auto str = AbstractValue::Make(std::string("foo"));
output_.add_port(std::move(str));
}
SystemOutput<double> output_;
};
TEST_F(SystemOutputTest, Access) {
VectorX<double> expected(2);
expected << 5, 25;
EXPECT_EQ(
expected,
output_.get_vector_data(0)->get_value());
EXPECT_EQ("foo", output_.get_data(2)->get_value<std::string>());
}
TEST_F(SystemOutputTest, Mutation) {
output_.GetMutableVectorData(0)->get_mutable_value() << 7, 8;
// Check that the vector contents changed.
VectorX<double> expected(2);
expected << 7, 8;
EXPECT_EQ(expected, output_.get_vector_data(0)->get_value());
output_.GetMutableData(2)->get_mutable_value<std::string>() = "bar";
// Check that the contents changed.
EXPECT_EQ("bar", output_.get_data(2)->get_value<std::string>());
}
// Tests that a copy of a SystemOutput has a deep copy of the data.
TEST_F(SystemOutputTest, Copy) {
SystemOutput<double> copy(output_);
// Changes to the original port should not affect the copy.
output_.GetMutableVectorData(0)->get_mutable_value() << 7, 8;
output_.GetMutableData(2)->get_mutable_value<std::string>() = "bar";
VectorX<double> expected(2);
expected << 5, 25;
EXPECT_EQ(expected, copy.get_vector_data(0)->get_value());
EXPECT_EQ("foo", copy.get_data(2)->get_value<std::string>());
// The type and value should be preserved.
const BasicVector<double>* basic = copy.get_vector_data(1);
ASSERT_TRUE((is_dynamic_castable<const MyVector3d>(basic)));
expected.resize(3);
expected << 125, 625, 3125;
EXPECT_EQ(expected, basic->get_value());
}
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/event_status_test.cc | #include "drake/systems/framework/event_status.h"
#include <gtest/gtest.h>
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace systems {
namespace {
bool equal_status(const EventStatus& one, const EventStatus& two) {
return one.severity() == two.severity() && one.system() == two.system() &&
one.message() == two.message();
}
GTEST_TEST(EventStatusTest, ConstructionAndRetrieval) {
const SystemBase* dummy = reinterpret_cast<const SystemBase*>(0x1234);
// EventStatus can only be produced by factory methods.
const EventStatus did_nothing = EventStatus::DidNothing();
const EventStatus succeeded = EventStatus::Succeeded();
const EventStatus terminated =
EventStatus::ReachedTermination(dummy, "reached termination");
const EventStatus failed = EventStatus::Failed(dummy, "failed");
EXPECT_EQ(did_nothing.severity(), EventStatus::kDidNothing);
EXPECT_EQ(succeeded.severity(), EventStatus::kSucceeded);
EXPECT_EQ(terminated.severity(), EventStatus::kReachedTermination);
EXPECT_EQ(failed.severity(), EventStatus::kFailed);
EXPECT_EQ(did_nothing.system(), nullptr);
EXPECT_EQ(succeeded.system(), nullptr);
EXPECT_EQ(terminated.system(), dummy);
EXPECT_EQ(failed.system(), dummy);
EXPECT_EQ(did_nothing.message(), "");
EXPECT_EQ(succeeded.message(), "");
EXPECT_EQ(terminated.message(), "reached termination");
EXPECT_EQ(failed.message(), "failed");
// Make sure the statuses are ordered.
EXPECT_LT(EventStatus::kDidNothing, EventStatus::kSucceeded);
EXPECT_LT(EventStatus::kSucceeded, EventStatus::kReachedTermination);
EXPECT_LT(EventStatus::kReachedTermination, EventStatus::kFailed);
// Test that KeepMoreSevere() works properly.
EventStatus status = EventStatus::Succeeded();
// Should update when more severe, not when less severe.
status.KeepMoreSevere(terminated);
EXPECT_TRUE(equal_status(status, terminated));
status.KeepMoreSevere(did_nothing);
EXPECT_TRUE(equal_status(status, terminated));
// Should not update when same severity (first one wins).
const SystemBase* dummy2 = reinterpret_cast<const SystemBase*>(0x5678);
const EventStatus failed2 = EventStatus::Failed(dummy2, "failed again");
status.KeepMoreSevere(failed); // Should update.
EXPECT_TRUE(equal_status(status, failed));
status.KeepMoreSevere(failed2); // Should not update (same severity).
EXPECT_TRUE(equal_status(status, failed));
}
class TestSystem : public LeafSystem<double> {
public:
TestSystem() {
this->set_name("my_system");
}
};
// Check that the ThrowOnFailure() function formats correctly.
GTEST_TEST(EventStatusTest, ThrowOnFailure) {
TestSystem test_system;
const EventStatus success = EventStatus::Succeeded();
const EventStatus did_nothing = EventStatus::DidNothing();
const EventStatus terminated = EventStatus::ReachedTermination(
&test_system, "this shouldn't throw");
const EventStatus failed_no_system =
EventStatus::Failed(nullptr, "error from somewhere");
const EventStatus failed_with_system =
EventStatus::Failed(&test_system, "error from test system");
EXPECT_NO_THROW(success.ThrowOnFailure("ApiName"));
EXPECT_NO_THROW(did_nothing.ThrowOnFailure("ApiName"));
EXPECT_NO_THROW(terminated.ThrowOnFailure("ApiName"));
DRAKE_EXPECT_THROWS_MESSAGE(failed_no_system.ThrowOnFailure("ApiName"),
"ApiName\\(\\):.*event handler in System "
"failed with message.*error from somewhere.*");
DRAKE_EXPECT_THROWS_MESSAGE(failed_with_system.ThrowOnFailure("ApiName"),
"ApiName\\(\\):.*event handler in.*TestSystem.*"
"my_system.*failed with message.*error from "
"test system.*");
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/model_values_test.cc | #include "drake/systems/framework/model_values.h"
#include <gtest/gtest.h>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_copyable.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/test_utilities/my_vector.h"
namespace drake {
namespace systems {
namespace internal {
namespace {
using symbolic::Expression;
/// Tests the AbstractValue basics.
GTEST_TEST(ModelValuesTest, AbstractValueTest) {
// The "device under test".
ModelValues dut;
// Empty.
EXPECT_EQ(dut.size(), 0);
// [0] is nullptr; [1] is 11.
dut.AddModel(1, std::make_unique<Value<int>>(11));
EXPECT_EQ(dut.size(), 2);
EXPECT_EQ(dut.CloneModel(0).get(), nullptr);
auto abstract_value = dut.CloneModel(1);
ASSERT_NE(abstract_value.get(), nullptr);
EXPECT_EQ(abstract_value->get_value<int>(), 11);
// Repeated clones work fine.
ASSERT_NE(dut.CloneModel(1).get(), nullptr);
// Expand enough to likely cause a vector reallocation.
// [0] is nullptr; [1] is 11; [99] is 999.
dut.AddModel(99, std::make_unique<Value<int>>(999));
EXPECT_EQ(dut.size(), 100);
EXPECT_EQ(dut.CloneModel(0).get(), nullptr);
EXPECT_EQ(dut.CloneModel(1)->get_value<int>(), 11);
EXPECT_EQ(dut.CloneModel(50).get(), nullptr);
EXPECT_EQ(dut.CloneModel(99)->get_value<int>(), 999);
// Unknown indices are nullptr.
EXPECT_EQ(dut.CloneModel(1000000).get(), nullptr);
// Test CloneAllModels().
auto cloned_vec = dut.CloneAllModels();
EXPECT_EQ(cloned_vec.size(), 100);
for (int i = 0; i < 100; ++i) {
if (i == 1) {
EXPECT_EQ(cloned_vec[i]->get_value<int>(), 11);
} else if (i == 99) {
EXPECT_EQ(cloned_vec[i]->get_value<int>(), 999);
} else {
EXPECT_EQ(cloned_vec[i].get(), nullptr);
}
}
}
/// Tests the BasicVector<T> sugar.
GTEST_TEST(ModelValuesTest, VectorValueTest) {
// The "device under test".
ModelValues dut;
// [1] is Value<int>(11).
// [3] is BasicVector<double>(33, 34).
// [5] is MyVector2d<double>(55, 56).
dut.AddModel(1, std::make_unique<Value<int>>(11));
dut.AddVectorModel(3, BasicVector<double>::Make({33, 34}));
dut.AddVectorModel<double>(5, MyVector2d::Make(55, 56));
// Empty model values are still nullptr, even with vector sugar.
EXPECT_EQ(dut.CloneVectorModel<double>(0).get(), nullptr);
EXPECT_EQ(dut.CloneVectorModel<double>(2).get(), nullptr);
EXPECT_EQ(dut.CloneVectorModel<double>(4).get(), nullptr);
// The AbstractValue is still okay.
EXPECT_EQ(dut.CloneModel(1)->get_value<int>(), 11);
// Some BasicVector access patterns are okay.
EXPECT_EQ(dut.CloneVectorModel<double>(3)->size(), 2);
EXPECT_EQ(dut.CloneVectorModel<double>(3)->GetAtIndex(0), 33);
EXPECT_EQ(dut.CloneVectorModel<double>(3)->GetAtIndex(1), 34);
EXPECT_EQ(dut.CloneVectorModel<double>(5)->size(), 2);
EXPECT_EQ(dut.CloneVectorModel<double>(5)->GetAtIndex(0), 55);
EXPECT_EQ(dut.CloneVectorModel<double>(5)->GetAtIndex(1), 56);
// The subclass comes through okay.
auto basic_vector = dut.CloneVectorModel<double>(5);
MyVector2d* const my_vector = dynamic_cast<MyVector2d*>(basic_vector.get());
ASSERT_NE(my_vector, nullptr);
// Various wrong access patterns throw.
EXPECT_THROW(dut.CloneVectorModel<double>(1), std::exception);
EXPECT_THROW(dut.CloneVectorModel<AutoDiffXd>(3), std::exception);
EXPECT_THROW(dut.CloneVectorModel<Expression>(5), std::exception);
// Unknown indices are nullptr, even with vector sugar.
EXPECT_EQ(dut.CloneVectorModel<double>(1000000).get(), nullptr);
}
/// Tests the details of nullptr handling.
GTEST_TEST(ModelValuesTest, NullTest) {
// The "device under test".
ModelValues dut;
// Add different flavors of nullptr.
dut.AddModel(0, nullptr);
EXPECT_EQ(dut.size(), 1);
dut.AddVectorModel<double>(1, nullptr);
EXPECT_EQ(dut.size(), 2);
dut.AddVectorModel<AutoDiffXd>(2, nullptr);
EXPECT_EQ(dut.size(), 3);
dut.AddVectorModel<Expression>(3, nullptr);
EXPECT_EQ(dut.size(), 4);
// Clone using the AbstractValue base type.
EXPECT_EQ(dut.CloneModel(0).get(), nullptr);
EXPECT_EQ(dut.CloneModel(1).get(), nullptr);
EXPECT_EQ(dut.CloneModel(2).get(), nullptr);
EXPECT_EQ(dut.CloneModel(3).get(), nullptr);
// Clone as VectorValue (yielding a nullptr BasicVector).
EXPECT_EQ(dut.CloneVectorModel<double>(0), nullptr);
EXPECT_EQ(dut.CloneVectorModel<double>(1), nullptr);
EXPECT_EQ(dut.CloneVectorModel<AutoDiffXd>(2), nullptr);
EXPECT_EQ(dut.CloneVectorModel<Expression>(3), nullptr);
}
} // namespace
} // namespace internal
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/diagram_builder_test.cc | #include "drake/systems/framework/diagram_builder.h"
#include <regex>
#include <Eigen/Dense>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/trajectories/exponential_plus_piecewise_polynomial.h"
#include "drake/common/trajectories/piecewise_polynomial.h"
#include "drake/systems/framework/diagram.h"
#include "drake/systems/primitives/adder.h"
#include "drake/systems/primitives/constant_vector_source.h"
#include "drake/systems/primitives/demultiplexer.h"
#include "drake/systems/primitives/gain.h"
#include "drake/systems/primitives/integrator.h"
#include "drake/systems/primitives/pass_through.h"
namespace drake {
namespace systems {
namespace {
using InputPortLocator = DiagramBuilder<double>::InputPortLocator;
using OutputPortLocator = DiagramBuilder<double>::OutputPortLocator;
// Simply an untemplated system that can be extracted from a builder via
// Get[Mutable]DowncastSubsystemByName.
class UntemplatedSystem : public LeafSystem<double> {};
// Tests ::empty().
GTEST_TEST(DiagramBuilderTest, Empty) {
DiagramBuilder<double> builder;
const DiagramBuilder<double>& const_builder = builder;
EXPECT_TRUE(const_builder.empty());
EXPECT_EQ(const_builder.num_input_ports(), 0);
EXPECT_EQ(const_builder.num_output_ports(), 0);
builder.AddSystem<Adder>(1 /* inputs */, 1 /* size */);
EXPECT_FALSE(const_builder.empty());
}
// Tests ::AddNamedSystem() post-condition.
GTEST_TEST(DiagramBuilderTest, AddNamedSystem) {
DiagramBuilder<double> builder;
auto a = builder.AddNamedSystem("a", std::make_unique<Adder<double>>(2, 1));
EXPECT_EQ(a->get_name(), "a");
auto b = builder.AddNamedSystem<Adder<double>>("b", 2, 1);
EXPECT_EQ(b->get_name(), "b");
auto c = builder.AddNamedSystem<Adder>("c", 2 , 1);
EXPECT_EQ(c->get_name(), "c");
}
// Tests ::RemoveSystem.
GTEST_TEST(DiagramBuilderTest, Remove) {
DiagramBuilder<double> builder;
// First, create this builder layout:
//
// ---------------------------
// u0 | ==> pass0a => pass0b => | y0
// | |
// u1 | ==> adder ==> pass1 ==> | y1
// | ^ ⧵ |
// | / ⧵==========> | adder_out
// | / |
// u2 | ============> pass2 ==> | y2
// ---------------------------
//
// This setup is carefully chosen such that removing 'adder' will cover all
// branching conditions within the implementation.
const auto& pass0a = *builder.AddSystem<PassThrough>(1 /* size */);
const auto& pass0b = *builder.AddSystem<PassThrough>(1 /* size */);
builder.Connect(pass0a, pass0b);
builder.ExportInput(pass0a.get_input_port(), "u0");
builder.ExportOutput(pass0b.get_output_port(), "y0");
const auto& adder = *builder.AddSystem<Adder>(2 /* inputs */, 1 /* size */);
builder.ExportInput(adder.get_input_port(0), "u1");
builder.ExportInput(adder.get_input_port(1), "u2");
const auto& pass1 = *builder.AddSystem<PassThrough>(1 /* size */);
builder.Connect(adder, pass1);
builder.ExportOutput(pass1.get_output_port(), "y1");
builder.ExportOutput(adder.get_output_port(), "adder_out");
const auto& pass2 = *builder.AddSystem<PassThrough>(1 /* size */);
builder.ConnectInput("u2", pass2.get_input_port());
builder.ExportOutput(pass2.get_output_port(), "y2");
// Now, remove the 'adder' leaving this diagram:
//
// ---------------------------
// u0 | ==> pass0a => pass0b => | y0
// | pass1 ==> | y1
// u2 | ============> pass2 ==> | y2
// ---------------------------
//
builder.RemoveSystem(adder);
auto diagram = builder.Build();
ASSERT_EQ(diagram->num_input_ports(), 2);
ASSERT_EQ(diagram->num_output_ports(), 3);
EXPECT_EQ(diagram->get_input_port(0).get_name(), "u0");
EXPECT_EQ(diagram->get_input_port(1).get_name(), "u2");
EXPECT_EQ(diagram->get_output_port(0).get_name(), "y0");
EXPECT_EQ(diagram->get_output_port(1).get_name(), "y1");
EXPECT_EQ(diagram->get_output_port(2).get_name(), "y2");
auto context = diagram->CreateDefaultContext();
diagram->GetInputPort("u0").FixValue(context.get(),
Eigen::VectorXd::Constant(1, 22.0));
diagram->GetInputPort("u2").FixValue(context.get(),
Eigen::VectorXd::Constant(1, 44.0));
EXPECT_EQ(diagram->GetOutputPort("y0").Eval(*context)[0], 22.0);
EXPECT_EQ(diagram->GetOutputPort("y2").Eval(*context)[0], 44.0);
}
// Tests ::RemoveSystem error message.
GTEST_TEST(DiagramBuilderTest, RemoveError) {
DiagramBuilder<double> builder;
PassThrough<double> dummy(1);
dummy.set_name("dummy");
DRAKE_EXPECT_THROWS_MESSAGE(builder.RemoveSystem(dummy),
".*RemoveSystem.*dummy.*not.*added.*");
}
// Tests already_built() and one example of ThrowIfAlreadyBuilt().
GTEST_TEST(DiagramBuilderTest, AlreadyBuilt) {
DiagramBuilder<double> builder;
builder.AddSystem<Adder>(1 /* inputs */, 1 /* size */);
EXPECT_FALSE(builder.already_built());
auto diagram = builder.Build();
EXPECT_TRUE(builder.already_built());
DRAKE_EXPECT_THROWS_MESSAGE(
builder.AddSystem<Adder>(2, 2),
".*DiagramBuilder may no longer be used.*");
}
// A special class to distinguish between cycles and algebraic loops. The system
// has one input and two outputs. One output simply "echoes" the input (direct
// feedthrough). The other output merely outputs a const value. That means, the
// system *has* feedthrough, but a cycle in the diagram graph does not imply
// an algebraic loop.
template <typename T>
class ConstAndEcho final : public LeafSystem<T> {
public:
ConstAndEcho() : LeafSystem<T>(SystemTypeTag<ConstAndEcho>{}) {
this->DeclareInputPort("input", kVectorValued, 1);
this->DeclareVectorOutputPort("echo", 1, &ConstAndEcho::CalcEcho);
this->DeclareVectorOutputPort("constant", 1, &ConstAndEcho::CalcConstant);
}
// Scalar-converting copy constructor.
template <typename U>
explicit ConstAndEcho(const ConstAndEcho<U>&) : ConstAndEcho() {}
const systems::InputPort<T>& get_vec_input_port() const {
return this->get_input_port(0);
}
const systems::OutputPort<T>& get_echo_output_port() const {
return systems::System<T>::get_output_port(0);
}
const systems::OutputPort<T>& get_const_output_port() const {
return systems::System<T>::get_output_port(1);
}
void CalcConstant(const Context<T>& context,
BasicVector<T>* const_value) const {
const_value->get_mutable_value() << 17;
}
void CalcEcho(const Context<T>& context, BasicVector<T>* echo) const {
const auto& input = this->get_vec_input_port().Eval(context);
echo->get_mutable_value() = input;
}
};
// Tests that an exception is thrown if the diagram contains an algebraic loop.
GTEST_TEST(DiagramBuilderTest, AlgebraicLoop) {
DiagramBuilder<double> builder;
auto adder = builder.AddNamedSystem<Adder>(
"adder", 1 /* inputs */, 1 /* size */);
auto pass = builder.AddNamedSystem<PassThrough>("pass", 1 /* size */);
// Connect the output port to the input port.
builder.Connect(adder->get_output_port(), pass->get_input_port());
builder.Connect(pass->get_output_port(), adder->get_input_port(0));
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Build(),
fmt::format(
"Reported algebraic loop detected in DiagramBuilder:\n"
" InputPort.0. .u0. of {adder} is direct-feedthrough to\n"
" OutputPort.0. .sum. of {adder} is connected to\n"
" InputPort.0. .u. of {pass} is direct-feedthrough to\n"
" OutputPort.0. .y. of {pass} is connected to\n"
" InputPort.0. .u0. of {adder}\n"
".*conservatively reported.*",
fmt::arg("adder", "System ::adder .Adder<double>."),
fmt::arg("pass", "System ::pass .PassThrough<double>.")));
}
// Tests that a cycle which is not an algebraic loop is recognized as valid.
// The system has direct feedthrough; but, at the port level, it is wired
// without an algebraic loop at the port level.
GTEST_TEST(DiagramBuilderTest, CycleButNoLoopPortLevel) {
DiagramBuilder<double> builder;
// +----------+
// |---+ +---|
// +->| I |->| E |
// | |---+ +---|
// | | +---|
// | | | C |--+
// | | +---| |
// | |__________| |
// | |
// +----------------+
//
// The input feeds through to the echo output, but it is the constant output
// that is connected to input. So, the system has direct feedthrough, the
// diagram has a cycle at the *system* level, but there is no algebraic loop.
auto echo = builder.AddNamedSystem<ConstAndEcho>("echo");
builder.Connect(echo->get_const_output_port(), echo->get_vec_input_port());
DRAKE_EXPECT_NO_THROW(builder.Build());
}
// Contrasts with CycleButNoLoopPortLevel. In this case, the cycle *does*
// represent an algebraic loop.
GTEST_TEST(DiagramBuilderTest, CycleAtLoopPortLevel) {
DiagramBuilder<double> builder;
// +----------+
// |---+ +---|
// +->| I |->| E |--+
// | |---+ +---| |
// | | +---| |
// | | | C | |
// | | +---| |
// | |__________| |
// | |
// +----------------+
//
// The input feeds through to the echo output, but it is the constant output
// that is connected to input. So, the system has direct feeedthrough, the
// diagram has a cycle at the *system* level, but there is no algebraic loop.
auto echo = builder.AddNamedSystem<ConstAndEcho>("echo");
builder.Connect(echo->get_echo_output_port(), echo->get_vec_input_port());
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Build(),
fmt::format(
"Reported algebraic loop detected in DiagramBuilder:\n"
" InputPort.0. .input. of {sys} is direct-feedthrough to\n"
" OutputPort.0. .echo. of {sys} is connected to\n"
" InputPort.0. .input. of {sys}\n"
".*conservatively reported.*",
fmt::arg("sys", "System ::echo .ConstAndEcho<double>.")));
}
// Tests that a cycle which is not an algebraic loop is recognized as valid.
// The cycle contains a system with no direct feedthrough; so the apparent loop
// is broken at the *system* level.
GTEST_TEST(DiagramBuilderTest, CycleButNoAlgebraicLoopSystemLevel) {
DiagramBuilder<double> builder;
// Create the following diagram:
//
// input --->| 0 |
// | Adder +---> Integrator -|
// |->| 1 | |---> output
// |------------------------------|
auto adder = builder.AddNamedSystem<Adder>(
"adder", 2 /* inputs */, 1 /* size */);
auto integrator = builder.AddNamedSystem<Integrator>(
"integrator", 1 /* size */);
builder.Connect(integrator->get_output_port(), adder->get_input_port(1));
// There is no algebraic loop, so we should not throw.
DRAKE_EXPECT_NO_THROW(builder.Build());
}
// Tests that multiple cascaded elements that are not direct-feedthrough
// are buildable.
GTEST_TEST(DiagramBuilderTest, CascadedNonDirectFeedthrough) {
DiagramBuilder<double> builder;
auto integrator1 = builder.AddNamedSystem<Integrator>(
"integrator1", 1 /* size */);
auto integrator2 = builder.AddNamedSystem<Integrator>(
"integrator2, ", 1 /* size */);
builder.Connect(integrator1->get_output_port(),
integrator2->get_input_port());
// There is no algebraic loop, so we should not throw.
DRAKE_EXPECT_NO_THROW(builder.Build());
}
// Tests that an exception is thrown when building an empty diagram.
GTEST_TEST(DiagramBuilderTest, FinalizeWhenEmpty) {
DiagramBuilder<double> builder;
EXPECT_THROW(builder.Build(), std::logic_error);
}
GTEST_TEST(DiagramBuilderTest, SystemsThatAreNotAddedThrow) {
DiagramBuilder<double> builder;
// These integrators should be listed in the error messages when it prints the
// lists of registered systems.
builder.AddNamedSystem<Integrator>("integrator1", 1 /* size */);
builder.AddNamedSystem<Integrator>("integrator2", 1 /* size */);
Adder<double> adder(1 /* inputs */, 1 /* size */);
adder.set_name("adder");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Connect(adder, adder),
"DiagramBuilder: System 'adder' has not been registered to this "
"DiagramBuilder using AddSystem nor AddNamedSystem.\n\n.*'integrator1', "
"'integrator2'.*\n\n.*");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.ExportInput(adder.get_input_port(0)),
"DiagramBuilder: System 'adder' has not been registered to this "
"DiagramBuilder using AddSystem nor AddNamedSystem.\n\n.*'integrator1', "
"'integrator2'.*\n\n.*");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.ExportOutput(adder.get_output_port()),
"DiagramBuilder: System 'adder' has not been registered to this "
"DiagramBuilder using AddSystem nor AddNamedSystem.\n\n.*'integrator1', "
"'integrator2'.*\n\n.*");
}
GTEST_TEST(DiagramBuilderTest, ConnectVectorToAbstractThrow) {
DiagramBuilder<double> builder;
auto vector_system = builder.AddNamedSystem<PassThrough<double>>(
"vector_system", 1 /* size */);
auto abstract_system = builder.AddNamedSystem<PassThrough<double>>(
"abstract_system", Value<int>{});
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Connect(
vector_system->get_output_port(),
abstract_system->get_input_port()),
"DiagramBuilder::Connect: "
"Cannot mix vector-valued and abstract-valued ports while connecting "
"output port y of System vector_system to "
"input port u of System abstract_system");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Connect(
abstract_system->get_output_port(),
vector_system->get_input_port()),
"DiagramBuilder::Connect: "
"Cannot mix vector-valued and abstract-valued ports while connecting "
"output port y of System abstract_system to "
"input port u of System vector_system");
}
GTEST_TEST(DiagramBuilderTest, ExportInputVectorToAbstractThrow) {
DiagramBuilder<double> builder;
auto vector_system = builder.AddSystem<PassThrough<double>>(1 /* size */);
vector_system->set_name("vector_system");
auto abstract_system = builder.AddSystem<PassThrough<double>>(Value<int>{});
abstract_system->set_name("abstract_system");
auto port_index = builder.ExportInput(vector_system->get_input_port());
DRAKE_EXPECT_THROWS_MESSAGE(
builder.ConnectInput(port_index, abstract_system->get_input_port()),
"DiagramBuilder::ConnectInput: "
"Cannot mix vector-valued and abstract-valued ports while connecting "
"input port u of System abstract_system to "
"input port vector_system_u of Diagram");
}
GTEST_TEST(DiagramBuilderTest, ExportInputAbstractToVectorThrow) {
DiagramBuilder<double> builder;
auto vector_system = builder.AddSystem<PassThrough<double>>(1 /* size */);
vector_system->set_name("vector_system");
auto abstract_system = builder.AddSystem<PassThrough<double>>(Value<int>{});
abstract_system->set_name("abstract_system");
auto port_index = builder.ExportInput(abstract_system->get_input_port());
DRAKE_EXPECT_THROWS_MESSAGE(
builder.ConnectInput(port_index, vector_system->get_input_port()),
"DiagramBuilder::ConnectInput: "
"Cannot mix vector-valued and abstract-valued ports while connecting "
"input port u of System vector_system to "
"input port abstract_system_u of Diagram");
}
GTEST_TEST(DiagramBuilderTest, ConnectVectorSizeMismatchThrow) {
DiagramBuilder<double> builder;
auto size1_system = builder.AddNamedSystem<PassThrough<double>>(
"size1_system", 1 /* size */);
auto size2_system = builder.AddNamedSystem<PassThrough<double>>(
"size2_system", 2 /* size */);
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Connect(
size1_system->get_output_port(),
size2_system->get_input_port()),
"DiagramBuilder::Connect: "
"Mismatched vector sizes while connecting "
"output port y of System size1_system \\(size 1\\) to "
"input port u of System size2_system \\(size 2\\)");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Connect(
size2_system->get_output_port(),
size1_system->get_input_port()),
"DiagramBuilder::Connect: "
"Mismatched vector sizes while connecting "
"output port y of System size2_system \\(size 2\\) to "
"input port u of System size1_system \\(size 1\\)");
}
GTEST_TEST(DiagramBuilderTest, ExportInputVectorSizeMismatchThrow) {
DiagramBuilder<double> builder;
auto size1_system = builder.AddSystem<PassThrough<double>>(1 /* size */);
size1_system->set_name("size1_system");
auto size2_system = builder.AddSystem<PassThrough<double>>(2 /* size */);
size2_system->set_name("size2_system");
auto port_index = builder.ExportInput(size1_system->get_input_port());
DRAKE_EXPECT_THROWS_MESSAGE(
builder.ConnectInput(port_index, size2_system->get_input_port()),
"DiagramBuilder::ConnectInput: "
"Mismatched vector sizes while connecting "
"input port u of System size2_system \\(size 2\\) to "
"input port size1_system_u of Diagram \\(size 1\\)");
}
GTEST_TEST(DiagramBuilderTest, ConnectAbstractTypeMismatchThrow) {
DiagramBuilder<double> builder;
auto int_system = builder.AddNamedSystem<PassThrough<double>>(
"int_system", Value<int>{});
auto char_system = builder.AddNamedSystem<PassThrough<double>>(
"char_system", Value<char>{});
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Connect(
int_system->get_output_port(),
char_system->get_input_port()),
"DiagramBuilder::Connect: "
"Mismatched value types while connecting "
"output port y of System int_system \\(type int\\) to "
"input port u of System char_system \\(type char\\)");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.Connect(
char_system->get_output_port(),
int_system->get_input_port()),
"DiagramBuilder::Connect: "
"Mismatched value types while connecting "
"output port y of System char_system \\(type char\\) to "
"input port u of System int_system \\(type int\\)");
}
GTEST_TEST(DiagramBuilderTest, ExportInputAbstractTypeMismatchThrow) {
DiagramBuilder<double> builder;
auto int_system = builder.AddSystem<PassThrough<double>>(Value<int>{});
int_system->set_name("int_system");
auto char_system = builder.AddSystem<PassThrough<double>>(Value<char>{});
char_system->set_name("char_system");
auto port_index = builder.ExportInput(int_system->get_input_port());
DRAKE_EXPECT_THROWS_MESSAGE(
builder.ConnectInput(port_index, char_system->get_input_port()),
"DiagramBuilder::ConnectInput: "
"Mismatched value types while connecting "
"input port u of System char_system \\(type char\\) to "
"input port int_system_u of Diagram \\(type int\\)");
}
// Test that port connections can be polymorphic, especially for types that are
// both copyable and cloneable. {ExponentialPlus,}PiecewisePolynomial are both
// copyable (to themselves) and cloneable (to a common base class, Trajectory).
// To connect them in a diagram, we must specify we want to use the subtyping.
GTEST_TEST(DiagramBuilderTest, ConnectAbstractSubtypes) {
using Trajectoryd = trajectories::Trajectory<double>;
using PiecewisePolynomiald = trajectories::PiecewisePolynomial<double>;
using ExponentialPlusPiecewisePolynomiald =
trajectories::ExponentialPlusPiecewisePolynomial<double>;
DiagramBuilder<double> builder;
auto sys1 = builder.AddSystem<PassThrough<double>>(
Value<Trajectoryd>(PiecewisePolynomiald{}));
auto sys2 = builder.AddSystem<PassThrough<double>>(
Value<Trajectoryd>(ExponentialPlusPiecewisePolynomiald{}));
DRAKE_EXPECT_NO_THROW(builder.Connect(*sys1, *sys2));
EXPECT_FALSE(builder.IsConnectedOrExported(sys1->get_input_port()));
builder.ExportInput(sys1->get_input_port());
EXPECT_TRUE(builder.IsConnectedOrExported(sys1->get_input_port()));
builder.ExportOutput(sys2->get_output_port());
auto diagram = builder.Build();
// We can feed PiecewisePolynomial through the Diagram.
{
auto context = diagram->CreateDefaultContext();
const PiecewisePolynomiald input(Vector1d(22.0));
diagram->get_input_port(0).FixValue(
context.get(), Value<Trajectoryd>(input));
const auto& output =
dynamic_cast<const PiecewisePolynomiald&>(
diagram->get_output_port(0).Eval<Trajectoryd>(*context));
EXPECT_EQ(output.value(0.0)(0), 22.0);
}
// We can feed ExponentialPlusPiecewisePolynomial through the Diagram.
{
auto context = diagram->CreateDefaultContext();
const ExponentialPlusPiecewisePolynomiald input(
PiecewisePolynomiald::ZeroOrderHold(Eigen::Vector2d(0., 1.),
Eigen::RowVector2d(22.0, 22.0)));
diagram->get_input_port(0).FixValue(
context.get(), Value<Trajectoryd>(input));
const auto& output =
dynamic_cast<const ExponentialPlusPiecewisePolynomiald&>(
diagram->get_output_port(0).Eval<Trajectoryd>(*context));
EXPECT_EQ(output.value(0.0)(0), 22.0);
}
}
// Helper class that has one input port, and no output ports.
template <typename T>
class Sink : public LeafSystem<T> {
public:
Sink() { this->DeclareInputPort("in", kVectorValued, 1); }
};
// Helper class that has no input port, and one output port.
template <typename T>
class Source : public LeafSystem<T> {
public:
Source() { this->DeclareVectorOutputPort("out", &Source<T>::CalcOutput); }
void CalcOutput(const Context<T>& context, BasicVector<T>* output) const {}
};
GTEST_TEST(DiagramBuilderTest, DefaultInputPortNamesAreUniqueTest) {
DiagramBuilder<double> builder;
auto sink1 = builder.AddSystem<Sink<double>>();
auto sink2 = builder.AddSystem<Sink<double>>();
EXPECT_FALSE(builder.IsConnectedOrExported(sink1->get_input_port(0)));
EXPECT_FALSE(builder.IsConnectedOrExported(sink2->get_input_port(0)));
builder.ExportInput(sink1->get_input_port(0));
builder.ExportInput(sink2->get_input_port(0));
EXPECT_TRUE(builder.IsConnectedOrExported(sink1->get_input_port(0)));
EXPECT_TRUE(builder.IsConnectedOrExported(sink2->get_input_port(0)));
// If the port names were not unique, then the build step would throw.
DRAKE_EXPECT_NO_THROW(builder.Build());
}
GTEST_TEST(DiagramBuilderTest, DefaultOutputPortNamesAreUniqueTest) {
DiagramBuilder<double> builder;
auto source1 = builder.AddSystem<Source<double>>();
auto source2 = builder.AddSystem<Source<double>>();
builder.ExportOutput(source1->get_output_port(0));
builder.ExportOutput(source2->get_output_port(0));
// If the port names were not unique, then the build step would throw.
DRAKE_EXPECT_NO_THROW(builder.Build());
}
GTEST_TEST(DiagramBuilderTest, DefaultPortNamesAreUniqueTest2) {
DiagramBuilder<double> builder;
// This time, we assign system names manually.
auto sink1 = builder.AddNamedSystem<Sink<double>>("sink1");
auto sink2 = builder.AddNamedSystem<Sink<double>>("sink2");
auto source1 = builder.AddNamedSystem<Source<double>>("source1");
auto source2 = builder.AddNamedSystem<Source<double>>("source2");
const auto sink1_in = builder.ExportInput(sink1->get_input_port(0));
const auto sink2_in = builder.ExportInput(sink2->get_input_port(0));
const auto source1_out = builder.ExportOutput(source1->get_output_port(0));
const auto source2_out = builder.ExportOutput(source2->get_output_port(0));
auto diagram = builder.Build();
EXPECT_EQ(diagram->get_input_port(sink1_in).get_name(), "sink1_in");
EXPECT_EQ(diagram->get_input_port(sink2_in).get_name(), "sink2_in");
EXPECT_EQ(diagram->get_output_port(source1_out).get_name(), "source1_out");
EXPECT_EQ(diagram->get_output_port(source2_out).get_name(), "source2_out");
}
GTEST_TEST(DiagramBuilderTest, SetPortNamesTest) {
DiagramBuilder<double> builder;
auto sink1 = builder.AddSystem<Sink<double>>();
auto sink2 = builder.AddSystem<Sink<double>>();
auto source1 = builder.AddSystem<Source<double>>();
auto source2 = builder.AddSystem<Source<double>>();
const auto sink1_in = builder.ExportInput(sink1->get_input_port(0), "sink1");
const auto sink2_in = builder.ExportInput(sink2->get_input_port(0), "sink2");
const auto source1_out =
builder.ExportOutput(source1->get_output_port(0), "source1");
const auto source2_out =
builder.ExportOutput(source2->get_output_port(0), "source2");
auto diagram = builder.Build();
EXPECT_EQ(diagram->get_input_port(sink1_in).get_name(), "sink1");
EXPECT_EQ(diagram->get_input_port(sink2_in).get_name(), "sink2");
EXPECT_EQ(diagram->get_output_port(source1_out).get_name(), "source1");
EXPECT_EQ(diagram->get_output_port(source2_out).get_name(), "source2");
}
GTEST_TEST(DiagramBuilderTest, DuplicateInputPortNamesThrow) {
DiagramBuilder<double> builder;
auto sink1 = builder.AddSystem<Sink<double>>();
auto sink2 = builder.AddSystem<Sink<double>>();
builder.ExportInput(sink1->get_input_port(0), "sink");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.ExportInput(sink2->get_input_port(0), "sink"),
".*already has an input port named.*");
}
GTEST_TEST(DiagramBuilderTest, ThrowIfInputAlreadyWired) {
DiagramBuilder<double> builder;
auto sink = builder.AddSystem<Sink<double>>();
builder.ExportInput(sink->get_input_port(0), "sink1");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.ExportInput(sink->get_input_port(0), "sink2"),
"Input port sink1 is already connected.");
}
GTEST_TEST(DiagramBuilderTest, InputPortNamesFanout) {
DiagramBuilder<double> builder;
auto sink1 = builder.AddSystem<Sink<double>>();
auto sink2 = builder.AddSystem<Sink<double>>();
auto sink3 = builder.AddSystem<Sink<double>>();
auto sink4 = builder.AddSystem<Sink<double>>();
auto sink5 = builder.AddSystem<Sink<double>>();
std::vector<InputPortIndex> indices;
// Name these ports just to make comparing easier later.
EXPECT_FALSE(builder.IsConnectedOrExported(sink1->get_input_port(0)));
indices.push_back(builder.ExportInput(sink1->get_input_port(0), "in1"));
EXPECT_TRUE(builder.IsConnectedOrExported(sink1->get_input_port(0)));
EXPECT_FALSE(builder.IsConnectedOrExported(sink2->get_input_port(0)));
indices.push_back(builder.ExportInput(sink2->get_input_port(0), "in2"));
EXPECT_TRUE(builder.IsConnectedOrExported(sink2->get_input_port(0)));
// Fan-out connect by index.
EXPECT_FALSE(builder.IsConnectedOrExported(sink3->get_input_port(0)));
builder.ConnectInput(indices[0], sink3->get_input_port(0));
EXPECT_TRUE(builder.IsConnectedOrExported(sink3->get_input_port(0)));
// Fan-out connect by name.
EXPECT_FALSE(builder.IsConnectedOrExported(sink4->get_input_port(0)));
builder.ConnectInput("in1", sink4->get_input_port(0));
EXPECT_TRUE(builder.IsConnectedOrExported(sink4->get_input_port(0)));
// Fan-out connect likewise.
EXPECT_FALSE(builder.IsConnectedOrExported(sink5->get_input_port(0)));
EXPECT_TRUE(builder.ConnectToSame(
sink1->get_input_port(0), sink5->get_input_port(0)));
EXPECT_TRUE(builder.IsConnectedOrExported(sink5->get_input_port(0)));
EXPECT_EQ(indices[0], 0);
EXPECT_EQ(indices[1], 1);
auto diagram = builder.Build();
EXPECT_EQ(diagram->num_input_ports(), 2);
EXPECT_EQ(diagram->get_input_port(0).get_name(), "in1");
EXPECT_EQ(diagram->get_input_port(1).get_name(), "in2");
auto sink_fanout = diagram->GetInputPortLocators(InputPortIndex(0));
EXPECT_EQ(sink_fanout.size(), 4);
auto sinkhole_fanout = diagram->GetInputPortLocators(InputPortIndex(1));
EXPECT_EQ(sinkhole_fanout.size(), 1);
}
GTEST_TEST(DiagramBuilderTest, DuplicateOutputPortNamesThrow) {
DiagramBuilder<double> builder;
auto sink1 = builder.AddSystem<Source<double>>();
auto sink2 = builder.AddSystem<Source<double>>();
builder.ExportOutput(sink1->get_output_port(0), "source");
builder.ExportOutput(sink2->get_output_port(0), "source");
DRAKE_EXPECT_THROWS_MESSAGE(builder.Build(),
".*already has an output port named.*");
}
// Tests the sole-port based overload of Connect().
class DiagramBuilderSolePortsTest : public ::testing::Test {
protected:
void SetUp() override {
out1_ = builder_.AddNamedSystem<ConstantVectorSource>(
"constant", Vector1d::Ones());
in1_ = builder_.AddNamedSystem<Sink>("sink");
in1out1_ = builder_.AddNamedSystem<Gain>(
"gain", 1.0 /* gain */, 1 /* size */);
in2out1_ = builder_.AddNamedSystem<Adder>(
"adder", 2 /* inputs */, 1 /* size */);
in1out2_ = builder_.AddNamedSystem<Demultiplexer>("demux", 2 /* size */);
}
DiagramBuilder<double> builder_;
ConstantVectorSource<double>* out1_ = nullptr;
Sink<double>* in1_ = nullptr;
Gain<double>* in1out1_ = nullptr;
Adder<double>* in2out1_ = nullptr;
Demultiplexer<double>* in1out2_ = nullptr;
};
// A diagram of Source->Gain->Sink is successful.
TEST_F(DiagramBuilderSolePortsTest, SourceGainSink) {
EXPECT_FALSE(builder_.IsConnectedOrExported(in1out1_->get_input_port()));
DRAKE_EXPECT_NO_THROW(builder_.Connect(*out1_, *in1out1_));
EXPECT_TRUE(builder_.IsConnectedOrExported(in1out1_->get_input_port()));
DRAKE_EXPECT_NO_THROW(builder_.Connect(*in1out1_, *in1_));
DRAKE_EXPECT_NO_THROW(builder_.Build());
}
// The connection map for Source->Gain->Sink is as expected.
TEST_F(DiagramBuilderSolePortsTest, ConnectionMap) {
builder_.Connect(*out1_, *in1out1_);
builder_.Connect(*in1out1_, *in1_);
ASSERT_EQ(builder_.connection_map().size(), 2);
{
const OutputPortLocator out1_output{out1_, OutputPortIndex{0}};
const InputPortLocator in1out1_input{in1out1_, InputPortIndex{0}};
EXPECT_EQ(builder_.connection_map().at(in1out1_input), out1_output);
}
{
const OutputPortLocator in1out1_output{in1out1_, OutputPortIndex{0}};
const InputPortLocator in1_input{in1_, InputPortIndex{0}};
EXPECT_EQ(builder_.connection_map().at(in1_input), in1out1_output);
}
}
// The cascade synonym also works.
TEST_F(DiagramBuilderSolePortsTest, SourceGainSinkCascade) {
DRAKE_EXPECT_NO_THROW(builder_.Cascade(*out1_, *in1out1_));
DRAKE_EXPECT_NO_THROW(builder_.Cascade(*in1out1_, *in1_));
DRAKE_EXPECT_NO_THROW(builder_.Build());
}
// A diagram can use ConnectToSame.
// Source-->Gain
// |->Sink
TEST_F(DiagramBuilderSolePortsTest, SourceGainSink2) {
builder_.Connect(*out1_, *in1out1_);
EXPECT_TRUE(builder_.ConnectToSame(
in1out1_->get_input_port(), in1_->get_input_port()));
auto diagram = builder_.Build();
const InputPortLocator in1_input{in1_, InputPortIndex{0}};
const auto& connections = diagram->connection_map();
ASSERT_TRUE(connections.contains(in1_input));
EXPECT_EQ(connections.find(in1_input)->second.first, out1_);
}
// Using ConnectToSame on a disconnected input is a no-op.
TEST_F(DiagramBuilderSolePortsTest, ConnectToSameNothing) {
EXPECT_FALSE(builder_.ConnectToSame(
in1out1_->get_input_port(), in1_->get_input_port()));
auto diagram = builder_.Build();
EXPECT_EQ(diagram->connection_map().size(), 0);
}
// A diagram of Gain->Source is has too few dest inputs.
TEST_F(DiagramBuilderSolePortsTest, TooFewDestInputs) {
EXPECT_THROW(builder_.Connect(*in1out1_, *out1_), std::exception);
}
// A diagram of Source->In2out1 is has too many dest inputs.
TEST_F(DiagramBuilderSolePortsTest, TooManyDestInputs) {
using std::exception;
EXPECT_THROW(builder_.Connect(*out1_, *in2out1_), std::exception);
// However, if all but one input port were deprecated, then it succeeds.
const_cast<InputPort<double>&>(in2out1_->get_input_port(1))
.set_deprecation("deprecated");
EXPECT_NO_THROW(builder_.Connect(*out1_, *in2out1_));
}
// A diagram of Sink->Gain is has too few src inputs.
TEST_F(DiagramBuilderSolePortsTest, TooFewSrcInputs) {
using std::exception;
EXPECT_THROW(builder_.Connect(*in1_, *in1out1_), std::exception);
}
// A diagram of Demux->Gain is has too many src inputs.
TEST_F(DiagramBuilderSolePortsTest, TooManySrcInputs) {
using std::exception;
EXPECT_THROW(builder_.Connect(*in1out2_, *in1out1_), std::exception);
// However, if all but one output port were deprecated, then it succeeds.
const_cast<OutputPort<double>&>(in1out2_->get_output_port(1))
.set_deprecation("deprecated");
EXPECT_NO_THROW(builder_.Connect(*in1out2_, *in1out1_));
}
// Test for GetSystems and GetMutableSystems.
GTEST_TEST(DiagramBuilderTest, GetMutableSystems) {
DiagramBuilder<double> builder;
auto adder1 = builder.AddNamedSystem<Adder>(
"adder1", 1 /* inputs */, 1 /* size */);
auto adder2 = builder.AddNamedSystem<Adder>(
"adder2", 1 /* inputs */, 1 /* size */);
EXPECT_EQ((std::vector<const System<double>*>{adder1, adder2}),
builder.GetSystems());
EXPECT_EQ((std::vector<System<double>*>{adder1, adder2}),
builder.GetMutableSystems());
}
// Test for the by-name suite of GetSystems functions.
GTEST_TEST(DiagramBuilderTest, GetByName) {
DiagramBuilder<double> builder;
auto adder = builder.AddNamedSystem<Adder>("adder", 1, 1);
auto pass = builder.AddNamedSystem<PassThrough>("pass", 1);
auto untemplated = builder.AddNamedSystem<UntemplatedSystem>("untemplated");
EXPECT_TRUE(builder.HasSubsystemNamed("adder"));
EXPECT_TRUE(builder.HasSubsystemNamed("pass"));
EXPECT_TRUE(builder.HasSubsystemNamed("untemplated"));
EXPECT_FALSE(builder.HasSubsystemNamed("no-such-name"));
// Plain by-name.
EXPECT_EQ(&builder.GetSubsystemByName("adder"), adder);
EXPECT_EQ(&builder.GetMutableSubsystemByName("pass"), pass);
EXPECT_EQ(&builder.GetMutableSubsystemByName("untemplated"), untemplated);
// Downcasting by name.
const Adder<double>& adder2 =
builder.GetDowncastSubsystemByName<Adder>("adder");
const PassThrough<double>& pass2 =
builder.GetDowncastSubsystemByName<PassThrough>("pass");
const UntemplatedSystem& untemplated2 =
builder.GetDowncastSubsystemByName<UntemplatedSystem>("untemplated");
EXPECT_EQ(&adder2, adder);
EXPECT_EQ(&pass2, pass);
EXPECT_EQ(&untemplated2, untemplated);
// Mutable downcasting by name.
Adder<double>& adder3 =
builder.GetMutableDowncastSubsystemByName<Adder>("adder");
PassThrough<double>& pass3 =
builder.GetMutableDowncastSubsystemByName<PassThrough>("pass");
UntemplatedSystem& untemplated3 =
builder.GetMutableDowncastSubsystemByName<UntemplatedSystem>(
"untemplated");
EXPECT_EQ(&adder3, adder);
EXPECT_EQ(&pass3, pass);
EXPECT_EQ(&untemplated3, untemplated);
// Error: no such name.
DRAKE_EXPECT_THROWS_MESSAGE(
builder.GetSubsystemByName("not_a_subsystem"),
".*not_a_subsystem.*");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.GetMutableSubsystemByName("not_a_subsystem"),
".*not_a_subsystem.*");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.GetDowncastSubsystemByName<Adder>("not_a_subsystem"),
".*not_a_subsystem.*");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.GetMutableDowncastSubsystemByName<Adder>("not_a_subsystem"),
".*not_a_subsystem.*");
// Error: wrong type.
DRAKE_EXPECT_THROWS_MESSAGE(
builder.GetDowncastSubsystemByName<Gain>("adder"),
".*cast.*Adder.*Gain.*");
DRAKE_EXPECT_THROWS_MESSAGE(
builder.GetMutableDowncastSubsystemByName<Gain>("adder"),
".*cast.*Adder.*Gain.*");
// Add a second system named "pass". We can still look up the "adder" but
// not the "pass" anymore
auto bonus_pass = builder.AddNamedSystem<PassThrough>("pass", 1);
EXPECT_EQ(&builder.GetSubsystemByName("adder"), adder);
EXPECT_TRUE(builder.HasSubsystemNamed("pass"));
DRAKE_EXPECT_THROWS_MESSAGE(
builder.GetMutableSubsystemByName("pass"),
".*multiple subsystems.*pass.*unique.*");
// Once the system is reset to use unique name, both lookups succeed.
bonus_pass->set_name("bonus_pass");
EXPECT_TRUE(builder.HasSubsystemNamed("bonus_pass"));
EXPECT_EQ(&builder.GetSubsystemByName("pass"), pass);
EXPECT_EQ(&builder.GetSubsystemByName("bonus_pass"), bonus_pass);
}
// Tests that the returned exported input / output port id matches the
// number of ExportInput() / ExportOutput() calls.
GTEST_TEST(DiagramBuilderTest, ExportInputOutputIndex) {
DiagramBuilder<double> builder;
auto adder1 = builder.AddNamedSystem<Adder>(
"adder1", 3 /* inputs */, 1 /* size */);
auto adder2 = builder.AddNamedSystem<Adder>(
"adder2", 1 /* inputs */, 1 /* size */);
EXPECT_EQ(builder.ExportInput(
adder1->get_input_port(0)), 0 /* exported input port id */);
EXPECT_EQ(builder.ExportInput(
adder1->get_input_port(1)), 1 /* exported input port id */);
EXPECT_EQ(builder.num_input_ports(), 2);
EXPECT_EQ(builder.num_output_ports(), 0);
EXPECT_EQ(builder.ExportOutput(
adder1->get_output_port()), 0 /* exported output port id */);
EXPECT_EQ(builder.ExportOutput(
adder2->get_output_port()), 1 /* exported output port id */);
EXPECT_EQ(builder.num_input_ports(), 2);
EXPECT_EQ(builder.num_output_ports(), 2);
}
class DtorTraceSystem final : public LeafSystem<double> {
public:
explicit DtorTraceSystem(int nonce) : nonce_(nonce) {}
~DtorTraceSystem() { destroyed_nonces().push_back(nonce_); }
static std::vector<int>& destroyed_nonces() {
static never_destroyed<std::vector<int>> nonces;
return nonces.access();
}
private:
int nonce_{};
};
// Tests the destruction order of DiagramBuilder.
GTEST_TEST(DiagramBuilderTest, DtorOrder_Builder) {
auto& nonces = DtorTraceSystem::destroyed_nonces();
nonces.clear();
auto dut = std::make_unique<DiagramBuilder<double>>();
dut->AddSystem<DtorTraceSystem>(1);
dut->AddSystem<DtorTraceSystem>(2);
EXPECT_EQ(nonces.size(), 0);
dut.reset();
EXPECT_EQ(nonces, (std::vector<int>{2, 1}));
}
// Tests the destruction order of Diagram.
GTEST_TEST(DiagramBuilderTest, DtorOrder_Built) {
auto& nonces = DtorTraceSystem::destroyed_nonces();
nonces.clear();
auto builder = std::make_unique<DiagramBuilder<double>>();
builder->AddSystem<DtorTraceSystem>(-1);
builder->AddSystem<DtorTraceSystem>(-2);
auto dut = builder->Build();
EXPECT_EQ(nonces.size(), 0);
dut.reset();
EXPECT_EQ(nonces, (std::vector<int>{-2, -1}));
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/system_constraint_test.cc | #include "drake/systems/framework/system_constraint.h"
#include <memory>
#include <stdexcept>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/systems/framework/system_symbolic_inspector.h"
#include "drake/systems/primitives/linear_system.h"
namespace drake {
namespace systems {
namespace {
using Eigen::Matrix2d;
using Eigen::MatrixXd;
using Eigen::Vector2d;
using Eigen::VectorXd;
// A hollow shell of a System.
class DummySystem final : public LeafSystem<double> {
public:
DummySystem() {}
};
GTEST_TEST(SystemConstraintBoundsTest, DefaultCtor) {
const SystemConstraintBounds dut;
EXPECT_EQ(dut.size(), 0);
EXPECT_TRUE(CompareMatrices(dut.lower(), VectorXd::Zero(0)));
EXPECT_TRUE(CompareMatrices(dut.upper(), VectorXd::Zero(0)));
}
GTEST_TEST(SystemConstraintBoundsTest, EqFactory) {
auto dut = SystemConstraintBounds::Equality(2);
EXPECT_EQ(dut.size(), 2);
EXPECT_EQ(dut.type(), SystemConstraintType::kEquality);
EXPECT_TRUE(CompareMatrices(dut.lower(), Vector2d::Zero()));
EXPECT_TRUE(CompareMatrices(dut.upper(), Vector2d::Zero()));
}
GTEST_TEST(SystemConstraintBoundsTest, EqCtor) {
const SystemConstraintBounds dut(Vector2d::Zero(), Vector2d::Zero());
EXPECT_EQ(dut.size(), 2);
EXPECT_EQ(dut.type(), SystemConstraintType::kEquality);
EXPECT_TRUE(CompareMatrices(dut.lower(), Vector2d::Zero()));
EXPECT_TRUE(CompareMatrices(dut.upper(), Vector2d::Zero()));
}
GTEST_TEST(SystemConstraintBoundsTest, EqNonzero) {
const Vector2d b = Vector2d::Constant(2.0);
// For now, we only allow b == 0; in the future, we might allow b != 0.
EXPECT_THROW(SystemConstraintBounds(b, b), std::exception);
}
GTEST_TEST(SystemConstraintBoundsTest, Lower) {
const double kInf = std::numeric_limits<double>::infinity();
const SystemConstraintBounds dut(Vector2d::Zero(), std::nullopt);
EXPECT_EQ(dut.size(), 2);
EXPECT_EQ(dut.type(), SystemConstraintType::kInequality);
EXPECT_TRUE(CompareMatrices(dut.lower(), Vector2d::Zero()));
EXPECT_TRUE(CompareMatrices(dut.upper(), Vector2d::Constant(kInf)));
}
GTEST_TEST(SystemConstraintBoundsTest, Upper) {
const double kInf = std::numeric_limits<double>::infinity();
const SystemConstraintBounds dut(std::nullopt, Vector2d::Constant(1.0));
EXPECT_EQ(dut.size(), 2);
EXPECT_EQ(dut.type(), SystemConstraintType::kInequality);
EXPECT_TRUE(CompareMatrices(dut.lower(), Vector2d::Constant(-kInf)));
EXPECT_TRUE(CompareMatrices(dut.upper(), Vector2d::Constant(1.0)));
}
GTEST_TEST(SystemConstraintBoundsTest, BadSizes) {
EXPECT_THROW(SystemConstraintBounds::Equality(-1), std::exception);
EXPECT_THROW(
SystemConstraintBounds(
Vector1d::Constant(1.0),
Vector2d::Constant(2.0)),
std::exception);
}
// Just a simple test to call each of the public methods.
GTEST_TEST(SystemConstraintTest, Basic) {
ContextConstraintCalc<double> calc = [](
const Context<double>& context, Eigen::VectorXd* value) {
*value = Vector1d(context.get_continuous_state_vector()[1]);
};
ContextConstraintCalc<double> calc2 = [](
const Context<double>& context, Eigen::VectorXd* value) {
*value =
Eigen::Vector2d(context.get_continuous_state_vector().CopyToVector());
};
Eigen::VectorXd value;
// Make a (linear) system just to make a valid context.
LinearSystem<double> system(Eigen::Matrix2d::Identity(),
Eigen::Vector2d::Zero(), Eigen::MatrixXd(0, 2),
Eigen::MatrixXd(0, 1));
auto context = system.CreateDefaultContext();
const double tol = 1e-6;
// Test equality constraint.
SystemConstraint<double> equality_constraint(
&system, calc, SystemConstraintBounds::Equality(1),
"equality constraint");
context->get_mutable_continuous_state_vector()[1] = 5.0;
equality_constraint.Calc(*context, &value);
EXPECT_EQ(value[0], 5.0);
EXPECT_TRUE(CompareMatrices(equality_constraint.lower_bound(), Vector1d(0)));
EXPECT_TRUE(CompareMatrices(equality_constraint.upper_bound(), Vector1d(0)));
EXPECT_FALSE(equality_constraint.CheckSatisfied(*context, tol));
context->get_mutable_continuous_state_vector()[1] = 0.0;
equality_constraint.Calc(*context, &value);
EXPECT_EQ(value[0], 0.0);
EXPECT_TRUE(equality_constraint.CheckSatisfied(*context, tol));
EXPECT_EQ(equality_constraint.size(), 1);
EXPECT_EQ(equality_constraint.description(), "equality constraint");
// Test inequality constraint.
SystemConstraint<double> inequality_constraint(
&system, calc2, { Eigen::Vector2d::Ones(), Eigen::Vector2d(4, 6) },
"inequality constraint");
EXPECT_TRUE(CompareMatrices(inequality_constraint.lower_bound(),
Eigen::Vector2d::Ones()));
EXPECT_TRUE(CompareMatrices(inequality_constraint.upper_bound(),
Eigen::Vector2d(4, 6)));
context->get_mutable_continuous_state_vector()[0] = 3.0;
context->get_mutable_continuous_state_vector()[1] = 5.0;
inequality_constraint.Calc(*context, &value);
EXPECT_EQ(value[0], 3.0);
EXPECT_EQ(value[1], 5.0);
EXPECT_TRUE(inequality_constraint.CheckSatisfied(*context, tol));
context->get_mutable_continuous_state_vector()[1] = -0.5;
inequality_constraint.Calc(*context, &value);
EXPECT_EQ(value[1], -0.5);
EXPECT_FALSE(inequality_constraint.CheckSatisfied(*context, tol));
EXPECT_EQ(inequality_constraint.size(), 2);
EXPECT_EQ(inequality_constraint.description(), "inequality constraint");
EXPECT_EQ(&inequality_constraint.get_system(), &system);
}
class WrongOrderSystem final : public LeafSystem<double> {
public:
WrongOrderSystem() {
this->DeclareEqualityConstraint([](const auto&, auto*) {}, 0, "dummy1");
this->AddExternalConstraint(ExternalSystemConstraint{});
this->DeclareEqualityConstraint([](const auto&, auto*) {}, 0, "dummy2");
}
};
// We should fail-fast if constraints are added in the wrong order.
GTEST_TEST(SystemConstraintTest, WrongOrder) {
DRAKE_EXPECT_THROWS_MESSAGE(
WrongOrderSystem{},
"System _ cannot add an internal constraint \\(named dummy2\\) after "
"an external constraint \\(named empty\\) has already been added");
}
// For a state x, constrains xc_dot = 0 and xd_{n+1} = 0.
// TODO(jwnimmer-tri) This cannot handle discrete state yet.
// TODO(jwnimmer-tri) Make this constraint public (and not testonly) -- it is
// quite commonly used.
ExternalSystemConstraint ZeroStateDerivativeConstraint(
const System<double>& shape) {
auto dummy_context = shape.AllocateContext();
// We don't handle discrete state yet, because to do so efficiently we'd
// need a method like System::EvalDiscreteVariableUpdates, but only the Calc
// flavor of that method currently exists.
DRAKE_DEMAND(dummy_context->num_discrete_state_groups() == 0);
const int n_xc = dummy_context->get_continuous_state_vector().size();
return ExternalSystemConstraint::MakeForAllScalars(
"xc_dot = 0 and xd_{n+1} = 0",
SystemConstraintBounds::Equality(n_xc),
[](const auto& system, const auto& context, auto* value) {
const auto& xc = system.EvalTimeDerivatives(context).get_vector();
*value = xc.CopyToVector();
});
}
// For a state x, constrains velocity(x) = 0. This can be useful to directly
// express decision variable bounds to a solver, even if an constraint on xcdot
// is already in effect.
// TODO(jwnimmer-tri) This cannot handle discrete state yet.
// TODO(jwnimmer-tri) Make this constraint public (and not testonly) -- it is
// quite commonly used.
ExternalSystemConstraint ZeroVelocityConstraint(
const System<double>& shape) {
auto dummy_context = shape.AllocateContext();
// We can't handle discrete state yet, because of #9171.
DRAKE_DEMAND(dummy_context->num_discrete_state_groups() == 0);
const int num_v = dummy_context->get_continuous_state().num_v();
return ExternalSystemConstraint::MakeForAllScalars(
"zero velocity", SystemConstraintBounds::Equality(num_v),
[](const auto& system, const auto& context, auto* value) {
*value = context.get_continuous_state().get_generalized_velocity()
.CopyToVector();
});
}
class ExternalSystemConstraintTest : public ::testing::Test {
protected:
// This system_ is a double integrator.
LinearSystem<double> system_{
(Matrix2d{} << 0.0, 1.0, 0.0, 0.0).finished(),
Vector2d(0.0, 1.0),
MatrixXd(0, 2),
MatrixXd(0, 1)};
};
// Acceptance test the symbolic form of a fixed-point constraint.
TEST_F(ExternalSystemConstraintTest, FixedPoint) {
// Add fixed-point constraints.
system_.AddExternalConstraint(ZeroStateDerivativeConstraint(system_));
system_.AddExternalConstraint(ZeroVelocityConstraint(system_));
// Check their symbolic form, thus proving that the constraints have
// been scalar-converted correctly.
auto symbolic = system_.ToSymbolic();
const SystemSymbolicInspector inspector(*symbolic);
ASSERT_EQ(inspector.constraints().size(), 2);
EXPECT_EQ(make_conjunction(inspector.constraints()).to_string(),
"((u0_0 == 0) and (xc1 == 0))");
// Confirm that the description was preserved through scalar conversion.
const auto& zero_vel = system_.get_constraint(SystemConstraintIndex{1});
EXPECT_EQ(zero_vel.description(), "zero velocity");
}
// Sanity check the public accessors.
TEST_F(ExternalSystemConstraintTest, Accessors) {
auto dut = ZeroVelocityConstraint(system_);
EXPECT_EQ(dut.description(), "zero velocity");
EXPECT_EQ(dut.bounds().type(), SystemConstraintType::kEquality);
EXPECT_TRUE(dut.get_calc<double>());
EXPECT_FALSE(dut.get_calc<float>());
}
// Check the double-only public constructor.
TEST_F(ExternalSystemConstraintTest, DoubleOnly) {
const DummySystem dummy_system;
auto dummy_context = dummy_system.CreateDefaultContext();
const ExternalSystemConstraint dut(
"desc", {std::nullopt, Vector2d::Constant(100.0)},
[&](const System<double>& system, const Context<double>& context,
VectorXd* value) {
EXPECT_EQ(&system, &dummy_system);
EXPECT_EQ(&context, dummy_context.get());
*value = Vector2d::Constant(22.0);
});
EXPECT_EQ(dut.description(), "desc");
EXPECT_EQ(dut.bounds().type(), SystemConstraintType::kInequality);
EXPECT_TRUE(dut.get_calc<double>());
EXPECT_FALSE(dut.get_calc<AutoDiffXd>());
EXPECT_FALSE(dut.get_calc<symbolic::Expression>());
VectorXd value;
dut.get_calc<double>()(dummy_system, *dummy_context, &value);
EXPECT_TRUE(CompareMatrices(value, Vector2d::Constant(22.0)));
}
// Check the non-symbolic factory function.
TEST_F(ExternalSystemConstraintTest, NonSymbolic) {
const auto& dut = ExternalSystemConstraint::MakeForNonsymbolicScalars(
"xcdot = 0", SystemConstraintBounds::Equality(2),
[](const auto& system, const auto& context, auto* value) {
const auto& xc = system.EvalTimeDerivatives(context).get_vector();
*value = xc.CopyToVector();
});
EXPECT_EQ(dut.description(), "xcdot = 0");
EXPECT_EQ(dut.bounds().type(), SystemConstraintType::kEquality);
EXPECT_TRUE(dut.get_calc<double>());
EXPECT_TRUE(dut.get_calc<AutoDiffXd>());
EXPECT_FALSE(dut.get_calc<symbolic::Expression>());
// Check that the generic lambda turned into a correct functor by calling it
// and checking the result, for double.
auto context_double = system_.CreateDefaultContext();
system_.get_input_port().FixValue(context_double.get(), VectorXd::Zero(1));
context_double->SetContinuousState((VectorXd(2) << 0.0, 22.0).finished());
VectorXd value_double;
dut.get_calc<double>()(system_, *context_double, &value_double);
EXPECT_TRUE(CompareMatrices(value_double, Vector2d(22.0, 0.0)));
// Check that the generic lambda turned into a correct functor by calling it
// and checking the result, for AutoDiffXd.
using T = AutoDiffXd;
auto system_autodiff = system_.ToAutoDiffXd();
auto context_autodiff = system_autodiff->CreateDefaultContext();
system_autodiff->get_input_port().FixValue(context_autodiff.get(),
VectorX<T>::Zero(1));
context_autodiff->SetContinuousState(
(VectorX<T>(2) << T{0.0}, T{22.0}).finished());
VectorX<T> value_autodiff;
dut.get_calc<T>()(
*system_autodiff, *context_autodiff, &value_autodiff);
EXPECT_EQ(value_autodiff[0].value(), 22.0);
EXPECT_EQ(value_autodiff[1].value(), 0.0);
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/vector_system_test.cc | #include "drake/systems/framework/vector_system.h"
#include <stdexcept>
#include <vector>
#include <Eigen/Dense>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/systems/framework/test_utilities/scalar_conversion.h"
#include "drake/systems/primitives/integrator.h"
namespace drake {
namespace systems {
namespace {
using Eigen::VectorXd;
// For all of the output / xdot / x[n+1] functions, the result is set to be
// either (1) equal to the input, when there is no declared state or (2) equal
// to the input plus the state, when there is declared state. Unlike most
// Systems, this System allows test code to configure its ports and state even
// beyond what the constructor does by default. For all of the Siso overrides,
// a call count is retained for tests to examine.
class TestVectorSystem : public VectorSystem<double> {
public:
static constexpr int kSize = 2;
TestVectorSystem() : VectorSystem<double>(kSize, kSize) {}
// Let test code abuse these by making them public.
using VectorSystem<double>::DeclareAbstractState;
using VectorSystem<double>::DeclareContinuousState;
using VectorSystem<double>::DeclareDiscreteState;
using VectorSystem<double>::DeclareAbstractInputPort;
using VectorSystem<double>::DeclareAbstractOutputPort;
using VectorSystem<double>::EvalVectorInput;
using VectorSystem<double>::GetVectorState;
// VectorSystem override.
// N.B. This method signature might be used by many downstream projects.
// Change it only with good reason and with a deprecation period first.
void DoCalcVectorOutput(const Context<double>& context,
const Eigen::VectorBlock<const VectorXd>& input,
const Eigen::VectorBlock<const VectorXd>& state,
Eigen::VectorBlock<VectorXd>* output) const override {
++output_count_;
last_context_ = &context;
if (state.size() == 0) {
*output = input;
} else {
*output = input + state;
}
}
// VectorSystem override.
// N.B. This method signature might be used by many downstream projects.
// Change it only with good reason and with a deprecation period first.
void DoCalcVectorTimeDerivatives(
const Context<double>& context,
const Eigen::VectorBlock<const VectorXd>& input,
const Eigen::VectorBlock<const VectorXd>& state,
Eigen::VectorBlock<VectorXd>* derivatives) const override {
++time_derivatives_count_;
last_context_ = &context;
if (state.size() == 0) {
*derivatives = input;
} else {
*derivatives = input + state;
}
}
// VectorSystem override.
// N.B. This method signature might be used by many downstream projects.
// Change it only with good reason and with a deprecation period first.
void DoCalcVectorDiscreteVariableUpdates(
const Context<double>& context,
const Eigen::VectorBlock<const VectorXd>& input,
const Eigen::VectorBlock<const VectorXd>& state,
Eigen::VectorBlock<VectorXd>* next_state) const override {
++discrete_variable_updates_count_;
last_context_ = &context;
if (state.size() == 0) {
*next_state = input;
} else {
*next_state = input + state;
}
}
// Testing accessors.
const Context<double>* get_last_context() const { return last_context_; }
int get_output_count() const { return output_count_; }
int get_time_derivatives_count() const { return time_derivatives_count_; }
int get_discrete_variable_updates_count() const {
return discrete_variable_updates_count_;
}
private:
mutable const Context<double>* last_context_{nullptr};
mutable int output_count_{0};
mutable int time_derivatives_count_{0};
mutable int discrete_variable_updates_count_{0};
};
class VectorSystemTest : public ::testing::Test {
// Not yet needed, but placeholder for future common code.
};
// The system has an appropriate topology.
TEST_F(VectorSystemTest, Topology) {
// The device-under-test ("dut").
TestVectorSystem dut;
// One input port.
ASSERT_EQ(dut.num_input_ports(), 1);
const InputPort<double>& input_port = dut.get_input_port();
EXPECT_EQ(input_port.get_data_type(), kVectorValued);
EXPECT_EQ(input_port.size(), TestVectorSystem::kSize);
// One output port.
ASSERT_EQ(dut.num_output_ports(), 1);
const OutputPort<double>& output_port = dut.get_output_port();
EXPECT_EQ(output_port.get_data_type(), kVectorValued);
EXPECT_EQ(output_port.size(), TestVectorSystem::kSize);
// No state by default ...
auto context = dut.CreateDefaultContext();
ASSERT_EQ(context->num_input_ports(), 1);
EXPECT_TRUE(context->is_stateless());
// ... but subclasses may declare it.
dut.DeclareContinuousState(TestVectorSystem::kSize);
context = dut.CreateDefaultContext();
EXPECT_FALSE(context->is_stateless());
}
// Subclasses that violate the VectorSystem premise fail-fast.
TEST_F(VectorSystemTest, TopologyFailFast) {
{ // A second input.
TestVectorSystem dut;
DRAKE_EXPECT_NO_THROW(dut.CreateDefaultContext());
dut.DeclareAbstractInputPort(kUseDefaultName, Value<std::string>{});
EXPECT_THROW(dut.CreateDefaultContext(), std::exception);
}
{ // A second output.
TestVectorSystem dut;
DRAKE_EXPECT_NO_THROW(dut.CreateDefaultContext());
dut.DeclareAbstractOutputPort(
kUseDefaultName,
[]() { return AbstractValue::Make<int>(); }, // Dummies.
[](const ContextBase&, AbstractValue*) {});
EXPECT_THROW(dut.CreateDefaultContext(), std::exception);
}
{ // Abstract state.
// TODO(jwnimmer-tri) Conceptually, allowing abstract state could be
// consistent with the VectorSystem contract. However, if we widened the
// VectorSystem contract to support that, then we would have add code to
// fail-fast if the subclass neglected to override the unrestricted
// updates API. That doesn't seem worth it yet, but if we ever want
// abstract state in VectorSystem, then it would be okay to write the
// code and tests to support it.
TestVectorSystem dut;
DRAKE_EXPECT_NO_THROW(dut.CreateDefaultContext());
dut.DeclareAbstractState(Value<double>(1.0));
EXPECT_THROW(dut.CreateDefaultContext(), std::exception);
}
{ // More than one discrete state group.
TestVectorSystem dut;
dut.DeclareDiscreteState(TestVectorSystem::kSize);
DRAKE_EXPECT_NO_THROW(dut.CreateDefaultContext());
dut.DeclareDiscreteState(TestVectorSystem::kSize);
EXPECT_THROW(dut.CreateDefaultContext(), std::exception);
}
{ // Both continuous and discrete state.
TestVectorSystem dut;
dut.DeclareContinuousState(1);
DRAKE_EXPECT_NO_THROW(dut.CreateDefaultContext());
dut.DeclareDiscreteState(TestVectorSystem::kSize);
EXPECT_THROW(dut.CreateDefaultContext(), std::exception);
}
}
// Forwarding of CalcOutput with no state.
TEST_F(VectorSystemTest, OutputStateless) {
TestVectorSystem dut;
auto context = dut.CreateDefaultContext();
auto& output_port = dut.get_output_port();
dut.get_input_port(0).FixValue(context.get(), Eigen::Vector2d(1.0, 2.0));
const auto& output = output_port.Eval(*context);
EXPECT_EQ(dut.get_output_count(), 1);
EXPECT_EQ(dut.get_last_context(), context.get());
EXPECT_EQ(output[0], 1.0);
EXPECT_EQ(output[1], 2.0);
const auto& input = dut.EvalVectorInput(*context);
EXPECT_EQ(input.size(), 2);
EXPECT_EQ(input[0], 1.0);
EXPECT_EQ(input[1], 2.0);
const auto& state = dut.GetVectorState(*context);
EXPECT_EQ(state.size(), 0);
}
// Forwarding of CalcOutput with continuous state.
TEST_F(VectorSystemTest, OutputContinuous) {
TestVectorSystem dut;
dut.DeclareContinuousState(TestVectorSystem::kSize);
auto context = dut.CreateDefaultContext();
auto& output_port = dut.get_output_port();
dut.get_input_port(0).FixValue(context.get(), Eigen::Vector2d(1.0, 2.0));
context->get_mutable_continuous_state_vector().SetFromVector(
Eigen::Vector2d::Ones());
const auto& output = output_port.Eval(*context);
EXPECT_EQ(dut.get_output_count(), 1);
EXPECT_EQ(dut.get_last_context(), context.get());
EXPECT_EQ(output[0], 2.0);
EXPECT_EQ(output[1], 3.0);
const auto& state = dut.GetVectorState(*context);
EXPECT_EQ(state.size(), 2);
EXPECT_EQ(state[0], 1.0);
EXPECT_EQ(state[1], 1.0);
}
// Forwarding of CalcOutput with discrete state.
TEST_F(VectorSystemTest, OutputDiscrete) {
TestVectorSystem dut;
dut.DeclareDiscreteState(TestVectorSystem::kSize);
auto context = dut.CreateDefaultContext();
auto& output_port = dut.get_output_port();
dut.get_input_port(0).FixValue(context.get(), Eigen::Vector2d(1.0, 2.0));
context->SetDiscreteState(0, Eigen::Vector2d::Ones());
const auto& output = output_port.Eval(*context);
EXPECT_EQ(dut.get_output_count(), 1);
EXPECT_EQ(dut.get_last_context(), context.get());
EXPECT_EQ(output[0], 2.0);
EXPECT_EQ(output[1], 3.0);
// Nothing else weird happened.
EXPECT_EQ(dut.get_discrete_variable_updates_count(), 0);
EXPECT_EQ(dut.get_time_derivatives_count(), 0);
const auto& state = dut.GetVectorState(*context);
EXPECT_EQ(state.size(), 2);
EXPECT_EQ(state[0], 1.0);
EXPECT_EQ(state[1], 1.0);
}
// Forwarding of CalcTimeDerivatives works.
TEST_F(VectorSystemTest, TimeDerivatives) {
TestVectorSystem dut;
auto context = dut.CreateDefaultContext();
std::unique_ptr<ContinuousState<double>> derivatives =
dut.AllocateTimeDerivatives();
// There's no state declared yet, so the VectorSystem base shouldn't call our
// DUT.
dut.CalcTimeDerivatives(*context, derivatives.get());
EXPECT_EQ(dut.get_time_derivatives_count(), 0);
// Now we have state, so the VectorSystem base should call our DUT.
dut.DeclareContinuousState(TestVectorSystem::kSize);
context = dut.CreateDefaultContext();
dut.get_input_port(0).FixValue(context.get(), Eigen::Vector2d(1.0, 2.0));
context->get_mutable_continuous_state_vector().SetFromVector(
Eigen::Vector2d::Ones());
derivatives = dut.AllocateTimeDerivatives();
dut.CalcTimeDerivatives(*context, derivatives.get());
EXPECT_EQ(dut.get_last_context(), context.get());
EXPECT_EQ(dut.get_time_derivatives_count(), 1);
EXPECT_EQ(derivatives->get_vector()[0], 2.0);
EXPECT_EQ(derivatives->get_vector()[1], 3.0);
// Nothing else weird happened.
EXPECT_EQ(dut.get_discrete_variable_updates_count(), 0);
EXPECT_EQ(dut.get_output_count(), 0);
}
// Forwarding of CalcForcedDiscreteVariableUpdate works.
TEST_F(VectorSystemTest, DiscreteVariableUpdate) {
TestVectorSystem dut;
auto context = dut.CreateDefaultContext();
auto discrete_updates = dut.AllocateDiscreteVariables();
// There's no state declared yet, so the VectorSystem base shouldn't call our
// DUT.
dut.CalcForcedDiscreteVariableUpdate(*context, discrete_updates.get());
EXPECT_EQ(dut.get_discrete_variable_updates_count(), 0);
// Now we have state, so the VectorSystem base should call our DUT.
dut.DeclareDiscreteState(TestVectorSystem::kSize);
context = dut.CreateDefaultContext();
dut.get_input_port(0).FixValue(context.get(), Eigen::Vector2d(1.0, 2.0));
context->SetDiscreteState(0, Eigen::Vector2d::Ones());
discrete_updates = dut.AllocateDiscreteVariables();
dut.CalcForcedDiscreteVariableUpdate(*context, discrete_updates.get());
EXPECT_EQ(dut.get_last_context(), context.get());
EXPECT_EQ(dut.get_discrete_variable_updates_count(), 1);
EXPECT_EQ(discrete_updates->get_vector(0)[0], 2.0);
EXPECT_EQ(discrete_updates->get_vector(0)[1], 3.0);
// Nothing else weird happened.
EXPECT_EQ(dut.get_time_derivatives_count(), 0);
EXPECT_EQ(dut.get_output_count(), 0);
}
class NoFeedthroughContinuousTimeSystem : public VectorSystem<double> {
public:
NoFeedthroughContinuousTimeSystem() : VectorSystem<double>(1, 1, false) {
this->DeclareContinuousState(1);
}
private:
void DoCalcVectorOutput(
const drake::systems::Context<double>& context,
const Eigen::VectorBlock<const Eigen::VectorXd>& input,
const Eigen::VectorBlock<const Eigen::VectorXd>& state,
Eigen::VectorBlock<Eigen::VectorXd>* output) const override {
EXPECT_EQ(input.size(), 0);
*output = state;
}
};
class NoInputContinuousTimeSystem : public VectorSystem<double> {
public:
NoInputContinuousTimeSystem() : VectorSystem<double>(0, 1) {
this->DeclareContinuousState(1);
}
// Let test code abuse this by making it public.
using VectorSystem<double>::EvalVectorInput;
private:
virtual void DoCalcVectorTimeDerivatives(
const drake::systems::Context<double>& context,
const Eigen::VectorBlock<const Eigen::VectorXd>& input,
const Eigen::VectorBlock<const Eigen::VectorXd>& state,
Eigen::VectorBlock<Eigen::VectorXd>* derivatives) const {
*derivatives = -state;
}
virtual void DoCalcVectorOutput(
const drake::systems::Context<double>& context,
const Eigen::VectorBlock<const Eigen::VectorXd>& input,
const Eigen::VectorBlock<const Eigen::VectorXd>& state,
Eigen::VectorBlock<Eigen::VectorXd>* output) const {
*output = state;
}
};
// Input is not provided to DoCalcOutput when non-direct-feedthrough.
TEST_F(VectorSystemTest, NoFeedthroughContinuousTimeSystemTest) {
NoFeedthroughContinuousTimeSystem dut;
// The non-connected input is never evaluated.
auto context = dut.CreateDefaultContext();
const auto& output = dut.get_output_port();
EXPECT_EQ(output.Eval(*context)[0], 0.0);
}
// Symbolic analysis should be able to determine that the system is not direct
// feedthrough. (This is of special concern to VectorSystem, because it must
// be precise about when it evaluates its inputs.)
TEST_F(VectorSystemTest, ImplicitlyNoFeedthroughTest) {
static_assert(
std::is_base_of_v<VectorSystem<double>, Integrator<double>>,
"This test assumes that Integrator is implemented in terms of "
"VectorSystem; if that changes, copy its old implementation here "
"so that this test is unchanged.");
const Integrator<double> dut(1);
EXPECT_FALSE(dut.HasAnyDirectFeedthrough());
// The non-connected input is never evaluated.
auto context = dut.CreateDefaultContext();
const auto& output = dut.get_output_port();
EXPECT_EQ(output.Eval(*context)[0], 0.0);
}
// Derivatives and Output methods still work when input size is zero.
TEST_F(VectorSystemTest, NoInputContinuousTimeSystemTest) {
NoInputContinuousTimeSystem dut;
auto context = dut.CreateDefaultContext();
context->SetContinuousState(Vector1d::Ones());
// Ensure that time derivatives get calculated correctly.
std::unique_ptr<ContinuousState<double>> derivatives =
dut.AllocateTimeDerivatives();
dut.CalcTimeDerivatives(*context, derivatives.get());
EXPECT_EQ(derivatives->get_vector()[0], -1.0);
const auto& output = dut.get_output_port();
EXPECT_EQ(output.Eval(*context)[0], 1.0);
const auto& input = dut.EvalVectorInput(*context);
EXPECT_EQ(input.size(), 0);
}
class NoInputNoOutputDiscreteTimeSystem : public VectorSystem<double> {
public:
NoInputNoOutputDiscreteTimeSystem() : VectorSystem<double>(0, 0) {
this->DeclarePeriodicDiscreteUpdate(1.0, 0.0);
this->DeclareDiscreteState(1);
}
private:
// x[n+1] = x[n]^3
virtual void DoCalcVectorDiscreteVariableUpdates(
const drake::systems::Context<double>& context,
const Eigen::VectorBlock<const Eigen::VectorXd>& input,
const Eigen::VectorBlock<const Eigen::VectorXd>& state,
Eigen::VectorBlock<Eigen::VectorXd>* next_state) const {
(*next_state)[0] = std::pow(state[0], 3.0);
}
};
// Discrete updates still work when input size is zero.
// No output ports are created when the output size is zero.
TEST_F(VectorSystemTest, NoInputNoOutputDiscreteTimeSystemTest) {
NoInputNoOutputDiscreteTimeSystem dut;
auto context = dut.CreateDefaultContext();
context->get_mutable_discrete_state().get_mutable_vector().SetFromVector(
Vector1d::Constant(2.0));
auto discrete_updates = dut.AllocateDiscreteVariables();
dut.CalcForcedDiscreteVariableUpdate(*context, discrete_updates.get());
EXPECT_EQ(discrete_updates->get_vector(0)[0], 8.0);
EXPECT_EQ(dut.num_output_ports(), 0);
}
/// A system that can use any scalar type: AutoDiff, symbolic form, etc.
template <typename T>
class OpenScalarTypeSystem : public VectorSystem<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(OpenScalarTypeSystem);
explicit OpenScalarTypeSystem(int some_number)
: VectorSystem<T>(SystemTypeTag<OpenScalarTypeSystem>{}, 1, 1),
some_number_(some_number) {}
// Scalar-converting copy constructor.
template <typename U>
explicit OpenScalarTypeSystem(const OpenScalarTypeSystem<U>& other)
: OpenScalarTypeSystem<T>(other.some_number_) {}
int get_some_number() const { return some_number_; }
private:
// Allow different specializations to access each other's private data.
template <typename> friend class OpenScalarTypeSystem;
const int some_number_{};
};
TEST_F(VectorSystemTest, ToAutoDiffXdTest) {
// The member field remains intact.
const OpenScalarTypeSystem<double> dut{22};
EXPECT_TRUE(is_autodiffxd_convertible(dut, [](const auto& converted) {
EXPECT_EQ(converted.get_some_number(), 22);
}));
}
TEST_F(VectorSystemTest, ToSymbolicTest) {
// The member field remains intact.
const OpenScalarTypeSystem<double> dut{22};
EXPECT_TRUE(is_symbolic_convertible(dut, [](const auto& converted) {
EXPECT_EQ(converted.get_some_number(), 22);
}));
}
/// A system that passes a custom SystemScalarConverter object to VectorSystem,
/// rather than a SystemTypeTag.
template <typename T>
class DirectScalarTypeConversionSystem : public VectorSystem<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DirectScalarTypeConversionSystem);
DirectScalarTypeConversionSystem()
: VectorSystem<T>(
SystemTypeTag<DirectScalarTypeConversionSystem>(), 0, 0) {
// This will fail at compile-time if T is ever symbolic::Expression.
const T neg_one = test::copysign_int_to_non_symbolic_scalar(-1, T{1.0});
DRAKE_DEMAND(neg_one == T{-1.0});
}
explicit DirectScalarTypeConversionSystem(
const DirectScalarTypeConversionSystem<double>&, int dummy = 0)
: DirectScalarTypeConversionSystem<T>() {}
};
} // namespace
// Only support double => AutoDiffXd.
namespace scalar_conversion {
template <> struct Traits<DirectScalarTypeConversionSystem> {
template <typename T, typename U>
using supported = typename std::bool_constant<
std::is_same_v<U, double> && !std::is_same_v<T, symbolic::Expression>>;
};
} // namespace scalar_conversion
namespace {
TEST_F(VectorSystemTest, DirectToAutoDiffXdTest) {
DirectScalarTypeConversionSystem<double> dut;
// Convert to AutoDiffXd.
EXPECT_TRUE(is_autodiffxd_convertible(dut));
// Convert to Symbolic (expected fail).
EXPECT_EQ(dut.ToSymbolicMaybe(), nullptr);
}
// This system declares an output and continuous state, but does not define
// the required methods.
class MissingMethodsContinuousTimeSystem : public VectorSystem<double> {
public:
MissingMethodsContinuousTimeSystem() : VectorSystem<double>(0, 1) {
this->DeclareContinuousState(1);
}
};
TEST_F(VectorSystemTest, MissingMethodsContinuousTimeSystemTest) {
MissingMethodsContinuousTimeSystem dut;
auto context = dut.CreateDefaultContext();
std::unique_ptr<ContinuousState<double>> derivatives =
dut.AllocateTimeDerivatives();
DRAKE_EXPECT_THROWS_MESSAGE(
dut.CalcTimeDerivatives(*context, derivatives.get()),
".*TimeDerivatives.*derivatives->size.. == 0.*failed.*");
const auto& output = dut.get_output_port();
DRAKE_EXPECT_THROWS_MESSAGE(
output.Eval(*context),
".*Output.*'output->size.. == 0.*failed.*");
}
// This system declares an output and discrete state, but does not define
// the required methods.
class MissingMethodsDiscreteTimeSystem : public VectorSystem<double> {
public:
MissingMethodsDiscreteTimeSystem() : VectorSystem<double>(0, 1) {
this->DeclarePeriodicDiscreteUpdate(1.0, 0.0);
this->DeclareDiscreteState(1);
}
};
TEST_F(VectorSystemTest, MissingMethodsDiscreteTimeSystemTest) {
MissingMethodsDiscreteTimeSystem dut;
auto context = dut.CreateDefaultContext();
context->get_mutable_discrete_state().get_mutable_vector().SetFromVector(
Vector1d::Constant(2.0));
auto discrete_updates = dut.AllocateDiscreteVariables();
DRAKE_EXPECT_THROWS_MESSAGE(
dut.CalcForcedDiscreteVariableUpdate(*context, discrete_updates.get()),
".*DiscreteVariableUpdates.*next_state->size.. == 0.*failed.*");
const auto& output = dut.get_output_port();
DRAKE_EXPECT_THROWS_MESSAGE(
output.Eval(*context),
".*Output.*'output->size.. == 0.*failed.*");
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/leaf_system_deprecation_test.cc | #include <gtest/gtest.h>
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace systems {
// This is used for friendship, so can't be anonymous.
class LeafSystemDeprecationTest : public ::testing::Test {
protected:
class PortDeprecationSystem : public LeafSystem<double> {
public:
using LeafSystem::DeclareVectorInputPort;
using LeafSystem::DeclareVectorOutputPort;
using LeafSystem::DeprecateInputPort;
using LeafSystem::DeprecateOutputPort;
};
InputPort<double>& DeclareDeprecatedInput(const std::string& message = "") {
auto& result = dut_.DeclareVectorInputPort(kUseDefaultName, 1);
dut_.DeprecateInputPort(result, message);
return result;
}
OutputPort<double>& DeclareDeprecatedOutput(const std::string& message = "") {
auto& result = dut_.DeclareVectorOutputPort(
kUseDefaultName, 1, noop_calc_, {SystemBase::all_input_ports_ticket()});
dut_.DeprecateOutputPort(result, message);
return result;
}
bool has_warned(const PortBase& port) const {
using internal::PortBaseAttorney;
PortBase& mutable_port = const_cast<PortBase&>(port);
return PortBaseAttorney::deprecation_already_warned(&mutable_port)->load();
}
PortDeprecationSystem dut_;
const LeafOutputPort<double>::CalcVectorCallback noop_calc_ =
[](const Context<double>&, BasicVector<double>*) {};
};
namespace {
// ======== Positive test cases: we want these to generate warnings ========
// Give a deprecation message (or not) and make sure nothing crashes.
// You can manually look at the test's output to see what it looks like.
TEST_F(LeafSystemDeprecationTest, Messages) {
// Use default messages.
EXPECT_NO_THROW(DeclareDeprecatedInput());
EXPECT_NO_THROW(DeclareDeprecatedOutput());
// Use custom messages.
EXPECT_NO_THROW(DeclareDeprecatedInput("this string gets logged"));
EXPECT_NO_THROW(DeclareDeprecatedOutput("this string gets logged, too"));
// Log the warnings.
EXPECT_NO_THROW(dut_.get_input_port(0));
EXPECT_NO_THROW(dut_.get_input_port(1));
EXPECT_NO_THROW(dut_.get_output_port(0));
EXPECT_NO_THROW(dut_.get_output_port(1));
}
// Accessing input by index triggers the message.
TEST_F(LeafSystemDeprecationTest, InputByIndex) {
auto& port = DeclareDeprecatedInput();
EXPECT_EQ(has_warned(port), false);
dut_.get_input_port(0);
EXPECT_EQ(has_warned(port), true);
}
// Accessing base input by index triggers the message.
TEST_F(LeafSystemDeprecationTest, BaseInputByIndex) {
auto& port = DeclareDeprecatedInput();
EXPECT_EQ(has_warned(port), false);
dut_.get_input_port_base(InputPortIndex{0});
EXPECT_EQ(has_warned(port), true);
}
// Accessing input ticket by index triggers the message.
TEST_F(LeafSystemDeprecationTest, TicketInputByIndex) {
auto& port = DeclareDeprecatedInput();
EXPECT_EQ(has_warned(port), false);
dut_.input_port_ticket(InputPortIndex{0});
EXPECT_EQ(has_warned(port), true);
}
// Accessing output by index triggers the message.
TEST_F(LeafSystemDeprecationTest, OutputByIndex) {
auto& port = DeclareDeprecatedOutput();
EXPECT_EQ(has_warned(port), false);
dut_.get_output_port(0);
EXPECT_EQ(has_warned(port), true);
}
// Accessing base output by index triggers the message.
TEST_F(LeafSystemDeprecationTest, BaseOutputByIndex) {
auto& port = DeclareDeprecatedOutput();
EXPECT_EQ(has_warned(port), false);
dut_.get_output_port_base(OutputPortIndex{0});
EXPECT_EQ(has_warned(port), true);
}
// Accessing input by name triggers the message.
TEST_F(LeafSystemDeprecationTest, InputByName) {
auto& port = DeclareDeprecatedInput();
EXPECT_EQ(has_warned(port), false);
dut_.GetInputPort("u0");
EXPECT_EQ(has_warned(port), true);
}
// Checking for input by name triggers the message.
TEST_F(LeafSystemDeprecationTest, HasInputByName) {
auto& port = DeclareDeprecatedInput();
EXPECT_EQ(has_warned(port), false);
dut_.HasInputPort("u0");
EXPECT_EQ(has_warned(port), true);
}
// Accessing output by name triggers the message.
TEST_F(LeafSystemDeprecationTest, OutputByName) {
auto& port = DeclareDeprecatedOutput();
EXPECT_EQ(has_warned(port), false);
dut_.GetOutputPort("y0");
EXPECT_EQ(has_warned(port), true);
}
// Checking for output by name triggers the message.
TEST_F(LeafSystemDeprecationTest, HasOutputByName) {
auto& port = DeclareDeprecatedOutput();
EXPECT_EQ(has_warned(port), false);
dut_.HasOutputPort("y0");
EXPECT_EQ(has_warned(port), true);
}
// Evaluating the input (using the dispreferred SystemBase function) triggers
// the message.
TEST_F(LeafSystemDeprecationTest, InputEval) {
auto& port = DeclareDeprecatedInput();
auto context = dut_.CreateDefaultContext();
EXPECT_EQ(has_warned(port), false);
dut_.EvalAbstractInput(*context, 0);
EXPECT_EQ(has_warned(port), true);
}
// ======== Negative test cases: we want these to NOT generate warnings ========
// Non-deprecated input ports don't trigger the message.
TEST_F(LeafSystemDeprecationTest, OtherInputNoSpurious) {
auto& in0 = DeclareDeprecatedInput();
auto& in1 = dut_.DeclareVectorInputPort("ok", 1);
EXPECT_EQ(has_warned(in0), false);
EXPECT_EQ(has_warned(in1), false);
dut_.HasInputPort("ok");
dut_.GetInputPort("ok");
EXPECT_EQ(has_warned(in0), false);
EXPECT_EQ(has_warned(in1), false);
}
// Non-deprecated output ports don't trigger the message.
TEST_F(LeafSystemDeprecationTest, OtherOutputNoSpurious) {
auto& out0 = DeclareDeprecatedOutput();
auto& out1 = dut_.DeclareVectorOutputPort("ok", 1, noop_calc_);
EXPECT_EQ(has_warned(out0), false);
EXPECT_EQ(has_warned(out1), false);
dut_.HasOutputPort("ok");
dut_.GetOutputPort("ok");
EXPECT_EQ(has_warned(out0), false);
EXPECT_EQ(has_warned(out1), false);
}
// Multiple inputs don't trigger the message when checking for duplicate names.
TEST_F(LeafSystemDeprecationTest, HeterogeneousInputNoSpurious) {
auto& port0 = DeclareDeprecatedInput();
auto& port1 = DeclareDeprecatedInput();
EXPECT_EQ(has_warned(port0), false);
EXPECT_EQ(has_warned(port1), false);
}
// Multiple outputs don't trigger the message when checking for duplicate names.
TEST_F(LeafSystemDeprecationTest, HeterogeneousOutputNoSpurious) {
auto& port0 = DeclareDeprecatedOutput();
auto& port1 = DeclareDeprecatedOutput();
EXPECT_EQ(has_warned(port0), false);
EXPECT_EQ(has_warned(port1), false);
}
// Feedthrough calculations don't trigger the message.
TEST_F(LeafSystemDeprecationTest, FeedthroughNoSpurious) {
auto& in0 = DeclareDeprecatedInput();
auto& out0 = DeclareDeprecatedOutput();
dut_.GetDirectFeedthroughs();
EXPECT_EQ(has_warned(in0), false);
EXPECT_EQ(has_warned(out0), false);
}
// Fixed input port allocation doesn't trigger the message.
TEST_F(LeafSystemDeprecationTest, FixedAllocateNoSpurious) {
auto& in0 = DeclareDeprecatedInput();
auto context = dut_.CreateDefaultContext();
dut_.AllocateFixedInputs(context.get());
EXPECT_EQ(has_warned(in0), false);
}
// Fixed input port bulk setting doesn't trigger the message.
TEST_F(LeafSystemDeprecationTest, FixedFromNoSpurious) {
PortDeprecationSystem other;
auto& other_in = other.DeclareVectorInputPort("ok", 1);
auto other_context = other.CreateDefaultContext();
other.get_input_port().FixValue(
other_context.get(), Eigen::VectorXd::Constant(1, 22.0));
auto& dut_in = DeclareDeprecatedInput();
auto dut_context = dut_.CreateDefaultContext();
dut_.FixInputPortsFrom(other, *other_context, dut_context.get());
EXPECT_EQ(has_warned(other_in), false);
EXPECT_EQ(has_warned(dut_in), false);
}
// Bulk output calculation doesn't trigger the message.
TEST_F(LeafSystemDeprecationTest, CalcOutputNoSpurious) {
auto& port = DeclareDeprecatedOutput();
auto context = dut_.CreateDefaultContext();
auto output = dut_.AllocateOutput();
dut_.CalcOutput(*context, output.get());
EXPECT_EQ(has_warned(port), false);
}
TEST_F(LeafSystemDeprecationTest, GraphvizNoSpurious) {
auto& port = DeclareDeprecatedOutput();
dut_.GetGraphvizString();
EXPECT_EQ(has_warned(port), false);
}
// ======== Acceptance test ========
// Illustrates how to use the deprecation mechanism in practice. We have a
// PassThrough system where we've decided to add a "_new" suffix to port names.
class SillyPassThrough : public LeafSystem<double> {
public:
SillyPassThrough() {
// These are the non-deprecated ports.
input_new_ = &this->DeclareVectorInputPort("input_new", 1);
output_new_ = &this->DeclareVectorOutputPort(
"output_new", 1, &SillyPassThrough::CalcOutput);
// These are the deprecated ports. For the output port, we'll use the same
// CalcOutput function as the non-deprecated port. (Another option would be
// to have the deprecated port calculation function call Eval on the non-
// deprecated port and copy the result; that might be more appropriate in
// case the computation was too expensive to risk doing twice.)
const std::string message = "use the ports with suffix '_new'";
input_old_ = &this->DeclareVectorInputPort("input", 1);
output_old_ = &this->DeclareVectorOutputPort(
"output", 1, &SillyPassThrough::CalcOutput);
this->DeprecateInputPort(*input_old_, message);
this->DeprecateOutputPort(*output_old_, message);
}
void CalcOutput(const Context<double>& context,
BasicVector<double>* output) const {
const bool has_old = input_old_->HasValue(context);
const bool has_new = input_new_->HasValue(context);
if (has_old && has_new) {
throw std::runtime_error("Don't connect both input ports!");
}
const Eigen::VectorXd& input =
(has_old ? *input_old_ : *input_new_).Eval(context);
output->SetFromVector(input);
}
private:
const InputPort<double>* input_new_{};
const InputPort<double>* input_old_{};
const OutputPort<double>* output_new_{};
const OutputPort<double>* output_old_{};
};
GTEST_TEST(LeafSystemDeprecationAcceptanceTest, Demo) {
SillyPassThrough dut;
auto context = dut.CreateDefaultContext();
// The call to GetInputPort will log a warning.
const Eigen::VectorXd u = Eigen::VectorXd::Constant(1, 22.0);
dut.GetInputPort("input").FixValue(context.get(), u);
// The call to GetOutputPort will log a warning.
EXPECT_EQ(dut.GetOutputPort("output").Eval(*context), u);
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/system_base_test.cc | #include "drake/systems/framework/system_base.h"
#include <memory>
#include <string>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/common/test_utilities/expect_throws_message.h"
// TODO(sherm1) As SystemBase gains more functionality, move type-agnostic
// tests here from {system, diagram, leaf}_test.cc.
// Cache entry methods are tested in cache_entry_test.cc.
namespace drake {
namespace systems {
// Don't want anonymous here because the type name test would then depend on
// exactly how anonymous namespaces are rendered by NiceTypeName, which is
// a "don't care" here.
namespace system_base_test_internal {
// A minimal concrete ContextBase object suitable for some simple tests.
// Objects of this class are created with no system id.
class MyContextBase final : public ContextBase {
public:
MyContextBase() = default;
MyContextBase(const MyContextBase&) = default;
private:
std::unique_ptr<ContextBase> DoCloneWithoutPointers() const final {
return std::make_unique<MyContextBase>(*this);
}
};
// A minimal concrete SystemBase object suitable for some simple tests.
class MySystemBase final : public SystemBase {
public:
MySystemBase() {}
private:
std::unique_ptr<ContextBase> DoAllocateContext() const final {
auto context = std::make_unique<MyContextBase>();
InitializeContextBase(&*context);
return context;
}
std::function<void(const AbstractValue&)> MakeFixInputPortTypeChecker(
InputPortIndex) const override {
return {};
}
std::multimap<int, int> GetDirectFeedthroughs() const final {
throw std::logic_error("GetDirectFeedthroughs is not implemented");
}
};
// Verify that system name methods work properly. Can't fully test the
// pathname here since we can't build a diagram; that's tested in diagram_test
// instead. But we can test it works right for a single-node System.
GTEST_TEST(SystemBaseTest, NameAndMessageSupport) {
MySystemBase system;
EXPECT_EQ(system.get_name(), "");
EXPECT_EQ(system.GetSystemName(), "_"); // Current dummy name.
EXPECT_EQ(system.GetSystemPathname(), "::_");
system.set_name("any_name_will_do");
EXPECT_EQ(system.get_name(), "any_name_will_do");
EXPECT_EQ(system.GetSystemName(), "any_name_will_do");
EXPECT_EQ(system.GetSystemPathname(), "::any_name_will_do");
EXPECT_EQ(system.GetSystemType(),
"drake::systems::system_base_test_internal::MySystemBase");
// Test specialized ValidateContext() and more-general
// ValidateCreatedForThisSystem() which can check anything that supports
// a get_system_id() method (we'll just use Context here for that also
// since it qualifies). We should ignore the differences in the error messages
// between the two functions. Both methods have pointer and non-pointer
// variants, so we exercise both.
std::unique_ptr<ContextBase> context = system.AllocateContext();
DRAKE_EXPECT_NO_THROW(system.ValidateContext(*context));
DRAKE_EXPECT_NO_THROW(system.ValidateContext(context.get()));
DRAKE_EXPECT_NO_THROW(system.ValidateCreatedForThisSystem(*context));
DRAKE_EXPECT_NO_THROW(system.ValidateCreatedForThisSystem(context.get()));
MySystemBase other_system;
auto other_context = other_system.AllocateContext();
// N.B. the error message we're looking for in ValidateContext() should *not*
// indicate that the system (or the context) is a root system/context.
DRAKE_EXPECT_THROWS_MESSAGE(system.ValidateContext(*other_context),
".+call on a .+ system.+was passed the Context "
"of[^]*#framework-context-system-mismatch.*");
DRAKE_EXPECT_THROWS_MESSAGE(system.ValidateContext(other_context.get()),
".+call on a .+ system.+was passed the Context "
"of[^]*#framework-context-system-mismatch.*");
DRAKE_EXPECT_THROWS_MESSAGE(
system.ValidateCreatedForThisSystem(*other_context),
".*ContextBase.*was not created for.*MySystemBase.*any_name_will_do.*");
DRAKE_EXPECT_THROWS_MESSAGE(
system.ValidateCreatedForThisSystem(other_context.get()),
".*ContextBase.*was not created for.*MySystemBase.*any_name_will_do.*");
// These methods check for null pointers even in Release builds but don't
// generate fancy messages for them. We're happy as long as "nullptr" gets
// mentioned.
ContextBase* null_context = nullptr;
DRAKE_EXPECT_THROWS_MESSAGE(system.ValidateContext(null_context),
".*nullptr.*");
DRAKE_EXPECT_THROWS_MESSAGE(system.ValidateCreatedForThisSystem(null_context),
".*nullptr.*");
MyContextBase disconnected_context; // No system id.
// ValidateContext() can't be used on a Context that has no system id.
DRAKE_EXPECT_THROWS_MESSAGE(
system.ValidateCreatedForThisSystem(disconnected_context),
".*MyContextBase.*was not associated.*should have been "
"created for.*MySystemBase.*any_name_will_do.*");
}
// Tests GetMemoryObjectName.
GTEST_TEST(SystemBaseTest, GetMemoryObjectName) {
const MySystemBase system;
const std::string name = system.GetMemoryObjectName();
// The nominal value for 'name' is something like:
// drake/systems/(anonymous namespace)/MySystemBase@0123456789abcdef
// We check only some platform-agnostic portions of that.
EXPECT_THAT(name, ::testing::HasSubstr("drake/systems/"));
EXPECT_THAT(name, ::testing::ContainsRegex("/MySystemBase@[0-9a-fA-F]{16}$"));
}
} // namespace system_base_test_internal
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/system_scalar_conversion_doxygen_test.cc | #include <gtest/gtest.h>
#include "drake/examples/pendulum/pendulum_plant.h"
namespace drake {
namespace systems {
namespace {
using Eigen::MatrixXd;
using examples::pendulum::PendulumPlant;
using examples::pendulum::PendulumState;
using examples::pendulum::PendulumStateIndices;
// N.B. The test code immediately below must be kept in sync with the identical
// code in ../system_scalar_conversion_doxygen.h.
GTEST_TEST(SystemScalarConversionDoxygen, PendulumPlantAutodiff) {
// Establish the plant and its initial conditions:
// tau = 0, theta = 0.1, thetadot = 0.2.
auto plant = std::make_unique<PendulumPlant<double>>();
auto context = plant->CreateDefaultContext();
plant->get_input_port(0).FixValue(context.get(), 0.0); // tau
auto* state = dynamic_cast<PendulumState<double>*>(
&context->get_mutable_continuous_state_vector());
state->set_theta(0.1);
state->set_thetadot(0.2);
double energy = plant->CalcTotalEnergy(*context);
ASSERT_NEAR(energy, -4.875, 0.001);
// Convert the plant and its context to use AutoDiff.
auto autodiff_plant = System<double>::ToAutoDiffXd(*plant);
auto autodiff_context = autodiff_plant->CreateDefaultContext();
autodiff_context->SetTimeStateAndParametersFrom(*context);
autodiff_plant->FixInputPortsFrom(*plant, *context, autodiff_context.get());
// Differentiate with respect to theta by setting dtheta/dtheta = 1.0.
constexpr int kNumDerivatives = 1;
auto& xc = autodiff_context->get_mutable_continuous_state_vector();
xc[PendulumStateIndices::kTheta].derivatives() =
MatrixXd::Identity(kNumDerivatives, kNumDerivatives).col(0);
// TODO(#6944) This is a hack to work around AutoDiffXd being broken.
// (This stanza is excluded from the Doxygen twin of this unit test.)
auto& params = autodiff_context->get_mutable_numeric_parameter(0);
for (int i = 0; i < params.size(); ++i) {
params[i].derivatives() = Vector1d::Zero(1);
}
// Compute denergy/dtheta around its initial conditions.
AutoDiffXd autodiff_energy =
autodiff_plant->CalcTotalEnergy(*autodiff_context);
ASSERT_NEAR(autodiff_energy.value(), -4.875, 0.001);
ASSERT_EQ(autodiff_energy.derivatives().size(), 1);
ASSERT_NEAR(autodiff_energy.derivatives()[0], 0.490, 0.001);
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/event_test.cc | #include "drake/systems/framework/event.h"
#include <gtest/gtest.h>
namespace drake {
namespace systems {
namespace {
// PeriodicEventData has an operator==() member function, and a Comparator
// struct whose operator() defines a "less than" ordering.
GTEST_TEST(EventsTest, PeriodicAttributeComparatorTest) {
PeriodicEventDataComparator comparator;
// Create two periodic event data objects.
PeriodicEventData d1, d2;
d1.set_period_sec(0);
d1.set_offset_sec(0);
d2.set_period_sec(0);
d2.set_offset_sec(1);
// Case 1: both period_sec's equal (d1's offset is less than d2's).
EXPECT_TRUE(comparator(d1, d2));
EXPECT_FALSE(d1 == d2);
// Case 2: d1's period is greater than d2's period (but d2's offset is
// greater than d1's offset).
d1.set_period_sec(1e-8);
EXPECT_FALSE(comparator(d1, d2));
EXPECT_FALSE(d1 == d2);
// Case 3: d1's period is less than d2's period (but d2's offset is
// lesser than d1's offset).
EXPECT_TRUE(comparator(d2, d1));
// Case 4: the two attributes are identical.
d2 = d1;
EXPECT_FALSE(comparator(d1, d2));
EXPECT_FALSE(comparator(d2, d1));
EXPECT_TRUE(d1 == d2);
}
// Check trigger data accessors:
// set/get_trigger_type()
// has/get/set_event_data(), get_mutable_event_data()
GTEST_TEST(EventsTest, EventDataAccess) {
PublishEvent<double> event; // Any concrete Event type will do.
EXPECT_EQ(event.get_trigger_type(), TriggerType::kUnknown);
EXPECT_FALSE(event.has_event_data<PeriodicEventData>());
EXPECT_FALSE(event.has_event_data<WitnessTriggeredEventData<double>>());
EXPECT_EQ(event.get_event_data<PeriodicEventData>(), nullptr);
EXPECT_EQ(event.get_event_data<WitnessTriggeredEventData<double>>(), nullptr);
EXPECT_EQ(event.get_mutable_event_data<PeriodicEventData>(), nullptr);
EXPECT_EQ(event.get_mutable_event_data<WitnessTriggeredEventData<double>>(),
nullptr);
PeriodicEventData data;
data.set_period_sec(0.125);
data.set_offset_sec(0.5);
event.set_trigger_type(TriggerType::kPeriodic);
EXPECT_EQ(event.get_trigger_type(), TriggerType::kPeriodic);
event.set_event_data(data);
EXPECT_TRUE(event.has_event_data<PeriodicEventData>());
EXPECT_FALSE(event.has_event_data<WitnessTriggeredEventData<double>>());
const PeriodicEventData* stored_data =
event.get_event_data<PeriodicEventData>();
ASSERT_NE(stored_data, nullptr);
EXPECT_NE(stored_data, &data); // Should have stored a copy.
EXPECT_EQ(stored_data->period_sec(), data.period_sec());
EXPECT_EQ(stored_data->offset_sec(), data.offset_sec());
EXPECT_EQ(stored_data, event.get_mutable_event_data<PeriodicEventData>());
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/parameters_test.cc | #include "drake/systems/framework/parameters.h"
#include <gtest/gtest.h>
#include "drake/systems/framework/test_utilities/pack_value.h"
namespace drake {
namespace systems {
namespace {
class ParametersTest : public ::testing::Test {
protected:
void SetUp() override {
params_ = MakeParams<double>();
BasicVector<double>& p0 = params_->get_mutable_numeric_parameter(0);
p0[0] = 3.0;
p0[1] = 6.0;
BasicVector<double>& p1 = params_->get_mutable_numeric_parameter(1);
p1[0] = 9.0;
p1[1] = 12.0;
}
template <typename T>
static std::unique_ptr<Parameters<T>> MakeParams() {
std::vector<std::unique_ptr<BasicVector<T>>> numeric;
// Two numeric parameters, each vectors of length 2.
numeric.push_back(std::make_unique<BasicVector<T>>(2));
numeric.push_back(std::make_unique<BasicVector<T>>(2));
// Two abstract parameters, each integers.
std::vector<std::unique_ptr<AbstractValue>> abstract;
abstract.push_back(PackValue<int>(72));
abstract.push_back(PackValue<int>(144));
return std::make_unique<Parameters<T>>(std::move(numeric),
std::move(abstract));
}
std::unique_ptr<Parameters<double>> params_;
};
TEST_F(ParametersTest, Numeric) {
ASSERT_EQ(2, params_->num_numeric_parameter_groups());
ASSERT_EQ(2, params_->get_numeric_parameters().num_groups());
EXPECT_EQ(3.0, params_->get_numeric_parameter(0)[0]);
EXPECT_EQ(6.0, params_->get_numeric_parameter(0)[1]);
EXPECT_EQ(9.0, params_->get_numeric_parameter(1)[0]);
EXPECT_EQ(12.0, params_->get_numeric_parameter(1)[1]);
params_->get_mutable_numeric_parameter(0)[1] = 42.0;
EXPECT_EQ(42.0, params_->get_numeric_parameter(0)[1]);
}
TEST_F(ParametersTest, Abstract) {
ASSERT_EQ(2, params_->num_abstract_parameters());
ASSERT_EQ(2, params_->get_abstract_parameters().size());
EXPECT_EQ(72, UnpackIntValue(params_->get_abstract_parameter(0)));
EXPECT_EQ(144, params_->template get_abstract_parameter<int>(1));
params_->template get_mutable_abstract_parameter<int>(1) = 512;
EXPECT_EQ(512, UnpackIntValue(params_->get_abstract_parameter(1)));
}
TEST_F(ParametersTest, Clone) {
// Test that data is copied into the clone.
auto clone = params_->Clone();
EXPECT_EQ(3.0, clone->get_numeric_parameter(0)[0]);
EXPECT_EQ(72, UnpackIntValue(clone->get_abstract_parameter(0)));
EXPECT_EQ(144, UnpackIntValue(clone->get_abstract_parameter(1)));
// Test that changes to the clone don't write through to the original.
// - numeric
clone->get_mutable_numeric_parameter(0)[1] = 42.0;
EXPECT_EQ(6.0, params_->get_numeric_parameter(0)[1]);
// - abstract
clone->get_mutable_abstract_parameter(0).set_value<int>(256);
EXPECT_EQ(72, UnpackIntValue(params_->get_abstract_parameter(0)));
}
// Tests we can promote Parameters<double> to Parameters<symbolic::Expression>.
TEST_F(ParametersTest, SetSymbolicFromDouble) {
auto symbolic_params = MakeParams<symbolic::Expression>();
symbolic_params->SetFrom(*params_);
// The numeric parameters have been converted to symbolic constants.
const auto& p0 = symbolic_params->get_numeric_parameter(0);
EXPECT_EQ("3", p0[0].to_string());
EXPECT_EQ("6", p0[1].to_string());
const auto& p1 = symbolic_params->get_numeric_parameter(1);
EXPECT_EQ("9", p1[0].to_string());
EXPECT_EQ("12", p1[1].to_string());
// The abstract parameters have simply been cloned.
EXPECT_EQ(72, UnpackIntValue(symbolic_params->get_abstract_parameter(0)));
EXPECT_EQ(144, UnpackIntValue(symbolic_params->get_abstract_parameter(1)));
}
// Tests we can demote Parameters<symbolic::Expression> to Parameters<double>.
TEST_F(ParametersTest, SetDoubleFromSymbolic) {
auto symbolic_params = MakeParams<symbolic::Expression>();
auto& p0 = symbolic_params->get_mutable_numeric_parameter(0);
auto& p1 = symbolic_params->get_mutable_numeric_parameter(1);
p0[0] = 4.0;
p0[1] = 7.0;
p1[0] = 10.0;
p1[1] = 13.0;
params_->SetFrom(*symbolic_params);
const auto& actual_p0 = params_->get_numeric_parameter(0);
const auto& actual_p1 = params_->get_numeric_parameter(1);
EXPECT_EQ(4.0, actual_p0[0]);
EXPECT_EQ(7.0, actual_p0[1]);
EXPECT_EQ(10.0, actual_p1[0]);
EXPECT_EQ(13.0, actual_p1[1]);
}
// Constructs an AutoDiffXd parameters with the same dimensions as
// params_, and tests we can upconvert the latter into the former.
TEST_F(ParametersTest, SetAutodiffFromDouble) {
auto autodiff_params = MakeParams<AutoDiffXd>();
autodiff_params->SetFrom(*params_);
// The numeric parameters have been converted to autodiff.
const auto& p0 = autodiff_params->get_numeric_parameter(0);
EXPECT_EQ(3.0, p0[0].value());
EXPECT_EQ(6.0, p0[1].value());
const auto& p1 = autodiff_params->get_numeric_parameter(1);
EXPECT_EQ(9.0, p1[0].value());
EXPECT_EQ(12.0, p1[1].value());
// The abstract parameters have simply been cloned.
EXPECT_EQ(72, UnpackIntValue(autodiff_params->get_abstract_parameter(0)));
EXPECT_EQ(144, UnpackIntValue(autodiff_params->get_abstract_parameter(1)));
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/leaf_context_test.cc | #include "drake/systems/framework/leaf_context.h"
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "drake/common/autodiff.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/test_utilities/is_dynamic_castable.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/fixed_input_port_value.h"
#include "drake/systems/framework/test_utilities/pack_value.h"
using Eigen::VectorXd;
namespace drake {
namespace systems {
constexpr int kNumInputPorts = 2;
constexpr int kInputSize[kNumInputPorts] = {1, 2};
constexpr int kNumOutputPorts = 3;
constexpr int kContinuousStateSize = 5;
constexpr int kGeneralizedPositionSize = 2;
constexpr int kGeneralizedVelocitySize = 2;
constexpr int kMiscContinuousStateSize = 1;
constexpr double kTime = 12.0;
// Defines a simple class for evaluating abstract types.
class TestAbstractType {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(TestAbstractType)
TestAbstractType() = default;
};
class LeafContextTest : public ::testing::Test {
protected:
void SetUp() override {
context_.SetTime(kTime);
internal::SystemBaseContextBaseAttorney::set_system_id(
&context_, internal::SystemId::get_new_id());
// Set up slots for input and output ports.
AddInputPorts(kNumInputPorts, &context_);
AddOutputPorts(kNumOutputPorts, &context_);
// Fixed input values get new tickets -- manually update the ticket
// counter here so this test can add more ticketed things later.
// (That's not allowed in user code.)
for (int i = 0; i < kNumInputPorts; ++i) {
context_.FixInputPort(
i, Value<BasicVector<double>>(kInputSize[i]));
++next_ticket_;
}
// Reserve a continuous state with five elements.
context_.init_continuous_state(std::make_unique<ContinuousState<double>>(
BasicVector<double>::Make({1.0, 2.0, 3.0, 5.0, 8.0}),
kGeneralizedPositionSize, kGeneralizedVelocitySize,
kMiscContinuousStateSize));
// Reserve a discrete state with a single element of size 1, and verify
// that we can change it using get_mutable_discrete_state_vector().
std::vector<std::unique_ptr<BasicVector<double>>> xd_single;
xd_single.push_back(BasicVector<double>::Make({128.0}));
context_.init_discrete_state(
std::make_unique<DiscreteValues<double>>(std::move(xd_single)));
context_.get_mutable_discrete_state_vector()[0] = 192.0;
EXPECT_EQ(context_.get_discrete_state().get_vector()[0], 192.0);
// Reserve a discrete state with two elements, of size 1 and size 2.
std::vector<std::unique_ptr<BasicVector<double>>> xd;
xd.push_back(BasicVector<double>::Make({128.0}));
xd.push_back(BasicVector<double>::Make({256.0, 512.0}));
context_.init_discrete_state(
std::make_unique<DiscreteValues<double>>(std::move(xd)));
// Add a tracker for the discrete variable xd0 and subscribe the xd
// tracker to it.
DependencyGraph& graph = context_.get_mutable_dependency_graph();
auto& xd0_tracker = graph.CreateNewDependencyTracker(next_ticket_++,
"xd0");
context_.AddDiscreteStateTicket(xd0_tracker.ticket());
graph.get_mutable_tracker(DependencyTicket(internal::kXdTicket))
.SubscribeToPrerequisite(&xd0_tracker);
// Reserve an abstract state with one element, which is not owned.
abstract_state_ = PackValue(42);
std::vector<AbstractValue*> xa;
xa.push_back(abstract_state_.get());
context_.init_abstract_state(
std::make_unique<AbstractValues>(std::move(xa)));
// Add a tracker for the abstract variable xa0 and subscribe the xa
// tracker to it.
auto& xa0_tracker = graph.CreateNewDependencyTracker(next_ticket_++,
"xa0");
context_.AddAbstractStateTicket(xa0_tracker.ticket());
graph.get_mutable_tracker(DependencyTicket(internal::kXaTicket))
.SubscribeToPrerequisite(&xa0_tracker);
// Reserve two numeric parameters of size 3 and size 4.
std::vector<std::unique_ptr<BasicVector<double>>> vector_params;
vector_params.push_back(BasicVector<double>::Make({1.0, 2.0, 4.0}));
vector_params.push_back(BasicVector<double>::Make({8.0, 16.0, 32.0, 64.0}));
auto& pn0_tracker = graph.CreateNewDependencyTracker(next_ticket_++, "pn0");
auto& pn1_tracker = graph.CreateNewDependencyTracker(next_ticket_++, "pn1");
context_.AddNumericParameterTicket(pn0_tracker.ticket());
context_.AddNumericParameterTicket(pn1_tracker.ticket());
graph.get_mutable_tracker(DependencyTicket(internal::kPnTicket))
.SubscribeToPrerequisite(&pn0_tracker);
graph.get_mutable_tracker(DependencyTicket(internal::kPnTicket))
.SubscribeToPrerequisite(&pn1_tracker);
// Reserve one abstract-valued parameter of type TestAbstractType.
std::vector<std::unique_ptr<AbstractValue>> abstract_params;
abstract_params.push_back(std::make_unique<Value<TestAbstractType>>());
auto& pa0_tracker = graph.CreateNewDependencyTracker(next_ticket_++, "pa0");
context_.AddAbstractParameterTicket(pa0_tracker.ticket());
graph.get_mutable_tracker(DependencyTicket(internal::kPaTicket))
.SubscribeToPrerequisite(&pa0_tracker);
context_.init_parameters(std::make_unique<Parameters<double>>(
std::move(vector_params), std::move(abstract_params)));
}
// Reads a FixedInputPortValue connected to @p context at @p index.
// Returns nullptr if the port is not connected.
const BasicVector<double>* ReadVectorInputPort(const Context<double>& context,
int index) {
const FixedInputPortValue* free_value =
context.MaybeGetFixedInputPortValue(InputPortIndex(index));
return free_value ? &free_value->get_vector_value<double>() : nullptr;
}
// Reads a FixedInputPortValue connected to @p context at @p index.
const std::string* ReadStringInputPort(const Context<double>& context,
int index) {
const FixedInputPortValue* free_value =
context.MaybeGetFixedInputPortValue(InputPortIndex(index));
return free_value ? &free_value->get_value().get_value<std::string>()
: nullptr;
}
// Reads a FixedInputPortValue connected to @p context at @p index.
const AbstractValue* ReadAbstractInputPort(const Context<double>& context,
int index) {
const FixedInputPortValue* free_value =
context.MaybeGetFixedInputPortValue(InputPortIndex(index));
return free_value ? &free_value->get_value() : nullptr;
}
// Mocks up an input port sufficient to allow us to give it a fixed value.
template <typename T>
void AddInputPort(InputPortIndex i, LeafContext<T>* context,
std::function<void(const AbstractValue&)> type_checker) {
input_port_tickets_.push_back(next_ticket_);
context->AddInputPort(i, next_ticket_++, std::move(type_checker));
}
// Mocks up input ports numbered [0, n).
template <typename T>
void AddInputPorts(int n, LeafContext<T>* context) {
for (InputPortIndex i(0); i < n; ++i) {
AddInputPort(i, context, {});
}
}
// Mocks up some output ports sufficient to check that they are installed and
// wired up properly. (We can't evaluate output ports without a System.)
// This code mimics SystemBase::AllocateContext().
template <typename T>
void AddOutputPorts(int n, LeafContext<T>* context) {
// Pretend the first output port has an external dependency (so tracking
// should be deferred) while the rest are dependent on a built-in tracker.
output_port_tickets_.push_back(next_ticket_);
context->AddOutputPort(OutputPortIndex(0), next_ticket_++,
{SubsystemIndex(1), DependencyTicket(0)});
for (OutputPortIndex i(1); i < n; ++i) {
output_port_tickets_.push_back(next_ticket_);
context->AddOutputPort(
i, next_ticket_++,
{std::nullopt, DependencyTicket(internal::kAllSourcesTicket)});
}
}
DependencyTicket next_ticket_{internal::kNextAvailableTicket};
LeafContext<double> context_;
std::unique_ptr<AbstractValue> abstract_state_;
// Track assigned tickets for sanity checking.
std::vector<DependencyTicket> input_port_tickets_;
std::vector<DependencyTicket> output_port_tickets_;
};
namespace {
// Verifies that @p state is a clone of the state constructed in
// LeafContextTest::SetUp.
void VerifyClonedState(const State<double>& clone) {
// Verify that the state was copied.
const ContinuousState<double>& xc = clone.get_continuous_state();
{
VectorX<double> contents = xc.CopyToVector();
VectorX<double> expected(kContinuousStateSize);
expected << 1.0, 2.0, 3.0, 5.0, 8.0;
EXPECT_EQ(expected, contents);
}
EXPECT_EQ(2, clone.get_discrete_state().num_groups());
const BasicVector<double>& xd0 = clone.get_discrete_state().get_vector(0);
const BasicVector<double>& xd1 = clone.get_discrete_state().get_vector(1);
// Check that sugar methods work too.
EXPECT_EQ(&clone.get_discrete_state(0), &xd0);
EXPECT_EQ(&clone.get_discrete_state(1), &xd1);
{
VectorX<double> contents = xd0.CopyToVector();
VectorX<double> expected(1);
expected << 128.0;
EXPECT_EQ(expected, contents);
}
{
VectorX<double> contents = xd1.CopyToVector();
VectorX<double> expected(2);
expected << 256.0, 512.0;
EXPECT_EQ(expected, contents);
}
EXPECT_EQ(1, clone.get_abstract_state().size());
EXPECT_EQ(42, clone.get_abstract_state().get_value(0).get_value<int>());
EXPECT_EQ(42, clone.get_abstract_state<int>(0));
// Verify that the state type was preserved.
const BasicVector<double>* xc_data =
dynamic_cast<const BasicVector<double>*>(&xc.get_vector());
ASSERT_NE(nullptr, xc_data);
EXPECT_EQ(kContinuousStateSize, xc_data->size());
// Verify that the second-order structure was preserved.
EXPECT_EQ(kGeneralizedPositionSize, xc.get_generalized_position().size());
EXPECT_EQ(1.0, xc.get_generalized_position()[0]);
EXPECT_EQ(2.0, xc.get_generalized_position()[1]);
EXPECT_EQ(kGeneralizedVelocitySize, xc.get_generalized_velocity().size());
EXPECT_EQ(3.0, xc.get_generalized_velocity()[0]);
EXPECT_EQ(5.0, xc.get_generalized_velocity()[1]);
EXPECT_EQ(kMiscContinuousStateSize, xc.get_misc_continuous_state().size());
EXPECT_EQ(8.0, xc.get_misc_continuous_state()[0]);
}
TEST_F(LeafContextTest, CheckPorts) {
ASSERT_EQ(kNumInputPorts, context_.num_input_ports());
ASSERT_EQ(kNumOutputPorts, context_.num_output_ports());
// The "all inputs" tracker should have been subscribed to each of the
// input ports. And each input port should have subscribed to its fixed
// input value.
auto& u_tracker =
context_.get_tracker(DependencyTicket(internal::kAllInputPortsTicket));
for (InputPortIndex i(0); i < kNumInputPorts; ++i) {
EXPECT_EQ(context_.input_port_ticket(i), input_port_tickets_[i]);
auto& tracker = context_.get_tracker(input_port_tickets_[i]);
// The fixed input value is a prerequisite.
EXPECT_EQ(tracker.num_prerequisites(), 1);
EXPECT_EQ(tracker.num_subscribers(), 1);
EXPECT_TRUE(u_tracker.HasPrerequisite(tracker));
}
// All output ports but port 0 should be subscribed to the "all sources"
// tracker (just for testing -- would normally be subscribed to a cache
// entry tracker).
auto& all_sources_tracker =
context_.get_tracker(DependencyTicket(internal::kAllSourcesTicket));
for (OutputPortIndex i(0); i < kNumOutputPorts; ++i) {
EXPECT_EQ(context_.output_port_ticket(i), output_port_tickets_[i]);
auto& tracker = context_.get_tracker(output_port_tickets_[i]);
EXPECT_EQ(tracker.num_subscribers(), 0);
if (i == 0) {
EXPECT_EQ(tracker.num_prerequisites(), 0);
} else {
EXPECT_EQ(tracker.num_prerequisites(), 1);
EXPECT_TRUE(all_sources_tracker.HasSubscriber(tracker));
}
}
}
TEST_F(LeafContextTest, GetNumDiscreteStateGroups) {
EXPECT_EQ(2, context_.num_discrete_state_groups());
}
TEST_F(LeafContextTest, GetNumAbstractStates) {
EXPECT_EQ(1, context_.num_abstract_states());
}
TEST_F(LeafContextTest, IsStateless) {
EXPECT_FALSE(context_.is_stateless());
LeafContext<double> empty_context;
EXPECT_TRUE(empty_context.is_stateless());
}
TEST_F(LeafContextTest, HasOnlyContinuousState) {
EXPECT_FALSE(context_.has_only_continuous_state());
context_.init_discrete_state(std::make_unique<DiscreteValues<double>>());
context_.init_abstract_state(std::make_unique<AbstractValues>());
EXPECT_TRUE(context_.has_only_continuous_state());
}
TEST_F(LeafContextTest, HasOnlyDiscreteState) {
EXPECT_FALSE(context_.has_only_discrete_state());
context_.init_continuous_state(std::make_unique<ContinuousState<double>>());
context_.init_abstract_state(std::make_unique<AbstractValues>());
EXPECT_TRUE(context_.has_only_discrete_state());
}
TEST_F(LeafContextTest, GetNumStates) {
LeafContext<double> context;
EXPECT_EQ(context.num_total_states(), 0);
// Reserve a continuous state with five elements.
context.init_continuous_state(std::make_unique<ContinuousState<double>>(
BasicVector<double>::Make({1.0, 2.0, 3.0, 5.0, 8.0})));
EXPECT_EQ(context.num_total_states(), 5);
// Reserve a discrete state with two elements, of size 1 and size 2.
std::vector<std::unique_ptr<BasicVector<double>>> xd;
xd.push_back(BasicVector<double>::Make({128.0}));
xd.push_back(BasicVector<double>::Make({256.0, 512.0}));
context.init_discrete_state(
std::make_unique<DiscreteValues<double>>(std::move(xd)));
EXPECT_EQ(context.num_total_states(), 8);
// Reserve an abstract state with one element, which is not owned.
std::unique_ptr<AbstractValue> abstract_state = PackValue(42);
std::vector<AbstractValue*> xa;
xa.push_back(abstract_state.get());
context.init_abstract_state(std::make_unique<AbstractValues>(std::move(xa)));
EXPECT_THROW(context.num_total_states(), std::runtime_error);
}
TEST_F(LeafContextTest, GetVectorInput) {
// N.B. This test ignores the member field `context_`.
LeafContext<double> context;
AddInputPorts(2, &context);
// Add input port 0 to the context, but leave input port 1 uninitialized.
context.FixInputPort(0, Value<BasicVector<double>>(
Eigen::Vector2d(5.0, 6.0)));
// Test that port 0 is retrievable.
VectorX<double> expected(2);
expected << 5, 6;
EXPECT_EQ(expected, ReadVectorInputPort(context, 0)->get_value());
// Test that port 1 is nullptr.
EXPECT_EQ(nullptr, ReadVectorInputPort(context, 1));
}
TEST_F(LeafContextTest, GetAbstractInput) {
// N.B. This test ignores the member field `context_`.
LeafContext<double> context;
AddInputPorts(2, &context);
// Add input port 0 to the context, but leave input port 1 uninitialized.
context.FixInputPort(0, Value<std::string>("foo"));
// Test that port 0 is retrievable.
EXPECT_EQ("foo", *ReadStringInputPort(context, 0));
// Test that port 1 is nullptr.
EXPECT_EQ(nullptr, ReadAbstractInputPort(context, 1));
}
TEST_F(LeafContextTest, ToString) {
const std::string str = context_.to_string();
using ::testing::HasSubstr;
EXPECT_THAT(str, HasSubstr("Time: 12"));
EXPECT_THAT(str, HasSubstr("5 continuous states"));
EXPECT_THAT(str, HasSubstr("2 discrete state groups"));
EXPECT_THAT(str, HasSubstr("1 abstract state"));
EXPECT_THAT(str, HasSubstr("2 numeric parameter groups"));
EXPECT_THAT(str, HasSubstr("1 abstract parameters"));
}
// Tests that items can be stored and retrieved in the cache.
TEST_F(LeafContextTest, SetAndGetCache) {
CacheIndex index = context_.get_mutable_cache()
.CreateNewCacheEntryValue(
CacheIndex(0), ++next_ticket_, "entry",
{DependencyTicket(internal::kNothingTicket)},
&context_.get_mutable_dependency_graph())
.cache_index();
CacheEntryValue& entry_value =
context_.get_mutable_cache().get_mutable_cache_entry_value(index);
entry_value.SetInitialValue(PackValue(42));
EXPECT_EQ(entry_value.cache_index(), index);
EXPECT_TRUE(entry_value.ticket().is_valid());
EXPECT_EQ(entry_value.description(), "entry");
EXPECT_TRUE(entry_value.is_out_of_date()); // Initial value isn't up to date.
EXPECT_THROW(entry_value.GetValueOrThrow<int>(), std::logic_error);
entry_value.mark_up_to_date();
DRAKE_EXPECT_NO_THROW(entry_value.GetValueOrThrow<int>());
const AbstractValue& value = entry_value.GetAbstractValueOrThrow();
EXPECT_EQ(42, UnpackIntValue(value));
EXPECT_EQ(42, entry_value.GetValueOrThrow<int>());
EXPECT_EQ(42, entry_value.get_value<int>());
// Already up to date.
EXPECT_THROW(entry_value.SetValueOrThrow<int>(43), std::logic_error);
entry_value.mark_out_of_date();
DRAKE_EXPECT_NO_THROW(entry_value.SetValueOrThrow<int>(43));
EXPECT_FALSE(entry_value.is_out_of_date()); // Set marked it up to date.
EXPECT_EQ(43, UnpackIntValue(entry_value.GetAbstractValueOrThrow()));
entry_value.mark_out_of_date();
entry_value.set_value<int>(99);
EXPECT_FALSE(entry_value.is_out_of_date()); // Set marked it up to date.
EXPECT_EQ(99, entry_value.get_value<int>());
}
TEST_F(LeafContextTest, Clone) {
std::unique_ptr<Context<double>> clone = context_.Clone();
// Verify that the time was copied.
EXPECT_EQ(kTime, clone->get_time());
// Verify that the system id was copied.
EXPECT_TRUE(context_.get_system_id().is_valid());
EXPECT_EQ(context_.get_system_id(), clone->get_system_id());
ContinuousState<double>& xc = clone->get_mutable_continuous_state();
EXPECT_TRUE(xc.get_system_id().is_valid());
EXPECT_EQ(xc.get_system_id(), context_.get_system_id());
const DiscreteValues<double>& xd = clone->get_discrete_state();
EXPECT_TRUE(xd.get_system_id().is_valid());
EXPECT_EQ(xd.get_system_id(), context_.get_system_id());
// Verify that the cloned input ports contain the same data,
// but are different pointers.
EXPECT_EQ(kNumInputPorts, clone->num_input_ports());
for (int i = 0; i < kNumInputPorts; ++i) {
const BasicVector<double>* context_port = ReadVectorInputPort(context_, i);
const BasicVector<double>* clone_port = ReadVectorInputPort(*clone, i);
EXPECT_NE(context_port, clone_port);
EXPECT_TRUE(CompareMatrices(context_port->get_value(),
clone_port->get_value(), 1e-8,
MatrixCompareType::absolute));
}
// Verify that the state was copied.
VerifyClonedState(clone->get_state());
// Verify that changes to the cloned state do not affect the original state.
// -- Continuous
xc.get_mutable_generalized_velocity()[1] = 42.0;
EXPECT_EQ(42.0, xc[3]);
EXPECT_EQ(5.0, context_.get_continuous_state_vector()[3]);
// -- Discrete
BasicVector<double>& xd1 = clone->get_mutable_discrete_state(1);
xd1[0] = 1024.0;
EXPECT_EQ(1024.0, clone->get_discrete_state(1)[0]);
EXPECT_EQ(256.0, context_.get_discrete_state(1)[0]);
// Check State indexed discrete methods too.
State<double>& state = clone->get_mutable_state();
EXPECT_EQ(1024.0, state.get_discrete_state(1)[0]);
EXPECT_EQ(1024.0, state.get_mutable_discrete_state(1)[0]);
// -- Abstract (even though it's not owned in context_)
clone->get_mutable_abstract_state<int>(0) = 2048;
EXPECT_EQ(42, context_.get_abstract_state<int>(0));
EXPECT_EQ(42, context_.get_abstract_state().get_value(0).get_value<int>());
EXPECT_EQ(2048, clone->get_abstract_state<int>(0));
// Verify that the parameters were copied.
LeafContext<double>* leaf_clone =
dynamic_cast<LeafContext<double>*>(clone.get());
EXPECT_EQ(2, leaf_clone->num_numeric_parameter_groups());
const BasicVector<double>& param0 = leaf_clone->get_numeric_parameter(0);
EXPECT_EQ(1.0, param0[0]);
EXPECT_EQ(2.0, param0[1]);
EXPECT_EQ(4.0, param0[2]);
const BasicVector<double>& param1 = leaf_clone->get_numeric_parameter(1);
EXPECT_EQ(8.0, param1[0]);
EXPECT_EQ(16.0, param1[1]);
EXPECT_EQ(32.0, param1[2]);
EXPECT_EQ(64.0, param1[3]);
ASSERT_EQ(1, leaf_clone->num_abstract_parameters());
EXPECT_TRUE(is_dynamic_castable<const TestAbstractType>(
&leaf_clone->get_abstract_parameter(0).get_value<TestAbstractType>()));
// Verify that changes to the cloned parameters do not affect the originals.
leaf_clone->get_mutable_numeric_parameter(0)[0] = 76.0;
EXPECT_EQ(1.0, context_.get_numeric_parameter(0)[0]);
}
// Violates the Context `DoCloneWithoutPointers` law.
class InvalidContext : public LeafContext<double> {
public:
InvalidContext() : LeafContext<double>() {}
};
TEST_F(LeafContextTest, BadClone) {
InvalidContext bad_context;
DRAKE_EXPECT_THROWS_MESSAGE(
bad_context.Clone(),
".*typeid.source. == typeid.clone.*");
}
// Tests that a LeafContext can provide a clone of its State.
TEST_F(LeafContextTest, CloneState) {
std::unique_ptr<State<double>> clone = context_.CloneState();
VerifyClonedState(*clone);
// Verify that the system id was copied.
EXPECT_TRUE(clone->get_system_id().is_valid());
EXPECT_EQ(clone->get_system_id(), context_.get_system_id());
const ContinuousState<double>& xc = clone->get_continuous_state();
EXPECT_TRUE(xc.get_system_id().is_valid());
EXPECT_EQ(xc.get_system_id(), context_.get_system_id());
const DiscreteValues<double>& xd = clone->get_discrete_state();
EXPECT_TRUE(xd.get_system_id().is_valid());
EXPECT_EQ(xd.get_system_id(), context_.get_system_id());
}
// Tests that the State can be copied from another State.
TEST_F(LeafContextTest, CopyStateFrom) {
std::unique_ptr<Context<double>> clone = context_.Clone();
clone->get_mutable_continuous_state()[0] = 81.0;
clone->get_mutable_discrete_state(0)[0] = 243.0;
clone->get_mutable_abstract_state<int>(0) = 729;
context_.get_mutable_state().SetFrom(clone->get_state());
EXPECT_EQ(81.0, context_.get_continuous_state()[0]);
EXPECT_EQ(243.0, context_.get_discrete_state(0)[0]);
EXPECT_EQ(729, context_.get_abstract_state<int>(0));
}
// Tests that a LeafContext<AutoDiffXd> can be initialized from a
// LeafContext<double>.
TEST_F(LeafContextTest, SetTimeStateAndParametersFrom) {
// Set up a target with the same geometry as the source, and no
// interesting values.
// In actual applications, System<T>::CreateDefaultContext does this.
LeafContext<AutoDiffXd> target;
target.init_continuous_state(std::make_unique<ContinuousState<AutoDiffXd>>(
std::make_unique<BasicVector<AutoDiffXd>>(5),
kGeneralizedPositionSize, kGeneralizedVelocitySize,
kMiscContinuousStateSize));
std::vector<std::unique_ptr<BasicVector<AutoDiffXd>>> xd;
xd.push_back(std::make_unique<BasicVector<AutoDiffXd>>(1));
xd.push_back(std::make_unique<BasicVector<AutoDiffXd>>(2));
target.init_discrete_state(
std::make_unique<DiscreteValues<AutoDiffXd>>(std::move(xd)));
std::vector<std::unique_ptr<AbstractValue>> xa;
xa.push_back(PackValue(76));
target.init_abstract_state(std::make_unique<AbstractValues>(std::move(xa)));
std::vector<std::unique_ptr<BasicVector<AutoDiffXd>>> params;
params.push_back(std::make_unique<BasicVector<AutoDiffXd>>(3));
params.push_back(std::make_unique<BasicVector<AutoDiffXd>>(4));
target.get_mutable_parameters().set_numeric_parameters(
std::make_unique<DiscreteValues<AutoDiffXd>>(std::move(params)));
std::vector<std::unique_ptr<AbstractValue>> abstract_params;
abstract_params.push_back(std::make_unique<Value<TestAbstractType>>());
target.get_mutable_parameters().set_abstract_parameters(
std::make_unique<AbstractValues>(std::move(abstract_params)));
// Set the accuracy in the target- setting time, state, and parameters
// should reset it.
const double accuracy = 0.1;
target.SetAccuracy(accuracy);
// Set the target from the source.
target.SetTimeStateAndParametersFrom(context_);
// Verify that accuracy is no longer set.
EXPECT_FALSE(target.get_accuracy());
// Verify that time was set.
EXPECT_EQ(kTime, target.get_time());
// Verify that state was set.
const ContinuousState<AutoDiffXd>& xc = target.get_continuous_state();
EXPECT_EQ(kGeneralizedPositionSize, xc.get_generalized_position().size());
EXPECT_EQ(5.0, xc.get_generalized_velocity()[1].value());
EXPECT_EQ(0, xc.get_generalized_velocity()[1].derivatives().size());
EXPECT_EQ(128.0, target.get_discrete_state(0)[0]);
// Verify that parameters were set.
target.get_numeric_parameter(0);
EXPECT_EQ(2.0, (target.get_numeric_parameter(0)[1].value()));
// Set the accuracy in the context.
context_.SetAccuracy(accuracy);
target.SetTimeStateAndParametersFrom(context_);
EXPECT_EQ(target.get_accuracy(), accuracy);
}
// Verifies that accuracy is set properly.
TEST_F(LeafContextTest, Accuracy) {
// Verify accuracy is not set by default.
EXPECT_FALSE(context_.get_accuracy());
// Verify that setting the accuracy is reflected in cloning.
const double unity = 1.0;
context_.SetAccuracy(unity);
std::unique_ptr<Context<double>> clone = context_.Clone();
EXPECT_EQ(clone->get_accuracy().value(), unity);
}
void MarkAllCacheValuesUpToDate(Cache* cache) {
for (CacheIndex i(0); i < cache->cache_size(); ++i) {
if (cache->has_cache_entry_value(i))
cache->get_mutable_cache_entry_value(i).mark_up_to_date();
}
}
void CheckAllCacheValuesUpToDateExcept(
const Cache& cache, const std::set<CacheIndex>& should_be_out_of_date) {
for (CacheIndex i(0); i < cache.cache_size(); ++i) {
if (!cache.has_cache_entry_value(i)) continue;
const CacheEntryValue& entry = cache.get_cache_entry_value(i);
EXPECT_EQ(entry.is_out_of_date(), should_be_out_of_date.contains(i)) << i;
}
}
// Test that changing any Context source value invalidates computations that
// are dependent on that source value. The possible sources are:
// time, accuracy, state, parameters, and input ports. In addition, state
// is partitioned into continuous, discrete, and abstract, and parameters
// are partitioned into numeric and abstract.
//
TEST_F(LeafContextTest, Invalidation) {
// Add cache entries to the context, each dependent on one ticket and
// record the associated CacheIndex. Start with everything valid.
Cache& cache = context_.get_mutable_cache();
CacheIndex index(cache.cache_size()); // Next available index.
std::map<int, CacheIndex> depends; // Maps ticket number to cache index.
for (int ticket = internal::kNothingTicket;
ticket <= internal::kLastSourceTicket; ++ticket) {
CacheEntryValue& entry = cache.CreateNewCacheEntryValue(
index, next_ticket_++, "entry" + std::to_string(index),
{DependencyTicket(ticket)}, &context_.get_mutable_dependency_graph());
depends[ticket] = index;
entry.SetInitialValue(AbstractValue::Make<int>(int{index}));
++index;
}
// Baseline: nothing modified.
MarkAllCacheValuesUpToDate(&cache);
CheckAllCacheValuesUpToDateExcept(cache, {});
// Modify time.
MarkAllCacheValuesUpToDate(&cache);
context_.SetTime(context_.get_time() + 1); // Ensure this is a change.
CheckAllCacheValuesUpToDateExcept(cache,
{depends[internal::kTimeTicket],
depends[internal::kAllSourcesExceptInputPortsTicket],
depends[internal::kAllSourcesTicket]});
// Accuracy.
MarkAllCacheValuesUpToDate(&cache);
context_.SetAccuracy(7.123e-4); // Ensure this is a change.
CheckAllCacheValuesUpToDateExcept(cache,
{depends[internal::kAccuracyTicket],
depends[internal::kConfigurationTicket],
depends[internal::kKinematicsTicket],
depends[internal::kAllSourcesExceptInputPortsTicket],
depends[internal::kAllSourcesTicket]});
// This is everything that depends on generalized positions q.
const std::set<CacheIndex> q_dependent{
depends[internal::kQTicket], depends[internal::kXcTicket],
depends[internal::kXTicket], depends[internal::kConfigurationTicket],
depends[internal::kKinematicsTicket],
depends[internal::kAllSourcesExceptInputPortsTicket],
depends[internal::kAllSourcesTicket]};
// This is everything that depends on generalized velocities v and misc. z.
const std::set<CacheIndex> vz_dependent{
depends[internal::kVTicket], depends[internal::kZTicket],
depends[internal::kXcTicket], depends[internal::kXTicket],
depends[internal::kConfigurationTicket],
depends[internal::kKinematicsTicket],
depends[internal::kAllSourcesExceptInputPortsTicket],
depends[internal::kAllSourcesTicket]};
// This is everything that depends on continuous state.
std::set<CacheIndex> xc_dependent(q_dependent);
xc_dependent.insert(vz_dependent.cbegin(), vz_dependent.cend());
// This is everything depends on continuous, discrete, or abstract state.
std::set<CacheIndex> x_dependent(xc_dependent);
x_dependent.insert(depends[internal::kXdTicket]);
x_dependent.insert(depends[internal::kXaTicket]);
// Modify all of state.
MarkAllCacheValuesUpToDate(&cache);
context_.get_mutable_state();
CheckAllCacheValuesUpToDateExcept(cache, x_dependent);
// Modify just continuous state.
MarkAllCacheValuesUpToDate(&cache);
context_.get_mutable_continuous_state();
CheckAllCacheValuesUpToDateExcept(cache, xc_dependent);
MarkAllCacheValuesUpToDate(&cache);
context_.get_mutable_continuous_state_vector();
CheckAllCacheValuesUpToDateExcept(cache, xc_dependent);
MarkAllCacheValuesUpToDate(&cache);
context_.SetContinuousState(
context_.get_continuous_state_vector().CopyToVector());
CheckAllCacheValuesUpToDateExcept(cache, xc_dependent);
// Modify time and continuous state together.
std::set<CacheIndex> t_and_xc_dependent(xc_dependent);
t_and_xc_dependent.insert(depends[internal::kTimeTicket]);
MarkAllCacheValuesUpToDate(&cache);
context_.SetTimeAndContinuousState(
context_.get_time() + 1.,
context_.get_continuous_state_vector().CopyToVector());
CheckAllCacheValuesUpToDateExcept(cache, t_and_xc_dependent);
context_.SetTime(1.);
MarkAllCacheValuesUpToDate(&cache);
VectorBase<double>& xc1 =
context_.SetTimeAndGetMutableContinuousStateVector(2.);
CheckAllCacheValuesUpToDateExcept(cache, t_and_xc_dependent);
EXPECT_EQ(context_.get_time(), 2.);
EXPECT_EQ(&xc1, &context_.get_continuous_state_vector());
std::set<CacheIndex> t_and_q_dependent(q_dependent);
t_and_q_dependent.insert(depends[internal::kTimeTicket]);
MarkAllCacheValuesUpToDate(&cache);
VectorBase<double>& q1 = context_.SetTimeAndGetMutableQVector(3.);
CheckAllCacheValuesUpToDateExcept(cache, t_and_q_dependent);
EXPECT_EQ(context_.get_time(), 3.);
EXPECT_EQ(&q1, &context_.get_continuous_state().get_generalized_position());
MarkAllCacheValuesUpToDate(&cache);
context_.SetTimeAndNoteContinuousStateChange(4.);
CheckAllCacheValuesUpToDateExcept(cache, t_and_xc_dependent);
EXPECT_EQ(context_.get_time(), 4.);
MarkAllCacheValuesUpToDate(&cache);
context_.NoteContinuousStateChange();
CheckAllCacheValuesUpToDateExcept(cache, xc_dependent);
MarkAllCacheValuesUpToDate(&cache);
VectorBase<double>* v1{};
VectorBase<double>* z1{};
std::tie(v1, z1) = context_.GetMutableVZVectors();
CheckAllCacheValuesUpToDateExcept(cache, vz_dependent);
EXPECT_EQ(v1, &context_.get_continuous_state().get_generalized_velocity());
EXPECT_EQ(z1, &context_.get_continuous_state().get_misc_continuous_state());
// Modify discrete state).
const std::set<CacheIndex> xd_dependent
{depends[internal::kXdTicket],
depends[internal::kXTicket],
depends[internal::kConfigurationTicket],
depends[internal::kKinematicsTicket],
depends[internal::kAllSourcesExceptInputPortsTicket],
depends[internal::kAllSourcesTicket]};
MarkAllCacheValuesUpToDate(&cache);
context_.get_mutable_discrete_state();
CheckAllCacheValuesUpToDateExcept(cache, xd_dependent);
MarkAllCacheValuesUpToDate(&cache);
context_.get_mutable_discrete_state(DiscreteStateIndex(0));
CheckAllCacheValuesUpToDateExcept(cache, xd_dependent);
const Vector1d xd0_val(2.);
const Eigen::Vector2d xd1_val(3., 4.);
// SetDiscreteState(group) should be more discerning but currently invalidates
// dependents of all groups when only one changes.
MarkAllCacheValuesUpToDate(&cache);
context_.SetDiscreteState(DiscreteStateIndex(0), xd0_val);
CheckAllCacheValuesUpToDateExcept(cache, xd_dependent);
MarkAllCacheValuesUpToDate(&cache);
context_.SetDiscreteState(DiscreteStateIndex(1), xd1_val);
CheckAllCacheValuesUpToDateExcept(cache, xd_dependent);
// Modify abstract state.
const std::set<CacheIndex> xa_dependent
{depends[internal::kXaTicket],
depends[internal::kXTicket],
depends[internal::kConfigurationTicket],
depends[internal::kKinematicsTicket],
depends[internal::kAllSourcesExceptInputPortsTicket],
depends[internal::kAllSourcesTicket]};
MarkAllCacheValuesUpToDate(&cache);
context_.get_mutable_abstract_state();
CheckAllCacheValuesUpToDateExcept(cache, xa_dependent);
MarkAllCacheValuesUpToDate(&cache);
context_.get_mutable_abstract_state<int>(AbstractStateIndex(0));
CheckAllCacheValuesUpToDateExcept(cache, xa_dependent);
MarkAllCacheValuesUpToDate(&cache);
context_.SetAbstractState(AbstractStateIndex(0), 5); // <int> inferred.
CheckAllCacheValuesUpToDateExcept(cache, xa_dependent);
// Modify parameters.
const std::set<CacheIndex> pn_dependent
{depends[internal::kPnTicket],
depends[internal::kConfigurationTicket],
depends[internal::kKinematicsTicket],
depends[internal::kAllParametersTicket],
depends[internal::kAllSourcesExceptInputPortsTicket],
depends[internal::kAllSourcesTicket]};
const std::set<CacheIndex> pa_dependent
{depends[internal::kPaTicket],
depends[internal::kConfigurationTicket],
depends[internal::kKinematicsTicket],
depends[internal::kAllParametersTicket],
depends[internal::kAllSourcesExceptInputPortsTicket],
depends[internal::kAllSourcesTicket]};
std::set<CacheIndex> p_dependent(pn_dependent);
p_dependent.insert(depends[internal::kPaTicket]);
MarkAllCacheValuesUpToDate(&cache);
context_.get_mutable_numeric_parameter(NumericParameterIndex(0));
CheckAllCacheValuesUpToDateExcept(cache, pn_dependent);
MarkAllCacheValuesUpToDate(&cache);
context_.get_mutable_abstract_parameter(AbstractParameterIndex(0));
CheckAllCacheValuesUpToDateExcept(cache, pa_dependent);
MarkAllCacheValuesUpToDate(&cache);
context_.get_mutable_parameters();
CheckAllCacheValuesUpToDateExcept(cache, p_dependent);
// Modify an input port.
FixedInputPortValue* port_value =
context_.MaybeGetMutableFixedInputPortValue(InputPortIndex(0));
ASSERT_NE(port_value, nullptr);
MarkAllCacheValuesUpToDate(&cache);
port_value->GetMutableData();
CheckAllCacheValuesUpToDateExcept(cache,
{depends[internal::kAllInputPortsTicket],
depends[internal::kAllSourcesTicket]});
}
// Verify that safe Set() sugar for modifying state variables works. Cache
// invalidation is tested separately above; this just checks values.
TEST_F(LeafContextTest, TestStateSettingSugar) {
const Vector1d xd0_init{128.}, xd0_new{1.};
const Eigen::Vector2d xd1_init{256., 512.}, xd1_new{2., 3.};
EXPECT_EQ(context_.get_discrete_state(0).get_value(), xd0_init);
EXPECT_EQ(context_.get_discrete_state(1).get_value(), xd1_init);
context_.SetDiscreteState(0, xd0_new);
EXPECT_EQ(context_.get_discrete_state(0).get_value(), xd0_new);
context_.SetDiscreteState(1, xd1_new);
EXPECT_EQ(context_.get_discrete_state(1).get_value(), xd1_new);
// With two groups the abbreviated signature isn't allowed.
DRAKE_EXPECT_THROWS_MESSAGE(
context_.SetDiscreteState(xd0_new),
".*SetDiscreteState.*: expected exactly 1.*but there were 2 groups.*");
// Check the signature that takes a DiscreteValues argument.
// Make a compatible DiscreteValues object.
std::unique_ptr<DiscreteValues<double>> xd_clone =
context_.get_discrete_state().Clone();
const Vector1d val0{-4.};
const Eigen::Vector2d val1{5., 6.};
xd_clone->get_mutable_value(0) = val0;
xd_clone->get_mutable_value(1) = val1;
context_.SetDiscreteState(*xd_clone);
EXPECT_EQ(context_.get_discrete_state(0).get_value(), val0);
EXPECT_EQ(context_.get_discrete_state(1).get_value(), val1);
// Change to just one group, then the single-argument signature works.
std::vector<std::unique_ptr<BasicVector<double>>> xd;
const Eigen::VectorXd xd_init = Eigen::Vector3d{1., 2., 3.};
const Eigen::Vector3d xd_new{4., 5., 6.};
xd.push_back(std::make_unique<BasicVector<double>>(xd_init));
context_.init_discrete_state(
std::make_unique<DiscreteValues<double>>(std::move(xd)));
EXPECT_EQ(context_.get_discrete_state_vector().get_value(), xd_init);
context_.SetDiscreteState(xd_new);
EXPECT_EQ(context_.get_discrete_state_vector().get_value(), xd_new);
EXPECT_EQ(context_.get_abstract_state<int>(0), 42);
context_.SetAbstractState(0, 29); // Template arg is inferred.
EXPECT_EQ(context_.get_abstract_state<int>(0), 29);
// Type mismatch should be caught.
DRAKE_EXPECT_THROWS_MESSAGE(
context_.SetAbstractState(0, std::string("hello")),
".*cast to.*std::string.*failed.*static type.*int.*");
}
// Check that hidden internal functionality needed by Simulator::Initialize()
// and CalcNextUpdateTime() is functional in the Context.
TEST_F(LeafContextTest, PerturbTime) {
// This is a hidden method. Should set time to perturbed_time but current
// time to true_time.
const double true_time = 2.;
const double perturbed_time = true_time - 1e-14;
ASSERT_NE(perturbed_time, true_time); // Watch for fatal roundoff.
context_.PerturbTime(perturbed_time, true_time);
EXPECT_EQ(context_.get_time(), perturbed_time);
EXPECT_EQ(*context_.get_true_time(), true_time); // This is an std::optional.
// Setting time the normal way clears the "true time".
context_.SetTime(1.);
EXPECT_FALSE(context_.get_true_time());
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/continuous_state_test.cc | // This test covers ContinuousState (used directly by LeafContexts) and its
// derived class DiagramContinuousState (for DiagramContexts).
#include "drake/systems/framework/continuous_state.h"
#include <memory>
#include <Eigen/Dense>
#include <gtest/gtest.h>
#include "drake/common/fmt_eigen.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/diagram_continuous_state.h"
#include "drake/systems/framework/test_utilities/my_vector.h"
#include "drake/systems/framework/vector_base.h"
using Eigen::Vector2d;
using Eigen::Vector3d;
using Eigen::Vector4d;
using Eigen::VectorXd;
namespace drake {
namespace systems {
namespace {
typedef Eigen::Matrix<double, 5, 1> Vector5d;
constexpr int kPositionLength = 2;
constexpr int kVelocityLength = 1;
constexpr int kMiscLength = 1;
constexpr int kLength = kPositionLength + kVelocityLength + kMiscLength;
template <typename T>
std::unique_ptr<VectorBase<T>> MakeSomeVector() {
return BasicVector<T>::Make({1, 2, 3, 4});
}
// Tests for ContinuousState.
class ContinuousStateTest : public ::testing::Test {
protected:
void SetUp() override {
continuous_state_ = MakeSomeState<double>();
}
template <typename T>
std::unique_ptr<ContinuousState<T>> MakeSomeState() {
auto result = std::make_unique<ContinuousState<T>>(
MakeSomeVector<T>(), kPositionLength, kVelocityLength, kMiscLength);
result->set_system_id(system_id_);
return result;
}
template <typename T>
std::unique_ptr<ContinuousState<T>> MakeNanState() {
auto result = std::make_unique<ContinuousState<T>>(
std::make_unique<BasicVector<T>>(kLength),
kPositionLength, kVelocityLength, kMiscLength);
result->set_system_id(system_id_);
return result;
}
const internal::SystemId system_id_ = internal::SystemId::get_new_id();
std::unique_ptr<ContinuousState<double>> continuous_state_;
};
TEST_F(ContinuousStateTest, Access) {
EXPECT_EQ(kLength, continuous_state_->size());
EXPECT_EQ(kPositionLength,
continuous_state_->get_generalized_position().size());
EXPECT_EQ(1, continuous_state_->get_generalized_position()[0]);
EXPECT_EQ(2, continuous_state_->get_generalized_position()[1]);
EXPECT_EQ(kVelocityLength,
continuous_state_->get_generalized_velocity().size());
EXPECT_EQ(3, continuous_state_->get_generalized_velocity()[0]);
EXPECT_EQ(kMiscLength, continuous_state_->get_misc_continuous_state().size());
EXPECT_EQ(4, continuous_state_->get_misc_continuous_state()[0]);
}
TEST_F(ContinuousStateTest, Mutation) {
continuous_state_->get_mutable_generalized_position()[0] = 5;
continuous_state_->get_mutable_generalized_position()[1] = 6;
continuous_state_->get_mutable_generalized_velocity()[0] = 7;
continuous_state_->get_mutable_misc_continuous_state()[0] = 8;
EXPECT_EQ(5, continuous_state_->get_vector()[0]);
EXPECT_EQ(6, continuous_state_->get_vector()[1]);
EXPECT_EQ(7, continuous_state_->get_vector()[2]);
EXPECT_EQ(8, continuous_state_->get_vector()[3]);
}
// Tests that the continuous state can be indexed as an array.
TEST_F(ContinuousStateTest, ArrayOperator) {
(*continuous_state_)[1] = 42;
EXPECT_EQ(42, continuous_state_->get_generalized_position()[1]);
EXPECT_EQ(4, (*continuous_state_)[3]);
}
TEST_F(ContinuousStateTest, OutOfBoundsAccess) {
EXPECT_THROW(continuous_state_->get_generalized_position().GetAtIndex(2),
std::exception);
EXPECT_THROW(
continuous_state_->get_mutable_generalized_velocity().SetAtIndex(1, 42),
std::exception);
}
// Tests that std::out_of_range is thrown if the component dimensions do not
// sum to the state vector dimension.
TEST_F(ContinuousStateTest, OutOfBoundsConstruction) {
EXPECT_THROW(
continuous_state_.reset(new ContinuousState<double>(
MakeSomeVector<double>(),
kPositionLength, kVelocityLength, kMiscLength + 1)),
std::out_of_range);
}
// Tests that std::logic_error is thrown if there are more velocity than
// position variables.
TEST_F(ContinuousStateTest, MoreVelocityThanPositionVariables) {
EXPECT_THROW(
continuous_state_.reset(new ContinuousState<double>(
MakeSomeVector<double>(),
1 /* num_q */, 2 /* num_v */, kMiscLength + 1)),
std::out_of_range);
}
TEST_F(ContinuousStateTest, SetFrom) {
const auto expected_double = MakeSomeState<double>();
const auto expected_autodiff = MakeSomeState<AutoDiffXd>();
const auto expected_symbolic = MakeSomeState<symbolic::Expression>();
// Check ContinuousState<T>::SetFrom<T> for all T's.
auto actual_double = MakeNanState<double>();
auto actual_autodiff = MakeNanState<AutoDiffXd>();
auto actual_symbolic = MakeNanState<symbolic::Expression>();
actual_double->SetFrom(*expected_double);
actual_autodiff->SetFrom(*expected_autodiff);
actual_symbolic->SetFrom(*expected_symbolic);
EXPECT_EQ(actual_double->CopyToVector(), expected_double->CopyToVector());
EXPECT_EQ(actual_autodiff->CopyToVector(), expected_autodiff->CopyToVector());
EXPECT_EQ(actual_symbolic->CopyToVector(), expected_symbolic->CopyToVector());
// Check ContinuousState<double>::SetFrom<U> for U=AutoDiff and U=Expression.
actual_double = MakeNanState<double>();
actual_double->SetFrom(*expected_autodiff);
EXPECT_EQ(actual_double->CopyToVector(), expected_double->CopyToVector());
actual_double = MakeNanState<double>();
actual_double->SetFrom(*expected_symbolic);
EXPECT_EQ(actual_double->CopyToVector(), expected_double->CopyToVector());
// If there was an unbound variable, we get an exception.
auto unbound_symbolic = expected_symbolic->Clone();
unbound_symbolic->get_mutable_vector()[0] = symbolic::Variable("q");
DRAKE_EXPECT_THROWS_MESSAGE(
actual_double->SetFrom(*unbound_symbolic),
".*variable q.*\n*");
// Check ContinuousState<AutoDiff>::SetFrom<U> for U=double and U=Expression.
actual_autodiff = MakeNanState<AutoDiffXd>();
actual_autodiff->SetFrom(*expected_double);
EXPECT_EQ(actual_autodiff->CopyToVector(), expected_autodiff->CopyToVector());
actual_autodiff = MakeNanState<AutoDiffXd>();
actual_autodiff->SetFrom(*expected_symbolic);
EXPECT_EQ(actual_autodiff->CopyToVector(), expected_autodiff->CopyToVector());
// Check ContinuousState<Expression>::SetFrom<U> for U=double and U=AutoDiff.
actual_symbolic = MakeNanState<symbolic::Expression>();
actual_symbolic->SetFrom(*expected_double);
EXPECT_EQ(actual_symbolic->CopyToVector(), expected_symbolic->CopyToVector());
actual_symbolic = MakeNanState<symbolic::Expression>();
actual_symbolic->SetFrom(*expected_autodiff);
EXPECT_EQ(actual_symbolic->CopyToVector(), expected_symbolic->CopyToVector());
// Check ContinuousState<AutoDiff>::SetFrom<AutoDiff> preserves derivatives.
auto fancy_autodiff = MakeSomeState<AutoDiffXd>();
auto& fancy_vector = fancy_autodiff->get_mutable_vector();
fancy_vector[0].derivatives() = Eigen::VectorXd::Constant(4, -1.0);
fancy_vector[1].derivatives() = Eigen::VectorXd::Constant(4, -2.0);
fancy_vector[2].derivatives() = Eigen::VectorXd::Constant(4, -3.0);
fancy_vector[3].derivatives() = Eigen::VectorXd::Constant(4, -4.0);
actual_autodiff = MakeNanState<AutoDiffXd>();
actual_autodiff->SetFrom(*fancy_autodiff);
EXPECT_EQ(actual_autodiff->CopyToVector(), expected_autodiff->CopyToVector());
const auto& actual_vector = actual_autodiff->get_vector();
EXPECT_EQ(actual_vector[0].derivatives(), fancy_vector[0].derivatives());
EXPECT_EQ(actual_vector[1].derivatives(), fancy_vector[1].derivatives());
EXPECT_EQ(actual_vector[2].derivatives(), fancy_vector[2].derivatives());
EXPECT_EQ(actual_vector[3].derivatives(), fancy_vector[3].derivatives());
}
TEST_F(ContinuousStateTest, SetFromException) {
const auto dut = MakeSomeState<double>();
const auto wrong = std::make_unique<ContinuousState<double>>(
MakeSomeVector<double>(),
kPositionLength - 1, kVelocityLength, kMiscLength + 1);
EXPECT_THROW(dut->SetFrom(*wrong), std::exception);
}
// This is testing the default implementation of Clone() for when a
// ContinuousState is used as a concrete object. A DiagramContinuousState has
// to do more but that is not tested here.
TEST_F(ContinuousStateTest, Clone) {
auto clone_ptr = continuous_state_->Clone();
const ContinuousState<double>& clone = *clone_ptr;
EXPECT_EQ(clone.get_system_id(), system_id_);
EXPECT_EQ(1, clone[0]);
EXPECT_EQ(2, clone[1]);
EXPECT_EQ(3, clone[2]);
EXPECT_EQ(4, clone[3]);
// Make sure underlying BasicVector type, and 2nd-order structure,
// is preserved in the clone.
ContinuousState<double> state(MyVector3d::Make(1.25, 1.5, 1.75),
2, 1, 0);
clone_ptr = state.Clone();
const ContinuousState<double>& clone2 = *clone_ptr;
EXPECT_EQ(clone2[0], 1.25);
EXPECT_EQ(clone2[1], 1.5);
EXPECT_EQ(clone2[2], 1.75);
EXPECT_EQ(clone2.num_q(), 2);
EXPECT_EQ(clone2.num_v(), 1);
EXPECT_EQ(clone2.num_z(), 0);
EXPECT_EQ(clone2.get_generalized_position()[0], 1.25);
EXPECT_EQ(clone2.get_generalized_position()[1], 1.5);
EXPECT_EQ(clone2.get_generalized_velocity()[0], 1.75);
auto vector = dynamic_cast<const MyVector3d*>(&clone2.get_vector());
ASSERT_NE(vector, nullptr);
EXPECT_EQ((*vector)[0], 1.25);
EXPECT_EQ((*vector)[1], 1.5);
EXPECT_EQ((*vector)[2], 1.75);
}
// Tests ability to stream a ContinuousState vector into a string.
TEST_F(ContinuousStateTest, StringStream) {
std::stringstream s;
s << "hello " << continuous_state_->get_vector() << " world";
const std::string expected =
fmt::format("hello {} world",
fmt_eigen(continuous_state_->CopyToVector().transpose()));
EXPECT_EQ(s.str(), expected);
}
// Tests for DiagramContinousState.
class DiagramContinuousStateTest : public ::testing::Test {
protected:
void SetUp() override {
state0_.reset(
new ContinuousState<double>(MyVector3d::Make(1, 2, 3), 1, 1, 1));
state1_.reset(new ContinuousState<double>(
BasicVector<double>::Make(4, 5, 6, 7, 8), 2, 1, 2));
state2_.reset(new ContinuousState<double>(
BasicVector<double>::Make(10, 11), 0, 0, 2));
state3_.reset(new ContinuousState<double>(
BasicVector<double>::Make(-1, -2, -3, -4), 2, 1, 1));
state0_->set_system_id(internal::SystemId::get_new_id());
state1_->set_system_id(internal::SystemId::get_new_id());
state2_->set_system_id(internal::SystemId::get_new_id());
state3_->set_system_id(internal::SystemId::get_new_id());
// Expected contents, with expected number of q/v/z variables.
// unowned 3q 2v 5z
// state0 q v z 1 2 3
// state1 2q v 2z 4,5 6 7,8
// state2 2z 10,11
unowned_.reset(new DiagramContinuousState<double>(
{&*state0_, &*state1_, &*state2_}));
unowned_->set_system_id(internal::SystemId::get_new_id());
// root_unowned 5q 3v 6z
// state3 2q v z -1,-2 -3 -4
// unowned 3q 2v 5z 1,4,5 2,6 3,7,8,10,11
// state0
// state1
// state2
root_unowned_.reset(
new DiagramContinuousState<double>({&*state3_, &*unowned_}));
root_unowned_->set_system_id(internal::SystemId::get_new_id());
std::vector<std::unique_ptr<ContinuousState<double>>> copies;
copies.emplace_back(state3_->Clone());
copies.emplace_back(unowned_->Clone());
copies.emplace_back(state1_->Clone());
// root_owned 7q 4v 8z
// state3 (copy) 2q v z -1,-2 -3 -4
// unowned (copy) 3q 2v 5z 1,4,5 2,6 3,7,8,10,11
// state0 (copy)
// state1 (copy)
// state2 (copy)
// state1 (copy) 2q v 2z 4,5 6 7,8
root_owned_.reset(new DiagramContinuousState<double>(std::move(copies)));
root_owned_->set_system_id(internal::SystemId::get_new_id());
}
std::unique_ptr<ContinuousState<double>> state0_, state1_, state2_, state3_;
// These are created using the "unowned" constructor.
std::unique_ptr<DiagramContinuousState<double>> unowned_, root_unowned_;
// This is created using the "owned" constructor.
std::unique_ptr<DiagramContinuousState<double>> root_owned_;
};
// See above for number of substates and their identities.
TEST_F(DiagramContinuousStateTest, Substates) {
EXPECT_EQ(unowned_->num_substates(), 3);
EXPECT_EQ(root_unowned_->num_substates(), 2);
EXPECT_EQ(root_owned_->num_substates(), 3);
EXPECT_EQ(&unowned_->get_substate(0), &*state0_);
EXPECT_EQ(&unowned_->get_substate(1), &*state1_);
EXPECT_EQ(&unowned_->get_substate(2), &*state2_);
EXPECT_EQ(&root_unowned_->get_substate(0), &*state3_);
EXPECT_EQ(&root_unowned_->get_substate(1), &*unowned_);
// The root_owned substates must be copies.
EXPECT_NE(&root_owned_->get_substate(0), &*state3_);
EXPECT_NE(&root_owned_->get_substate(1), &*unowned_);
EXPECT_NE(&root_owned_->get_substate(2), &*state1_);
// Just make sure get_mutable_substate() exists and works.
EXPECT_EQ(&unowned_->get_mutable_substate(1), &*state1_);
}
// See above for expected dimensions.
TEST_F(DiagramContinuousStateTest, Counts) {
EXPECT_EQ(unowned_->size(), 10);
EXPECT_EQ(unowned_->num_q(), 3);
EXPECT_EQ(unowned_->num_v(), 2);
EXPECT_EQ(unowned_->num_z(), 5);
EXPECT_EQ(root_unowned_->size(), 14);
EXPECT_EQ(root_unowned_->num_q(), 5);
EXPECT_EQ(root_unowned_->num_v(), 3);
EXPECT_EQ(root_unowned_->num_z(), 6);
EXPECT_EQ(root_owned_->size(), 19);
EXPECT_EQ(root_owned_->num_q(), 7);
EXPECT_EQ(root_owned_->num_v(), 4);
EXPECT_EQ(root_owned_->num_z(), 8);
}
// See above for expected values.
TEST_F(DiagramContinuousStateTest, Values) {
// Asking for the whole value x treats all substates as whole values xi
// so the ordering is x={x0,x1,x2, ...} which means the q's v's and z's
// are all mixed together rather than grouped.
const VectorXd unowned_value = unowned_->CopyToVector();
VectorXd unowned_expected(10);
unowned_expected << 1, 2, 3, // state0
4, 5, 6, 7, 8, // state1
10, 11; // state2
EXPECT_EQ(unowned_value, unowned_expected);
// Asking for individual partitions groups like variables together.
const VectorXd unowned_q =
unowned_->get_generalized_position().CopyToVector();
const VectorXd unowned_v =
unowned_->get_generalized_velocity().CopyToVector();
const VectorXd unowned_z =
unowned_->get_misc_continuous_state().CopyToVector();
EXPECT_EQ(unowned_q, Vector3d(1, 4, 5));
EXPECT_EQ(unowned_v, Vector2d(2, 6));
Vector5d unowned_z_expected;
unowned_z_expected << 3, 7, 8, 10, 11;
EXPECT_EQ(unowned_z, unowned_z_expected);
const VectorXd root_unowned_value = root_unowned_->CopyToVector();
VectorXd root_unowned_expected(14);
root_unowned_expected << -1, -2, -3, -4, // state3
1, 2, 3, 4, 5, 6, 7, 8, 10, 11; // unowned
EXPECT_EQ(root_unowned_value, root_unowned_expected);
const VectorXd root_unowned_q =
root_unowned_->get_generalized_position().CopyToVector();
const VectorXd root_unowned_v =
root_unowned_->get_generalized_velocity().CopyToVector();
const VectorXd root_unowned_z =
root_unowned_->get_misc_continuous_state().CopyToVector();
Vector5d root_unowned_q_expected;
root_unowned_q_expected << -1, -2, 1, 4, 5;
EXPECT_EQ(root_unowned_q, root_unowned_q_expected);
EXPECT_EQ(root_unowned_v, Vector3d(-3, 2, 6));
Vector6d root_unowned_z_expected;
root_unowned_z_expected << -4, 3, 7, 8, 10, 11;
EXPECT_EQ(root_unowned_z, root_unowned_z_expected);
const VectorXd root_owned_value = root_owned_->CopyToVector();
VectorXd root_owned_expected(19);
root_owned_expected << -1, -2, -3, -4, // state3
1, 2, 3, 4, 5, 6, 7, 8, 10, 11, // unowned
4, 5, 6, 7, 8; // state1
EXPECT_EQ(root_owned_value, root_owned_expected);
const VectorXd root_owned_q =
root_owned_->get_generalized_position().CopyToVector();
const VectorXd root_owned_v =
root_owned_->get_generalized_velocity().CopyToVector();
const VectorXd root_owned_z =
root_owned_->get_misc_continuous_state().CopyToVector();
VectorXd root_owned_q_expected(7);
root_owned_q_expected << -1, -2, 1, 4, 5, 4, 5;
EXPECT_EQ(root_owned_q, root_owned_q_expected);
EXPECT_EQ(root_owned_v, Vector4d(-3, 2, 6, 6));
VectorXd root_owned_z_expected(8);
root_owned_z_expected << -4, 3, 7, 8, 10, 11, 7, 8;
EXPECT_EQ(root_owned_z, root_owned_z_expected);
}
// Check that Clone() results in new memory being allocated by modifying that
// memory and observing that it doesn't change the original. We'll assume that
// means the new DiagramContinuousState has ownership. (We're not checking for
// memory leaks here -- that's for Valgrind.)
TEST_F(DiagramContinuousStateTest, Clone) {
// unowned is singly-nested, root_unowned is doubly-nested.
auto clone_of_unowned = unowned_->Clone();
auto clone_of_root_unowned = root_unowned_->Clone();
// Show that values got copied.
for (int i=0; i < unowned_->size(); ++i)
EXPECT_EQ((*clone_of_unowned)[i], (*unowned_)[i]);
for (int i=0; i < root_unowned_->size(); ++i)
EXPECT_EQ((*clone_of_root_unowned)[i], (*root_unowned_)[i]);
(*state0_)[1] = 99; // Should affect unowned but not the clones (was 2).
EXPECT_EQ((*unowned_)[1], 99);
EXPECT_EQ((*clone_of_unowned)[1], 2);
EXPECT_EQ((*root_unowned_)[5], 99);
EXPECT_EQ((*clone_of_root_unowned)[5], 2);
}
// Check that Clone() preserves the system_id markers.
TEST_F(DiagramContinuousStateTest, CloneSystemId) {
auto clone_of_unowned = unowned_->Clone();
auto clone_of_root_unowned = root_unowned_->Clone();
EXPECT_EQ(clone_of_unowned->get_system_id(),
unowned_->get_system_id());
for (int i = 0; i < unowned_->num_substates(); ++i) {
EXPECT_EQ(clone_of_unowned->get_substate(i).get_system_id(),
unowned_->get_substate(i).get_system_id());
}
EXPECT_EQ(clone_of_root_unowned->get_system_id(),
root_unowned_->get_system_id());
for (int i = 0; i < root_unowned_->num_substates(); ++i) {
EXPECT_EQ(clone_of_root_unowned->get_substate(i).get_system_id(),
root_unowned_->get_substate(i).get_system_id());
}
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/cache_entry_test.cc | #include "drake/systems/framework/cache_entry.h"
#include "drake/common/test_utilities/expect_no_throw.h"
// Tests the System (const) side of caching, which consists of a CacheEntry
// objects that can be provided automatically or defined by users. When a
// Context is created, each CacheEntry in a System is provided with a
// CacheEntryValue in its corresponding Context.
//
// Here we test that the DeclareCacheEntry() API works correctly, that
// the resulting CacheEntry objects behave properly, and that they are
// assigned appropriate CacheEntryValue objects in the Context. A lot of
// the testing here is to make sure dependencies are being properly handled.
// The Context side tests are provided in cache_test.cc; we are testing the
// System side here.
#include <memory>
#include <stdexcept>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/text_logging.h"
#include "drake/systems/framework/system_base.h"
#include "drake/systems/framework/test_utilities/my_vector.h"
#include "drake/systems/framework/test_utilities/pack_value.h"
using std::string;
using Eigen::Vector3d;
namespace drake {
namespace systems {
namespace {
// Free functions suitable for defining cache entries.
auto Alloc1 = []() { return AbstractValue::Make<int>(1); };
auto Alloc3 = []() { return AbstractValue::Make<int>(3); };
auto Calc99 = [](const ContextBase&, AbstractValue* result) {
result->set_value(99);
};
// This one is fatally flawed since null is not allowed.
auto AllocNull = []() {
return std::unique_ptr<AbstractValue>();
};
// This is so we can use the contained cache & dependency graph objects.
class MyContextBase : public ContextBase {
public:
MyContextBase() = default;
MyContextBase(const MyContextBase&) = default;
private:
std::unique_ptr<ContextBase> DoCloneWithoutPointers() const final {
return std::make_unique<MyContextBase>(*this);
}
};
// Dependency chains for cache entries here:
//
// +-----------+ +---------------+
// | time +--->| string_entry +----------+
// +-+---------+ +---------------+ |
// | |
// | +------+ +------v-------+
// | | xc +------------------------> vector_entry +
// | +--+---+ +--------------+
// | |
// +-v-----v---+ +--------------+ +--------------+
// |all_sources+--->| entry0 +----> entry1 +
// +-----------+ +------+-------+ +------+-------+
// | |
// | +------v-------+
// +------------> entry2,3 +
// +--------------+
//
// Note that this diagram depicts DependencyTracker ("tracker") objects, not
// cache entries. The boxes labeled "entry" correspond to cache entries; time,
// xc, and all_sources are other dependency trackers that do not correspond to
// any cache entries.
//
// The dependencies for all_sources are set up automatically during
// Context construction; the others are set explicitly here.
//
// Value types:
// int: entry0,1,2,3
// string: string_entry
// MyVector3: vector_entry
class MySystemBase final : public SystemBase {
public:
// Uses all of DeclareCacheEntry() variants at least once.
MySystemBase() {
// Use the most general overload, taking free functions.
// Unspecified prerequisites should default to all_sources_ticket().
entry0_ = &DeclareCacheEntry("entry0", ValueProducer(Alloc3, Calc99));
// Same overload, but now using prerequisites.
entry1_ = &DeclareCacheEntry("entry1", ValueProducer(Alloc1, Calc99),
{entry0_->ticket()});
// Use the overload that takes a model value and member calculator.
entry2_ = &DeclareCacheEntry("entry2", 2, &MySystemBase::CalcInt98,
{entry0_->ticket(), entry1_->ticket()});
// Use the overload that takes just a member calculator. The model value
// will be value-initialized (using an `int{}` for this one).
entry3_ = &DeclareCacheEntry("entry3",
&MySystemBase::CalcInt98,
{entry0_->ticket(), entry1_->ticket()});
// Ditto but using a string{} defaulted model value.
string_entry_ = &DeclareCacheEntry("string thing",
&MySystemBase::CalcString,
{time_ticket()});
// Ditto but using a MyVector3d{} defaulted model value.
vector_entry_ =
&DeclareCacheEntry("vector thing", MyVector3d(Vector3d(1., 2., 3.)),
&MySystemBase::CalcMyVector3,
{xc_ticket(), string_entry_->ticket()});
set_name("cache_entry_test_system");
// We'll make entry3 disabled by default; everything else is enabled.
entry3_->disable_caching_by_default();
EXPECT_EQ(num_cache_entries(), 6);
EXPECT_EQ(GetSystemName(), "cache_entry_test_system");
EXPECT_FALSE(entry2_->is_disabled_by_default());
EXPECT_TRUE(entry3_->is_disabled_by_default());
}
const CacheEntry& entry0() const { return *entry0_; }
const CacheEntry& entry1() const { return *entry1_; }
const CacheEntry& entry2() const { return *entry2_; }
const CacheEntry& entry3() const { return *entry3_; }
const CacheEntry& string_entry() const { return *string_entry_; }
const CacheEntry& vector_entry() const { return *vector_entry_; }
// For use as an allocator.
int MakeInt1() const { return 1; }
// For use as a cache entry calculator.
void CalcInt98(const MyContextBase& my_context, int* out) const {
*out = 98;
}
void CalcString(const MyContextBase& my_context, string* out) const {
*out = "calculated_result";
}
void CalcMyVector3(const MyContextBase& my_context, MyVector3d* out) const {
out->set_value(Vector3d(3., 2., 1.));
}
using SystemBase::DeclareCacheEntry;
private:
std::unique_ptr<ContextBase> DoAllocateContext() const final {
auto context = std::make_unique<MyContextBase>();
this->InitializeContextBase(&*context);
return context;
}
std::function<void(const AbstractValue&)> MakeFixInputPortTypeChecker(
InputPortIndex /* unused */) const final {
return {};
}
std::multimap<int, int> GetDirectFeedthroughs() const final {
throw std::logic_error("GetDirectFeedthroughs is not implemented");
}
CacheEntry* entry0_{};
CacheEntry* entry1_{};
CacheEntry* entry2_{};
CacheEntry* entry3_{};
CacheEntry* string_entry_{};
CacheEntry* vector_entry_{};
};
// An allocator is not permitted to return null. That should be caught when
// we allocate a Context.
GTEST_TEST(CacheEntryAllocTest, BadAllocGetsCaught) {
MySystemBase system;
system.DeclareCacheEntry("bad alloc entry",
ValueProducer(AllocNull, Calc99),
{system.nothing_ticket()});
// Error messages should include the System name and type, cache entry
// description, and the specific message. The first three are boilerplate so
// we'll just check once here; everywhere else we'll just check for the
// right message.
DRAKE_EXPECT_THROWS_MESSAGE(system.AllocateContext(),
".*cache_entry_test_system"
".*MySystemBase"
".*bad alloc entry"
".*allocator returned a nullptr.*");
}
// Leaving out prerequisites altogether defaults to all sources and is fine
// (that default is tested for entry0 in SetUp() below). Explicitly specifying
// an empty list is forbidden -- the proper syntax for saying there are no
// dependencies is `{nothing_ticket()}`.
GTEST_TEST(CacheEntryAllocTest, EmptyPrerequisiteListForbidden) {
MySystemBase system;
const ValueProducer alloc3_calc99(Alloc3, Calc99);
DRAKE_EXPECT_NO_THROW(
system.DeclareCacheEntry("default prerequisites", alloc3_calc99));
DRAKE_EXPECT_NO_THROW(
system.DeclareCacheEntry(
"no prerequisites", alloc3_calc99, {system.nothing_ticket()}));
DRAKE_EXPECT_THROWS_MESSAGE(
system.DeclareCacheEntry("empty prerequisites", alloc3_calc99, {}),
".*[Cc]annot create.*empty prerequisites.*nothing_ticket.*");
}
GTEST_TEST(CacheEntryAllocTest, DetectsDefaultPrerequisites) {
MySystemBase system;
const ValueProducer alloc3_calc99(Alloc3, Calc99);
const CacheEntry& default_prereqs =
system.DeclareCacheEntry("default prerequisites", alloc3_calc99);
EXPECT_TRUE(default_prereqs.has_default_prerequisites());
// TODO(sherm1) Currently we treat default prerequisites and explicit
// all_sources_ticket() the same. That's not desirable though, just a
// limitation. Ideally explicit specification of anything should be considered
// non-default. Replace this test when that's fixed.
const CacheEntry& explicit_default_prereqs =
system.DeclareCacheEntry("explicit default prerequisites", alloc3_calc99,
{system.all_sources_ticket()});
EXPECT_TRUE(
explicit_default_prereqs.has_default_prerequisites()); // Not good.
// This specifies exactly the same dependencies as all_sources_ticket() but
// in a way that is clearly non-default.
const CacheEntry& long_form_all_sources_prereqs = system.DeclareCacheEntry(
"long form all sources prerequisites", alloc3_calc99,
{system.all_sources_except_input_ports_ticket(),
system.all_input_ports_ticket()});
EXPECT_FALSE(
long_form_all_sources_prereqs.has_default_prerequisites()); // Good!
const CacheEntry& no_prereqs = system.DeclareCacheEntry(
"no prerequisites", alloc3_calc99, {system.nothing_ticket()});
EXPECT_FALSE(no_prereqs.has_default_prerequisites());
const CacheEntry& time_only_prereq = system.DeclareCacheEntry(
"time only prerequisite", alloc3_calc99, {system.time_ticket()});
EXPECT_FALSE(time_only_prereq.has_default_prerequisites());
}
// Allocate a System and Context and provide some convenience methods.
class CacheEntryTest : public ::testing::Test {
protected:
void SetUp() override {
index0_ = entry0().cache_index();
index1_ = entry1().cache_index();
index2_ = entry2().cache_index();
index3_ = entry3().cache_index();
string_index_ = string_entry().cache_index();
vector_index_ = vector_entry().cache_index();
// We left prerequisites unspecified for entry0 -- should have defaulted
// to all_sources.
const DependencyTracker& entry0_tracker = tracker(entry0().cache_index());
EXPECT_EQ(entry0_tracker.prerequisites().size(), 1);
EXPECT_EQ(entry0_tracker.prerequisites()[0],
&context_.get_tracker(system_.all_sources_ticket()));
// Only entry3 should have been created disabled.
EXPECT_FALSE(entry0().is_cache_entry_disabled(context_));
EXPECT_FALSE(entry1().is_cache_entry_disabled(context_));
EXPECT_FALSE(entry2().is_cache_entry_disabled(context_));
EXPECT_TRUE(entry3().is_cache_entry_disabled(context_));
EXPECT_FALSE(string_entry().is_cache_entry_disabled(context_));
EXPECT_FALSE(vector_entry().is_cache_entry_disabled(context_));
EXPECT_TRUE(entry0().is_out_of_date(context_));
EXPECT_TRUE(entry1().is_out_of_date(context_));
EXPECT_TRUE(entry2().is_out_of_date(context_));
EXPECT_TRUE(entry3().is_out_of_date(context_));
EXPECT_TRUE(string_entry().is_out_of_date(context_));
EXPECT_TRUE(vector_entry().is_out_of_date(context_));
// Set the initial values and mark them up to date.
// Make the initial values up to date.
cache_value(index0_).mark_up_to_date();
cache_value(index1_).mark_up_to_date();
cache_value(index2_).mark_up_to_date();
cache_value(index3_).mark_up_to_date();
cache_value(string_index_).mark_up_to_date();
EXPECT_EQ(entry0().GetKnownUpToDate<int>(context_), 3);
EXPECT_EQ(entry1().GetKnownUpToDate<int>(context_), 1);
EXPECT_EQ(entry2().GetKnownUpToDate<int>(context_), 2);
EXPECT_EQ(entry3().GetKnownUpToDate<int>(context_), 0);
EXPECT_EQ(string_entry().GetKnownUpToDate<string>(context_), "");
// Let's change string's initial value. Can't when it's up to date.
DRAKE_EXPECT_THROWS_MESSAGE(
cache_value(string_index_).SetValueOrThrow<string>("initial"),
".*SetValueOrThrow().*current value.*already up to date.*");
cache_value(string_index_).mark_out_of_date();
cache_value(string_index_).SetValueOrThrow<string>("initial");
EXPECT_EQ(cache_value(string_index_).GetValueOrThrow<string>(), "initial");
EXPECT_FALSE(string_entry().is_out_of_date(context_));
// vector_entry still invalid so we can only peek.
DRAKE_EXPECT_THROWS_MESSAGE(
vector_entry().GetKnownUpToDate<MyVector3d>(context_),
".*GetKnownUpToDate().*value out of date.*");
EXPECT_EQ(
cache_value(vector_index_).PeekValueOrThrow<MyVector3d>().get_value(),
Vector3d(1., 2., 3.));
cache_value(vector_index_).set_value(MyVector3d(Vector3d(99., 98., 97.)));
// Everything should be up to date to start out.
EXPECT_FALSE(entry0().is_out_of_date(context_));
EXPECT_FALSE(entry1().is_out_of_date(context_));
EXPECT_FALSE(entry2().is_out_of_date(context_));
EXPECT_FALSE(entry3().is_out_of_date(context_));
EXPECT_FALSE(string_entry().is_out_of_date(context_));
EXPECT_FALSE(vector_entry().is_out_of_date(context_));
}
const CacheEntry& entry0() const { return system_.entry0(); }
const CacheEntry& entry1() const { return system_.entry1(); }
const CacheEntry& entry2() const { return system_.entry2(); }
const CacheEntry& entry3() const { return system_.entry3(); }
const CacheEntry& string_entry() const { return system_.string_entry(); }
const CacheEntry& vector_entry() const { return system_.vector_entry(); }
const DependencyTracker& tracker(CacheIndex index) {
return tracker(cache_value(index).ticket());
}
void invalidate(CacheIndex index) {
static int64_t next_change_event = 1;
const int64_t event = next_change_event++;
cache_value(index).mark_out_of_date();
tracker(index).NoteValueChange(event);
}
const DependencyGraph& graph() {
return context_.get_mutable_dependency_graph();
}
const DependencyTracker& tracker(DependencyTicket dticket) {
return graph().get_tracker(dticket);
}
// Create a System and a Context to match.
MySystemBase system_;
std::unique_ptr<ContextBase> context_base_ = system_.AllocateContext();
MyContextBase& context_ = dynamic_cast<MyContextBase&>(*context_base_);
CacheIndex index0_, index1_, index2_, index3_, index4_, index5_;
CacheIndex string_index_, vector_index_;
private:
CacheEntryValue& cache_value(CacheIndex index) {
return context_.get_mutable_cache().get_mutable_cache_entry_value(index);
}
};
TEST_F(CacheEntryTest, Descriptions) {
EXPECT_EQ(entry0().description(), "entry0");
EXPECT_EQ(entry1().description(), "entry1");
EXPECT_EQ(entry2().description(), "entry2");
EXPECT_EQ(entry3().description(), "entry3");
EXPECT_EQ(string_entry().description(), "string thing");
EXPECT_EQ(vector_entry().description(), "vector thing");
}
// Test that the GetKnownUpToDate/Calc/Eval() methods work.
TEST_F(CacheEntryTest, ValueMethodsWork) {
CacheEntryValue& value0 = entry0().get_mutable_cache_entry_value(context_);
int64_t expected_serial_num = value0.serial_number();
EXPECT_EQ(entry0().GetKnownUpToDate<int>(context_), 3);
EXPECT_EQ(value0.serial_number(), expected_serial_num); // No change.
EXPECT_EQ(entry0().Eval<int>(context_), 3); // Up to date; shouldn't update.
EXPECT_EQ(value0.serial_number(), expected_serial_num); // No change.
value0.mark_out_of_date();
DRAKE_EXPECT_THROWS_MESSAGE(entry0().GetKnownUpToDate<int>(context_),
".*GetKnownUpToDate().*value out of date.*");
EXPECT_EQ(entry0().Eval<int>(context_), 99); // Should update now.
++expected_serial_num;
EXPECT_EQ(value0.serial_number(), expected_serial_num); // Increased.
// EvalAbstract() should retrieve the same object as Eval() did.
const AbstractValue& abstract_value_eval = entry0().EvalAbstract(context_);
EXPECT_EQ(value0.serial_number(), expected_serial_num); // No change.
EXPECT_EQ(abstract_value_eval.get_value<int>(), 99);
// GetKnownUpToDateAbstract() should return the same object as EvalAbstract().
const AbstractValue& abstract_value_get =
entry0().GetKnownUpToDateAbstract(context_);
EXPECT_EQ(&abstract_value_get, &abstract_value_eval);
EXPECT_EQ(value0.serial_number(), expected_serial_num); // No change.
CacheEntryValue& string_value =
string_entry().get_mutable_cache_entry_value(context_);
expected_serial_num = string_value.serial_number();
EXPECT_EQ(string_entry().GetKnownUpToDate<string>(context_), "initial");
EXPECT_EQ(string_value.serial_number(), expected_serial_num); // No change.
// Check that the Calc() method produces output but doesn't change the
// stored value.
std::unique_ptr<AbstractValue> out = AbstractValue::Make<string>("something");
string_entry().Calc(context_, &*out);
EXPECT_EQ(out->get_value<string>(), "calculated_result");
EXPECT_EQ(string_entry().GetKnownUpToDate<string>(context_), "initial");
EXPECT_EQ(string_value.serial_number(), expected_serial_num); // No change.
// In Debug we have an expensive check that the output type provided to
// Calc() has the right concrete type. Make sure it works.
if (kDrakeAssertIsArmed) {
auto bad_out = AbstractValue::Make<double>(3.14);
DRAKE_EXPECT_THROWS_MESSAGE(
string_entry().Calc(context_, &*bad_out),
".*Calc().*expected.*type.*string.*but got.*double.*");
}
// The value is currently marked up to date, so Eval does nothing.
const string& result = string_entry().Eval<string>(context_);
EXPECT_EQ(result, "initial");
// Force out-of-date.
string_value.mark_out_of_date();
DRAKE_EXPECT_THROWS_MESSAGE(
string_entry().GetKnownUpToDateAbstract(context_),
".*GetKnownUpToDateAbstract().*value out of date.*");
DRAKE_EXPECT_THROWS_MESSAGE(string_entry().GetKnownUpToDate<string>(context_),
".*GetKnownUpToDate().*value out of date.*");
string_entry().Eval<string>(context_);
++expected_serial_num;
EXPECT_FALSE(string_entry().is_out_of_date(context_));
DRAKE_EXPECT_NO_THROW(string_entry().GetKnownUpToDate<string>(context_));
EXPECT_EQ(string_value.serial_number(), expected_serial_num); // Updated.
// The result reference was updated by the Eval().
EXPECT_EQ(result, "calculated_result");
// GetKnownUpToDate() returns the same reference.
EXPECT_EQ(&string_entry().GetKnownUpToDate<string>(context_), &result);
// This is the wrong value type.
DRAKE_EXPECT_THROWS_MESSAGE(
string_entry().GetKnownUpToDate<int>(context_),
".*GetKnownUpToDate().*wrong value type.*int.*actual type.*string.*");
}
// Check that a chain of dependent cache entries gets invalidated properly.
// See Diagram above for expected dependencies.
TEST_F(CacheEntryTest, InvalidationWorks) {
// Everything starts out up to date. This should invalidate everything.
context_.get_tracker(system_.time_ticket()).NoteValueChange(99);
EXPECT_TRUE(entry0().is_out_of_date(context_));
EXPECT_TRUE(entry1().is_out_of_date(context_));
EXPECT_TRUE(entry2().is_out_of_date(context_));
EXPECT_TRUE(entry3().is_out_of_date(context_));
EXPECT_TRUE(string_entry().is_out_of_date(context_));
EXPECT_TRUE(vector_entry().is_out_of_date(context_));
}
// Make sure the debugging routine that invalidates everything works.
TEST_F(CacheEntryTest, InvalidateAllWorks) {
// Everything starts out up to date. This should invalidate everything.
context_.SetAllCacheEntriesOutOfDate();
EXPECT_TRUE(entry0().is_out_of_date(context_));
EXPECT_TRUE(entry1().is_out_of_date(context_));
EXPECT_TRUE(entry2().is_out_of_date(context_));
EXPECT_TRUE(entry3().is_out_of_date(context_));
EXPECT_TRUE(string_entry().is_out_of_date(context_));
EXPECT_TRUE(vector_entry().is_out_of_date(context_));
}
// Make sure we can modify the set of prerequisites for a cache entry after
// its initial declaration, and that the new set is properly reflected in
// the next generated Context.
TEST_F(CacheEntryTest, ModifyPrerequisites) {
const std::set<DependencyTicket>& string_prereqs =
string_entry().prerequisites();
EXPECT_EQ(string_prereqs.size(), 1); // Just time_ticket.
EXPECT_FALSE(string_entry().is_out_of_date(context_));
const DependencyTracker& entry1_tracker =
context_.get_tracker(entry1().ticket());
const DependencyTracker& entry2_tracker =
context_.get_tracker(entry2().ticket());
// If we change entry1 or entry2, string_entry should not be invalidated.
entry1_tracker.NoteValueChange(1001); // Arbitrary unused change event #.
entry2_tracker.NoteValueChange(1002);
EXPECT_FALSE(string_entry().is_out_of_date(context_));
// Now add entry1 as a prerequisite.
CacheEntry& mutable_string_entry =
system_.get_mutable_cache_entry(string_entry().cache_index());
mutable_string_entry.mutable_prerequisites().insert(entry1().ticket());
auto new_context = system_.AllocateContext();
EXPECT_TRUE(string_entry().is_out_of_date(*new_context));
string_entry()
.get_mutable_cache_entry_value(*new_context)
.SetValueOrThrow<std::string>("something");
EXPECT_FALSE(string_entry().is_out_of_date(*new_context));
const DependencyTracker& new_entry1_tracker =
new_context->get_tracker(entry1().ticket());
const DependencyTracker& new_entry2_tracker =
new_context->get_tracker(entry2().ticket());
// entry2 should still not be a prerequisite.
new_entry2_tracker.NoteValueChange(1003);
EXPECT_FALSE(string_entry().is_out_of_date(*new_context));
// But entry1 is now a prerequisite.
new_entry1_tracker.NoteValueChange(1004);
EXPECT_TRUE(string_entry().is_out_of_date(*new_context));
// And let's make sure time is still a prerequisite.
string_entry()
.get_mutable_cache_entry_value(*new_context)
.SetValueOrThrow<std::string>("something else");
const DependencyTracker& new_time_tracker =
new_context->get_tracker(system_.time_ticket());
EXPECT_FALSE(string_entry().is_out_of_date(*new_context));
new_time_tracker.NoteValueChange(1005);
EXPECT_TRUE(string_entry().is_out_of_date(*new_context));
}
// Make sure the debugging routine to disable the cache works, and is
// independent of the out_of_date flags.
TEST_F(CacheEntryTest, DisableCacheWorks) {
CacheEntryValue& int_val = entry1().get_mutable_cache_entry_value(context_);
CacheEntryValue& str_val =
string_entry().get_mutable_cache_entry_value(context_);
CacheEntryValue& vec_val =
vector_entry().get_mutable_cache_entry_value(context_);
// Everything starts out up to date. Memorize serial numbers.
int64_t ser_int = int_val.serial_number();
int64_t ser_str = str_val.serial_number();
int64_t ser_vec = vec_val.serial_number();
EXPECT_FALSE(int_val.needs_recomputation());
EXPECT_FALSE(str_val.needs_recomputation());
EXPECT_FALSE(vec_val.needs_recomputation());
// Eval() shouldn't have to recalculate since caching is enabled.
entry1().EvalAbstract(context_);
string_entry().EvalAbstract(context_);
vector_entry().EvalAbstract(context_);
EXPECT_EQ(int_val.serial_number(), ser_int); // No change to serial numbers.
EXPECT_EQ(str_val.serial_number(), ser_str);
EXPECT_EQ(vec_val.serial_number(), ser_vec);
context_.DisableCaching();
// Up-to-date shouldn't be affected, but now we need recomputation.
EXPECT_FALSE(int_val.is_out_of_date());
EXPECT_FALSE(str_val.is_out_of_date());
EXPECT_FALSE(vec_val.is_out_of_date());
EXPECT_TRUE(int_val.needs_recomputation());
EXPECT_TRUE(str_val.needs_recomputation());
EXPECT_TRUE(vec_val.needs_recomputation());
// Eval() should recalculate even though up-to_date is true.
entry1().EvalAbstract(context_);
string_entry().EvalAbstract(context_);
vector_entry().EvalAbstract(context_);
++ser_int; ++ser_str; ++ser_vec;
EXPECT_EQ(int_val.serial_number(), ser_int);
EXPECT_EQ(str_val.serial_number(), ser_str);
EXPECT_EQ(vec_val.serial_number(), ser_vec);
// Flags are still supposed to be functioning while caching is disabled,
// even though they are mostly ignored. (The GetKnownUpToDate() methods
// depends on them.)
int_val.mark_out_of_date();
str_val.mark_out_of_date();
vec_val.mark_out_of_date();
// Eval() should recalculate and mark entries up to date.
entry1().EvalAbstract(context_);
string_entry().EvalAbstract(context_);
vector_entry().EvalAbstract(context_);
++ser_int; ++ser_str; ++ser_vec;
EXPECT_FALSE(int_val.is_out_of_date());
EXPECT_FALSE(str_val.is_out_of_date());
EXPECT_FALSE(vec_val.is_out_of_date());
EXPECT_EQ(int_val.serial_number(), ser_int);
EXPECT_EQ(str_val.serial_number(), ser_str);
EXPECT_EQ(vec_val.serial_number(), ser_vec);
// GetKnownUpToDate() should work even though caching is disabled, since the
// entries are marked up to date.
DRAKE_EXPECT_NO_THROW(entry1().GetKnownUpToDate<int>(context_));
DRAKE_EXPECT_NO_THROW(string_entry().GetKnownUpToDate<string>(context_));
DRAKE_EXPECT_NO_THROW(vector_entry().GetKnownUpToDate<MyVector3d>(context_));
// Now re-enable caching and verify that it works.
EXPECT_TRUE(entry1().is_cache_entry_disabled(context_));
EXPECT_TRUE(string_entry().is_cache_entry_disabled(context_));
context_.EnableCaching();
EXPECT_FALSE(entry1().is_cache_entry_disabled(context_));
EXPECT_FALSE(string_entry().is_cache_entry_disabled(context_));
// These are still up to date since enable/disable is independent. So
// these Eval's should be no-ops.
entry1().EvalAbstract(context_);
string_entry().EvalAbstract(context_);
EXPECT_EQ(int_val.serial_number(), ser_int);
EXPECT_EQ(str_val.serial_number(), ser_str);
// Verify that we can disable/enable a single entry.
string_entry().disable_caching(context_);
entry1().EvalAbstract(context_);
string_entry().EvalAbstract(context_);
++ser_str; // Only disabled entry needs recalculation.
EXPECT_EQ(int_val.serial_number(), ser_int);
EXPECT_EQ(str_val.serial_number(), ser_str);
// Enable and verify that no computation is required for either entry.
string_entry().enable_caching(context_);
entry1().EvalAbstract(context_);
string_entry().EvalAbstract(context_);
EXPECT_EQ(int_val.serial_number(), ser_int);
EXPECT_EQ(str_val.serial_number(), ser_str);
}
// Test that the vector-valued cache entry works and preserved the underlying
// concrete type.
TEST_F(CacheEntryTest, VectorCacheEntryWorks) {
auto& entry = system_.get_cache_entry(vector_index_);
auto& entry_value = entry.get_mutable_cache_entry_value(context_);
EXPECT_FALSE(entry_value.is_out_of_date()); // We set it during construction.
const MyVector3d& contents = entry_value.get_value<MyVector3d>();
Vector3d eigen_contents = contents.get_value();
EXPECT_EQ(eigen_contents, Vector3d(99., 98., 97.));
// Force Eval to recalculate by pretending we modified a z, which should
// invalidate this xc-dependent cache entry.
// Note: the change_event number just has to be unique from any others used
// on this context, doesn't have to be this particular value!
context_.get_mutable_tracker(system_.z_ticket()).NoteValueChange(1001);
EXPECT_TRUE(entry_value.is_out_of_date());
const MyVector3d& contents2 = entry.Eval<MyVector3d>(context_);
EXPECT_FALSE(entry_value.is_out_of_date());
Vector3d eigen_contents2 = contents2.get_value();
EXPECT_EQ(eigen_contents2, Vector3d(3., 2., 1.));
// The contents object should still be the same one.
EXPECT_EQ(&contents2, &contents);
}
// Test that we can swap in a new value if it has the right type, and that
// the swapped-in value is invalid immediately after swapping. In Debug,
// test that we throw if the swapped-in value is null or has the
// wrong type.
TEST_F(CacheEntryTest, CanSwapValue) {
auto& entry_value = string_entry().get_mutable_cache_entry_value(context_);
EXPECT_FALSE(entry_value.is_out_of_date()); // Set to "initial".
EXPECT_EQ(entry_value.get_value<string>(), "initial");
auto new_value = AbstractValue::Make<string>("new value");
entry_value.swap_value(&new_value);
EXPECT_EQ(new_value->get_value<string>(), "initial");
EXPECT_TRUE(entry_value.is_out_of_date());
entry_value.mark_up_to_date();
EXPECT_EQ(entry_value.get_value<string>(), "new value");
EXPECT_EQ(string_entry().GetKnownUpToDate<string>(context_), "new value");
// In Debug builds, try a bad swap and expect it to be caught.
if (kDrakeAssertIsArmed) {
std::unique_ptr<AbstractValue> empty_ptr;
DRAKE_EXPECT_THROWS_MESSAGE(entry_value.swap_value(&empty_ptr),
".*swap_value().*value.*empty.*");
auto bad_value = AbstractValue::Make<int>(29);
DRAKE_EXPECT_THROWS_MESSAGE(
entry_value.swap_value(&bad_value),
".*swap_value().*value.*wrong concrete type.*int.*"
"[Ee]xpected.*string.*");
}
}
TEST_F(CacheEntryTest, InvalidationIsRecursive) {
invalidate(index1_); // Invalidate entry1.
EXPECT_EQ(3, entry0().GetKnownUpToDate<int>(context_));
EXPECT_TRUE(entry1().is_out_of_date(context_));
EXPECT_TRUE(entry2().is_out_of_date(context_));
EXPECT_TRUE(entry3().is_out_of_date(context_));
// Shouldn't have leaked into independent entries.
EXPECT_FALSE(string_entry().is_out_of_date(context_));
EXPECT_FALSE(vector_entry().is_out_of_date(context_));
}
TEST_F(CacheEntryTest, Copy) {
// Create a clone of the cache and dependency graph.
auto clone_context_ptr = context_.Clone();
MyContextBase& clone_context =
dynamic_cast<MyContextBase&>(*clone_context_ptr);
// The copy should have the same values.
EXPECT_EQ(entry0().GetKnownUpToDate<int>(context_),
entry0().GetKnownUpToDate<int>(clone_context));
EXPECT_EQ(entry1().GetKnownUpToDate<int>(context_),
entry1().GetKnownUpToDate<int>(clone_context));
EXPECT_EQ(entry2().GetKnownUpToDate<int>(context_),
entry2().GetKnownUpToDate<int>(clone_context));
EXPECT_EQ(entry3().GetKnownUpToDate<int>(context_),
entry3().GetKnownUpToDate<int>(clone_context));
EXPECT_EQ(string_entry().GetKnownUpToDate<string>(context_),
string_entry().GetKnownUpToDate<string>(clone_context));
EXPECT_EQ(
vector_entry().GetKnownUpToDate<MyVector3d>(context_).get_value(),
vector_entry().GetKnownUpToDate<MyVector3d>(clone_context).get_value());
// Changes to the copy should not affect the original.
EXPECT_EQ(entry2().GetKnownUpToDate<int>(context_), 2);
entry2().get_mutable_cache_entry_value(clone_context).mark_out_of_date();
EXPECT_EQ(entry2().Eval<int>(clone_context), 98);
EXPECT_EQ(entry2().GetKnownUpToDate<int>(context_), 2);
// This should invalidate everything in the original cache, but nothing
// in the copy.
// Note: the change_event number just has to be unique from any others used
// on this context, doesn't have to be this particular value!
context_.get_tracker(system_.time_ticket()).NoteValueChange(10);
EXPECT_TRUE(string_entry().is_out_of_date(context_));
EXPECT_FALSE(string_entry().is_out_of_date(clone_context));
EXPECT_TRUE(vector_entry().is_out_of_date(context_));
EXPECT_FALSE(vector_entry().is_out_of_date(clone_context));
EXPECT_TRUE(entry0().is_out_of_date(context_));
EXPECT_FALSE(entry0().is_out_of_date(clone_context));
EXPECT_TRUE(entry1().is_out_of_date(context_));
EXPECT_FALSE(entry1().is_out_of_date(clone_context));
EXPECT_TRUE(entry2().is_out_of_date(context_));
EXPECT_FALSE(entry2().is_out_of_date(clone_context));
EXPECT_TRUE(entry3().is_out_of_date(context_));
EXPECT_FALSE(entry3().is_out_of_date(clone_context));
// Bring everything in source context up to date.
entry0().EvalAbstract(context_); entry1().EvalAbstract(context_);
entry2().EvalAbstract(context_); entry3().EvalAbstract(context_);
string_entry().EvalAbstract(context_); vector_entry().EvalAbstract(context_);
// Pretend entry0 was modified in the copy. Should invalidate the copy's
// entry1-5, but leave source untouched.
entry0().get_mutable_cache_entry_value(clone_context).mark_out_of_date();
clone_context.get_tracker(entry0().ticket()).NoteValueChange(11);
EXPECT_TRUE(entry0().is_out_of_date(clone_context));
EXPECT_FALSE(entry0().is_out_of_date(context_));
EXPECT_TRUE(entry1().is_out_of_date(clone_context));
EXPECT_FALSE(entry1().is_out_of_date(context_));
EXPECT_TRUE(entry2().is_out_of_date(clone_context));
EXPECT_FALSE(entry2().is_out_of_date(context_));
EXPECT_TRUE(entry3().is_out_of_date(clone_context));
EXPECT_FALSE(entry3().is_out_of_date(context_));
// These aren't downstream of entry0().
EXPECT_FALSE(string_entry().is_out_of_date(clone_context));
EXPECT_FALSE(vector_entry().is_out_of_date(clone_context));
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/discrete_values_limit_malloc_test.cc | #include <gtest/gtest.h>
#include "drake/common/autodiff.h"
#include "drake/common/test_utilities/limit_malloc.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/discrete_values.h"
using Eigen::Vector2d;
using Eigen::Vector3d;
using Eigen::VectorXd;
namespace drake {
namespace systems {
namespace {
template <typename T>
class DiscreteValuesLimitMallocFixture :public testing::Test {
protected:
void SetUp() override {
// Build a first object with some arbitrary data.
a_.AppendGroup(BasicVector<T>::Make({1.0, 2.0}));
a_.AppendGroup(BasicVector<T>::Make({3.0, 4.0}));
// Make a second object with the same "data shape".
b_.AppendGroup(std::make_unique<BasicVector<T>>(2));
b_.AppendGroup(std::make_unique<BasicVector<T>>(2));
}
DiscreteValues<T> a_;
DiscreteValues<T> b_;
};
using ScalarTypes = ::testing::Types<double, AutoDiffXd, symbolic::Expression>;
TYPED_TEST_SUITE(DiscreteValuesLimitMallocFixture, ScalarTypes);
// Ensure we avoid the heap when performing SetFrom() without changing scalar
// type. See #14802.
TYPED_TEST(DiscreteValuesLimitMallocFixture, NoHeapAllocsInNonConvertSetFrom) {
test::LimitMalloc guard({.max_num_allocations = 0});
this->b_.SetFrom(this->a_);
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/fixed_input_port_value_test.cc | #include "drake/systems/framework/fixed_input_port_value.h"
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/context_base.h"
#include "drake/systems/framework/system_base.h"
// Tests the functioning of the concrete FixedInputPortValue class and
// verifies that it properly notifies dependent input ports when its value
// changes. The latter requires some hand-crafting of a suitable Context since
// we can only use framework base objects here.
namespace drake {
namespace systems {
namespace {
// Create a ContextBase with a few input ports for us to play with.
class MyContextBase : public ContextBase {
public:
MyContextBase() {
AddInputPort(InputPortIndex(0), DependencyTicket(100), {});
AddInputPort(InputPortIndex(1), DependencyTicket(101), {});
}
MyContextBase(const MyContextBase&) = default;
private:
std::unique_ptr<ContextBase> DoCloneWithoutPointers() const final {
return std::make_unique<MyContextBase>(*this);
}
};
// Creates a MySystemBase and its context and wires up fixed input values
// to each of the two ports.
class FixedInputPortTest : public ::testing::Test {
protected:
void SetUp() override {
port0_value_ = &context_.FixInputPort(
InputPortIndex(0), Value<BasicVector<double>>(
Eigen::Vector2d(5.0, 6.0)));
port1_value_ = &context_.FixInputPort(
InputPortIndex(1), Value<std::string>("foo"));
// The input ports and free values should have distinct tickets.
DependencyTicket ticket0 = context_.input_port_ticket(InputPortIndex(0));
DependencyTicket ticket1 = context_.input_port_ticket(InputPortIndex(1));
DependencyTicket free_ticket0 = port0_value_->ticket();
DependencyTicket free_ticket1 = port1_value_->ticket();
EXPECT_TRUE(ticket0.is_valid() && ticket1.is_valid());
EXPECT_TRUE(free_ticket0.is_valid() && free_ticket1.is_valid());
EXPECT_NE(ticket0, free_ticket0);
EXPECT_NE(ticket1, free_ticket1);
tracker0_ = &context_.get_tracker(ticket0);
tracker1_ = &context_.get_tracker(ticket1);
free_tracker0_ = &context_.get_tracker(free_ticket0);
free_tracker1_ = &context_.get_tracker(free_ticket1);
// Record the initial notification statistics so we can see if they
// change properly.
sent0_ = free_tracker0_->num_notifications_sent();
sent1_ = free_tracker1_->num_notifications_sent();
rcvd0_ = tracker0_->num_notifications_received();
rcvd1_ = tracker1_->num_notifications_received();
serial0_ = port0_value_->serial_number();
serial1_ = port1_value_->serial_number();
}
MyContextBase context_;
FixedInputPortValue* port0_value_{};
FixedInputPortValue* port1_value_{};
const DependencyTracker* tracker0_{};
const DependencyTracker* tracker1_{};
const DependencyTracker* free_tracker0_{};
const DependencyTracker* free_tracker1_{};
int64_t sent0_{-1}, sent1_{-1};
int64_t rcvd0_{-1}, rcvd1_{-1};
int64_t serial0_{-1}, serial1_{-1};
};
// Tests that the Context wiring is set up as we assume for the
// tests here, and that the free values are wired in.
TEST_F(FixedInputPortTest, SystemAndContext) {
// The input port trackers should have declared the free values as
// prerequisites, and the free values should know the input ports are
// subscribers.
ASSERT_EQ(tracker0_->num_prerequisites(), 1);
ASSERT_EQ(free_tracker0_->num_subscribers(), 1);
EXPECT_EQ(free_tracker0_->num_prerequisites(), 0);
ASSERT_EQ(tracker1_->num_prerequisites(), 1);
ASSERT_EQ(free_tracker1_->num_subscribers(), 1);
EXPECT_EQ(free_tracker1_->num_prerequisites(), 0);
EXPECT_EQ(tracker0_->prerequisites()[0], free_tracker0_);
EXPECT_EQ(tracker1_->prerequisites()[0], free_tracker1_);
EXPECT_EQ(free_tracker0_->subscribers()[0], tracker0_);
EXPECT_EQ(free_tracker1_->subscribers()[0], tracker1_);
EXPECT_EQ(&port0_value_->get_owning_context(), &context_);
EXPECT_EQ(&port1_value_->get_owning_context(), &context_);
EXPECT_EQ(port0_value_->ticket(), free_tracker0_->ticket());
EXPECT_EQ(port1_value_->ticket(), free_tracker1_->ticket());
EXPECT_EQ(port0_value_->serial_number(), 1);
EXPECT_EQ(port1_value_->serial_number(), 1);
}
// Once the dependency wiring has been set up between a FixedInputPortValue
// and an input port, providing a replacement value should still use the same
// tracker and wiring.
TEST_F(FixedInputPortTest, RepeatedFixInputPortUsesSameTracker) {
// Remember the old tickets (corresponding trackers were saved above).
const DependencyTicket old_port1_ticket =
context_.input_port_ticket(InputPortIndex(1));
const DependencyTicket old_port1_value_ticket = port1_value_->ticket();
// Replace the value object for output port 1.
const FixedInputPortValue& new_port1_value = context_.FixInputPort(
InputPortIndex(1), Value<std::string>("bar"));
// The new value object should have the same ticket & tracker as the old one.
EXPECT_EQ(new_port1_value.ticket(), old_port1_value_ticket);
EXPECT_EQ(&context_.get_tracker(new_port1_value.ticket()), free_tracker1_);
// The InputPort object should still have the same ticket & tracker.
const DependencyTicket new_port1_ticket =
context_.input_port_ticket(InputPortIndex(1));
EXPECT_EQ(new_port1_ticket, old_port1_ticket);
EXPECT_EQ(&context_.get_tracker(new_port1_ticket), tracker1_);
// And the Prerequisite/Subscriber relationships should still exist.
EXPECT_TRUE(free_tracker1_->HasSubscriber(*tracker1_));
EXPECT_TRUE(tracker1_->HasPrerequisite(*free_tracker1_));
}
// Fixed values are cloned only as part of cloning a context, which
// requires changing the internal context pointer that is used for value
// change notification. The ticket and input port index remain unchanged
// in the new context. The values are copied and serial numbers unchanged.
TEST_F(FixedInputPortTest, Clone) {
std::unique_ptr<ContextBase> new_context = context_.Clone();
auto free0 = new_context->MaybeGetMutableFixedInputPortValue(0);
auto free1 = new_context->MaybeGetMutableFixedInputPortValue(1);
ASSERT_NE(free0, nullptr);
ASSERT_NE(free1, nullptr);
EXPECT_EQ(&free0->get_owning_context(), new_context.get());
EXPECT_EQ(&free1->get_owning_context(), new_context.get());
EXPECT_EQ(free0->get_vector_value<double>().get_value(),
port0_value_->get_vector_value<double>().get_value());
EXPECT_EQ(free1->get_value().get_value<std::string>(),
port1_value_->get_value().get_value<std::string>());
EXPECT_EQ(free0->serial_number(), port0_value_->serial_number());
EXPECT_EQ(free1->serial_number(), port1_value_->serial_number());
// Make sure changing a value in the old context doesn't change a value
// in the new one, and vice versa.
port0_value_->GetMutableVectorData<double>()->SetAtIndex(0, 99);
EXPECT_EQ(port0_value_->get_vector_value<double>()[0], 99);
EXPECT_EQ(free0->get_vector_value<double>()[0], 5);
free1->GetMutableData()->get_mutable_value<std::string>() = "hello";
EXPECT_EQ(free1->get_value().get_value<std::string>(), "hello");
EXPECT_EQ(port1_value_->get_value().get_value<std::string>(), "foo");
}
// Test that we can access values and that doing so does not send value change
// notifications.
TEST_F(FixedInputPortTest, Access) {
EXPECT_EQ(Vector2<double>(5, 6),
port0_value_->get_vector_value<double>().get_value());
EXPECT_EQ(free_tracker0_->num_notifications_sent(), sent0_);
EXPECT_EQ(tracker0_->num_notifications_received(), rcvd0_);
EXPECT_EQ(port0_value_->serial_number(), serial0_);
EXPECT_EQ("foo", port1_value_->get_value().get_value<std::string>());
EXPECT_EQ(free_tracker1_->num_notifications_sent(), sent1_);
EXPECT_EQ(tracker1_->num_notifications_received(), rcvd1_);
EXPECT_EQ(port1_value_->serial_number(), serial1_);
}
// Tests that changes to the vector data are propagated to the input port
// that wraps it.
TEST_F(FixedInputPortTest, Mutation) {
// Change the vector port's value.
port0_value_->GetMutableVectorData<double>()->get_mutable_value()
<< 7, 8;
// Check that the vector contents changed.
EXPECT_EQ(Vector2<double>(7, 8),
port0_value_->get_vector_value<double>().get_value());
// Check that notifications were sent and serial number bumped.
EXPECT_EQ(free_tracker0_->num_notifications_sent(), sent0_ + 1);
EXPECT_EQ(tracker0_->num_notifications_received(), rcvd0_ + 1);
EXPECT_EQ(port0_value_->serial_number(), serial0_ + 1);
// Change the abstract port's value.
port1_value_->GetMutableData()->get_mutable_value<std::string>() = "bar";
// Check that the contents changed.
EXPECT_EQ("bar", port1_value_->get_value().get_value<std::string>());
// Check that notifications were sent and serial number bumped.
EXPECT_EQ(free_tracker1_->num_notifications_sent(), sent1_ + 1);
EXPECT_EQ(tracker1_->num_notifications_received(), rcvd1_ + 1);
EXPECT_EQ(port1_value_->serial_number(), serial1_ + 1);
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/system_symbolic_inspector_test.cc | #include "drake/systems/framework/system_symbolic_inspector.h"
#include <algorithm>
#include <memory>
#include <gtest/gtest.h>
#include "drake/common/symbolic/polynomial.h"
#include "drake/examples/pendulum/pendulum_plant.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace systems {
namespace {
const int kSize = 2;
class SparseSystem : public LeafSystem<symbolic::Expression> {
public:
SparseSystem() {
this->DeclareInputPort(kUseDefaultName, kVectorValued, kSize);
this->DeclareInputPort(kUseDefaultName, kVectorValued, kSize);
this->DeclareVectorOutputPort(kUseDefaultName, kSize,
&SparseSystem::CalcY0);
this->DeclareVectorOutputPort(kUseDefaultName, kSize,
&SparseSystem::CalcY1);
this->DeclareAbstractOutputPort("port_42", 42, &SparseSystem::CalcNothing);
this->DeclareContinuousState(kSize);
this->DeclareDiscreteState(kSize);
this->DeclareForcedDiscreteUpdateEvent(&SparseSystem::CalcDiscreteUpdate);
this->DeclareEqualityConstraint(&SparseSystem::CalcConstraint, kSize,
"equality constraint");
this->DeclareInequalityConstraint(&SparseSystem::CalcConstraint,
{ Eigen::VectorXd::Zero(kSize),
std::nullopt }, "inequality constraint");
}
void AddAbstractInputPort() {
this->DeclareAbstractInputPort(kUseDefaultName, Value<std::string>{});
}
void set_discrete_update_is_affine(bool value) {
discrete_update_is_affine_ = value;
}
private:
// Calculation function for output port 0.
void CalcY0(const Context<symbolic::Expression>& context,
BasicVector<symbolic::Expression>* y0) const {
const auto& u0 = this->get_input_port(0).Eval(context);
const auto& u1 = this->get_input_port(1).Eval(context);
const auto& xc = context.get_continuous_state_vector().CopyToVector();
// Output 0 depends on input 0 and the continuous state. Input 1 appears in
// an intermediate computation, but is ultimately cancelled out.
y0->get_mutable_value() = u1;
y0->get_mutable_value() += u0;
y0->get_mutable_value() -= u1;
y0->get_mutable_value() += 12. * xc;
}
// Calculation function for output port 1.
void CalcY1(const Context<symbolic::Expression>& context,
BasicVector<symbolic::Expression>* y1) const {
const auto& u0 = this->get_input_port(0).Eval(context);
const auto& u1 = this->get_input_port(1).Eval(context);
const auto& xd = context.get_discrete_state(0).get_value();
// Output 1 depends on both inputs and the discrete state.
y1->set_value(u0 + u1 + xd);
}
void CalcNothing(const Context<symbolic::Expression>& context, int*) const {}
void CalcConstraint(const Context<symbolic::Expression>& context,
VectorX<symbolic::Expression>* value) const {
*value = context.get_continuous_state_vector().CopyToVector();
}
// Implements a time-varying affine dynamics.
void DoCalcTimeDerivatives(
const Context<symbolic::Expression>& context,
ContinuousState<symbolic::Expression>* derivatives) const override {
const auto& u0 = this->get_input_port(0).Eval(context);
const auto& u1 = this->get_input_port(1).Eval(context);
const auto& t = context.get_time();
const Vector2<symbolic::Expression> x =
context.get_continuous_state_vector().CopyToVector();
const Eigen::Matrix2d A = 2 * Eigen::Matrix2d::Identity();
const Eigen::Matrix2d B1 = 3 * Eigen::Matrix2d::Identity();
const Eigen::Matrix2d B2 = 4 * Eigen::Matrix2d::Identity();
const Eigen::Vector2d f0(5.0, 6.0);
const Vector2<symbolic::Expression> xdot =
A * t * x + B1 * u0 + B2 * u1 + f0;
derivatives->SetFromVector(xdot);
}
EventStatus CalcDiscreteUpdate(
const systems::Context<symbolic::Expression>& context,
systems::DiscreteValues<symbolic::Expression>* discrete_state) const {
const auto& u0 = this->get_input_port(0).Eval(context);
const auto& u1 = this->get_input_port(1).Eval(context);
const Vector2<symbolic::Expression> xd =
context.get_discrete_state(0).get_value();
const Eigen::Matrix2d A = 7 * Eigen::Matrix2d::Identity();
const Eigen::Matrix2d B1 = 8 * Eigen::Matrix2d::Identity();
const Eigen::Matrix2d B2 = 9 * Eigen::Matrix2d::Identity();
const Eigen::Vector2d f0(10.0, 11.0);
Vector2<symbolic::Expression> next_xd =
A * xd + B1 * u0 + B2 * u1 + f0;
if (!discrete_update_is_affine_) {
next_xd(0) += cos(u0(0));
}
discrete_state->set_value(0, next_xd);
return EventStatus::Succeeded();
}
bool discrete_update_is_affine_{true};
};
class SystemSymbolicInspectorTest : public ::testing::Test {
public:
SystemSymbolicInspectorTest() : system_() {}
protected:
void SetUp() override {
inspector_ = std::make_unique<SystemSymbolicInspector>(system_);
}
SparseSystem system_;
std::unique_ptr<SystemSymbolicInspector> inspector_;
};
class PendulumInspectorTest : public ::testing::Test {
public:
PendulumInspectorTest() : system_() {}
protected:
void SetUp() override {
inspector_ = std::make_unique<SystemSymbolicInspector>(system_);
}
examples::pendulum::PendulumPlant<symbolic::Expression> system_;
std::unique_ptr<SystemSymbolicInspector> inspector_;
};
// Tests that the SystemSymbolicInspector infers, from the symbolic equations of
// the System, that input 1 does not affect output 0.
TEST_F(SystemSymbolicInspectorTest, InputToOutput) {
// Only input 0 affects output 0.
EXPECT_TRUE(inspector_->IsConnectedInputToOutput(0, 0));
EXPECT_FALSE(inspector_->IsConnectedInputToOutput(1, 0));
// Both inputs affect output 1.
EXPECT_TRUE(inspector_->IsConnectedInputToOutput(0, 1));
EXPECT_TRUE(inspector_->IsConnectedInputToOutput(1, 1));
// All inputs are presumed to affect output 2, since it is abstract.
EXPECT_TRUE(inspector_->IsConnectedInputToOutput(0, 2));
EXPECT_TRUE(inspector_->IsConnectedInputToOutput(1, 2));
}
// Tests that, if the System has an abstract input, the SystemSymbolicInspector
// conservatively reports that every output might depend on every input.
TEST_F(SystemSymbolicInspectorTest, AbstractContextThwartsSparsity) {
system_.AddAbstractInputPort();
inspector_ = std::make_unique<SystemSymbolicInspector>(system_);
for (int i = 0; i < system_.num_input_ports(); ++i) {
for (int j = 0; j < system_.num_output_ports(); ++j) {
EXPECT_TRUE(inspector_->IsConnectedInputToOutput(i, j));
}
}
}
TEST_F(SystemSymbolicInspectorTest, ConstraintTest) {
const auto& constraints = inspector_->constraints();
const std::vector<std::string> expected{
"((xc0 == 0) and (xc1 == 0))",
"((xc0 >= 0) and (xc1 >= 0) and (xc0 <= inf) and (xc1 <= inf))",
};
std::vector<std::string> actual;
std::transform(
constraints.begin(), constraints.end(), std::back_inserter(actual),
[](const auto& item) { return item.to_string(); });
EXPECT_EQ(actual, expected);
}
TEST_F(SystemSymbolicInspectorTest, IsTimeInvariant) {
// The derivatives depends on t.
EXPECT_FALSE(inspector_->IsTimeInvariant());
}
TEST_F(PendulumInspectorTest, IsTimeInvariant) {
EXPECT_TRUE(inspector_->IsTimeInvariant());
}
TEST_F(SystemSymbolicInspectorTest, HasAffineDynamicsYes) {
EXPECT_TRUE(inspector_->HasAffineDynamics());
}
GTEST_TEST(SystemSymbolicInspectorTest2, HasAffineDynamicsNo) {
SparseSystem other;
other.set_discrete_update_is_affine(false);
SystemSymbolicInspector other_inspector(other);
EXPECT_FALSE(other_inspector.HasAffineDynamics());
}
TEST_F(PendulumInspectorTest, HasAffineDynamics) {
EXPECT_FALSE(inspector_->HasAffineDynamics());
}
TEST_F(SystemSymbolicInspectorTest, IsAbstract) {
auto context = system_.CreateDefaultContext();
EXPECT_FALSE(SystemSymbolicInspector::IsAbstract(system_, *context));
system_.AddAbstractInputPort();
auto context2 = system_.CreateDefaultContext();
EXPECT_TRUE(SystemSymbolicInspector::IsAbstract(system_, *context2));
}
TEST_F(PendulumInspectorTest, SymbolicParameters) {
auto params = inspector_->numeric_parameters(0);
using examples::pendulum::PendulumParamsIndices;
EXPECT_EQ(params.size(), PendulumParamsIndices::kNumCoordinates);
// Test that the damping parameter appears with the correct order in the
// derivatives and output methods.
symbolic::Variables v({params[PendulumParamsIndices::kDamping]});
auto derivatives = inspector_->derivatives();
EXPECT_EQ(symbolic::Polynomial(derivatives[0], v).TotalDegree(), 0);
EXPECT_EQ(symbolic::Polynomial(derivatives[1], v).TotalDegree(), 1);
auto output = inspector_->output(0);
EXPECT_EQ(symbolic::Polynomial(output[0], v).TotalDegree(), 0);
EXPECT_EQ(symbolic::Polynomial(output[1], v).TotalDegree(), 0);
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/discrete_values_test.cc | // This test covers DiscreteValues (used directly by LeafContexts) and its
// derived class DiagramDiscreteValues (for DiagramContexts).
#include "drake/systems/framework/discrete_values.h"
#include <memory>
#include <stdexcept>
#include <gtest/gtest.h>
#include "drake/common/autodiff.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/test_utilities/is_dynamic_castable.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/diagram_discrete_values.h"
#include "drake/systems/framework/test_utilities/my_vector.h"
using Eigen::Vector2d;
using Eigen::Vector3d;
using Eigen::VectorXd;
namespace drake {
namespace systems {
namespace {
class DiscreteValuesTest : public ::testing::Test {
public:
DiscreteValuesTest() {
data_.push_back(std::make_unique<BasicVector<double>>(v00_));
data_.push_back(std::make_unique<MyVector2d>(v01_));
data1_.push_back(std::make_unique<BasicVector<double>>(v10_));
data1_.push_back(std::make_unique<MyVector3d>(v11_));
data1_.push_back(std::make_unique<MyVector2d>(v12_));
}
protected:
const VectorXd v00_ = Vector2d{1., 1.},
v01_ = Vector2d{2., 3.},
v10_ = Vector3d{9., 10., 11.},
v11_ = Vector3d{-1.25, -2.5, -3.75},
v12_ = Vector2d{5., 6.};
std::vector<std::unique_ptr<BasicVector<double>>> data_;
std::vector<std::unique_ptr<BasicVector<double>>> data1_;
};
TEST_F(DiscreteValuesTest, OwnedState) {
DiscreteValues<double> xd(std::move(data_));
EXPECT_EQ(xd.get_vector(0).value(), v00_);
EXPECT_EQ(xd.get_vector(1).value(), v01_);
// To be deprecated: get_value() wraps a VectorBlock around the value.
EXPECT_EQ(xd.get_vector(0).get_value(), v00_);
EXPECT_EQ(xd.get_vector(1).get_value(), v01_);
}
TEST_F(DiscreteValuesTest, UnownedState) {
DiscreteValues<double> xd(
std::vector<BasicVector<double>*>{data_[0].get(), data_[1].get()});
EXPECT_EQ(xd.get_vector(0).value(), v00_);
EXPECT_EQ(xd.get_vector(1).value(), v01_);
// To be deprecated: get_value() wraps a VectorBlock around the value.
EXPECT_EQ(xd.get_vector(0).get_value(), v00_);
EXPECT_EQ(xd.get_vector(1).get_value(), v01_);
}
TEST_F(DiscreteValuesTest, AppendGroup) {
DiscreteValues<double> xd(std::move(data_));
ASSERT_EQ(xd.num_groups(), 2);
EXPECT_EQ(xd.get_vector(0).value(), v00_);
EXPECT_EQ(xd.get_vector(1).value(), v01_);
const int group_num = xd.AppendGroup(std::make_unique<MyVector3d>(v11_));
EXPECT_EQ(group_num, 2);
ASSERT_EQ(xd.num_groups(), 3);
// Check that we didn't break previous values.
EXPECT_EQ(xd.get_vector(0).value(), v00_);
EXPECT_EQ(xd.get_vector(1).value(), v01_);
// Check that new value and type are preserved.
EXPECT_EQ(xd.get_vector(2).value(), v11_);
EXPECT_TRUE(is_dynamic_castable<MyVector3d>(&xd.get_vector(2)));
}
TEST_F(DiscreteValuesTest, NoNullsAllowed) {
// Unowned.
EXPECT_THROW(DiscreteValues<double>(
std::vector<BasicVector<double>*>{nullptr, data_[1].get()}),
std::logic_error);
// Owned.
data_.push_back(nullptr);
EXPECT_THROW(DiscreteValues<double>(std::move(data_)), std::logic_error);
}
// Clone should be deep, even for unowned data.
TEST_F(DiscreteValuesTest, Clone) {
// Create a DiscreteValues object with unowned contents.
DiscreteValues<double> xd(
std::vector<BasicVector<double>*>{data_[0].get(), data_[1].get()});
xd.set_system_id(internal::SystemId::get_new_id());
std::unique_ptr<DiscreteValues<double>> clone = xd.Clone();
// First check that the clone has the original values.
EXPECT_EQ(clone->get_system_id(), xd.get_system_id());
EXPECT_EQ(clone->get_vector(0).value(), v00_);
EXPECT_EQ(clone->get_vector(1).value(), v01_);
// Set the clone's new values.
Eigen::Vector2d new0(9., 10.), new1(1.25, 2.5);
clone->get_mutable_vector(0).set_value(new0);
clone->get_mutable_vector(1).set_value(new1);
// Check that the clone changed correctly.
EXPECT_EQ(clone->get_vector(0).value(), new0);
EXPECT_EQ(clone->get_vector(1).value(), new1);
// Check that the original remains unchanged.
EXPECT_EQ(xd.get_vector(0).value(), v00_);
EXPECT_EQ(xd.get_vector(1).value(), v01_);
}
TEST_F(DiscreteValuesTest, SetFrom) {
DiscreteValues<double> dut_double(
BasicVector<double>::Make({1.0, 2.0}));
DiscreteValues<AutoDiffXd> dut_autodiff(
BasicVector<AutoDiffXd>::Make({3.0, 4.0}));
DiscreteValues<symbolic::Expression> dut_symbolic(
BasicVector<symbolic::Expression>::Make({5.0, 6.0}));
// Check DiscreteValues<AutoDiff>::SetFrom<double>.
dut_autodiff.SetFrom(dut_double);
EXPECT_EQ(dut_autodiff.get_vector(0)[0].value(), 1.0);
EXPECT_EQ(dut_autodiff.get_vector(0)[0].derivatives().size(), 0);
EXPECT_EQ(dut_autodiff.get_vector(0)[1].value(), 2.0);
EXPECT_EQ(dut_autodiff.get_vector(0)[1].derivatives().size(), 0);
// Check DiscreteValues<Expression>::SetFrom<double>.
dut_symbolic.SetFrom(dut_double);
EXPECT_EQ(dut_symbolic.get_vector(0)[0], 1.0);
EXPECT_EQ(dut_symbolic.get_vector(0)[1], 2.0);
// Check DiscreteValues<double>::SetFrom<AutoDiff>.
dut_autodiff.get_mutable_vector(0)[0] = 7.0;
dut_autodiff.get_mutable_vector(0)[1] = 8.0;
dut_double.SetFrom(dut_autodiff);
EXPECT_EQ(dut_double.get_vector(0)[0], 7.0);
EXPECT_EQ(dut_double.get_vector(0)[1], 8.0);
// Check DiscreteValues<double>::SetFrom<Expression>.
dut_symbolic.get_mutable_vector(0)[0] = 9.0;
dut_symbolic.get_mutable_vector(0)[1] = 10.0;
dut_double.SetFrom(dut_symbolic);
EXPECT_EQ(dut_double.get_vector(0)[0], 9.0);
EXPECT_EQ(dut_double.get_vector(0)[1], 10.0);
// If there was an unbound variable, we get an exception.
dut_symbolic.get_mutable_vector(0)[0] = symbolic::Variable("x");
DRAKE_EXPECT_THROWS_MESSAGE(
dut_double.SetFrom(dut_symbolic),
".*variable x.*\n*");
}
// Tests that the convenience accessors for a DiscreteValues that contains
// just one group work as documented.
GTEST_TEST(DiscreteValuesSingleGroupTest, ConvenienceSugar) {
DiscreteValues<double> xd(BasicVector<double>::Make({42.0, 43.0}));
EXPECT_EQ(2, xd.size());
EXPECT_EQ(42.0, xd[0]);
EXPECT_EQ(43.0, xd[1]);
xd[0] = 100.0;
EXPECT_EQ(100.0, xd.get_vector()[0]);
xd.get_mutable_vector()[1] = 1000.0;
EXPECT_EQ(1000.0, xd[1]);
Eigen::Vector2d vec{44., 45.}, vec2{46., 47.};
xd.set_value(vec);
EXPECT_TRUE(CompareMatrices(xd.value(), vec));
xd.get_mutable_value() = vec2;
EXPECT_TRUE(CompareMatrices(xd.value(), vec2));
DRAKE_EXPECT_THROWS_MESSAGE(xd.set_value(Vector3d::Ones()), ".*size.*");
}
// Tests that the convenience accessors for a DiscreteValues that contains
// no groups work as documented.
GTEST_TEST(DiscreteValuesSingleGroupTest, ConvenienceSugarEmpty) {
static constexpr char expected_pattern[] = ".*exactly one group.*";
DiscreteValues<double> xd;
DRAKE_EXPECT_THROWS_MESSAGE(xd.size(), expected_pattern);
DRAKE_EXPECT_THROWS_MESSAGE(xd[0], expected_pattern);
DRAKE_EXPECT_THROWS_MESSAGE(xd.get_vector(), expected_pattern);
DRAKE_EXPECT_THROWS_MESSAGE(xd.get_mutable_vector(), expected_pattern);
DRAKE_EXPECT_THROWS_MESSAGE(xd.set_value(VectorXd()), expected_pattern);
DRAKE_EXPECT_THROWS_MESSAGE(xd.value(), expected_pattern);
DRAKE_EXPECT_THROWS_MESSAGE(xd.get_mutable_value(), expected_pattern);
}
// Tests that the convenience accessors for a DiscreteValues that contains
// multiple groups work as documented.
TEST_F(DiscreteValuesTest, ConvenienceSugarMultiple) {
static constexpr char expected_pattern[] = ".*exactly one group.*";
DiscreteValues<double> xd(std::move(data_));
DRAKE_EXPECT_THROWS_MESSAGE(xd.size(), expected_pattern);
DRAKE_EXPECT_THROWS_MESSAGE(xd[0], expected_pattern);
DRAKE_EXPECT_THROWS_MESSAGE(xd.get_vector(), expected_pattern);
DRAKE_EXPECT_THROWS_MESSAGE(xd.get_mutable_vector(), expected_pattern);
Eigen::Vector2d vec{44., 45.}, vec2{46., 47.};
xd.set_value(1, vec);
EXPECT_TRUE(CompareMatrices(xd.value(1), vec));
xd.get_mutable_value(1) = vec2;
EXPECT_TRUE(CompareMatrices(xd.value(1), vec2));
DRAKE_EXPECT_THROWS_MESSAGE(xd.set_value(1, Vector3d::Ones()), ".*size.*");
}
// For DiagramDiscreteValues we want to check that we can build a tree of
// unowned DiscreteValues but then Clone() produces an identical tree of
// owned DiscreteValues, with underlying BasicVector types preserved.
// Below b=basic vector, m=myvector.
TEST_F(DiscreteValuesTest, DiagramDiscreteValues) {
DiscreteValues<double> dv0(std::move(data_)); // 2 groups size (b2,m2)
DiscreteValues<double> dv1(std::move(data1_)); // 3 groups size (b3,m3,m2)
auto dv2ptr = dv0.Clone(), dv3ptr = dv1.Clone();
DiscreteValues<double>& dv2 = *dv2ptr; // 2 groups size (b2,m2)
DiscreteValues<double>& dv3 = *dv3ptr; // 3 groups size (b3,m3,m2)
EXPECT_EQ(dv0.num_groups(), 2);
EXPECT_EQ(dv1.num_groups(), 3);
EXPECT_EQ(dv2.num_groups(), 2);
EXPECT_EQ(dv3.num_groups(), 3);
// root
// ╱ ╲ Flattened: root=10 groups
// dv3 ddv1 ddv1=7 groups
// ╱ | ╲
// dv0 dv1 dv2
std::vector<DiscreteValues<double>*> unowned1{&dv0, &dv1, &dv2};
DiagramDiscreteValues<double> ddv1(unowned1);
std::vector<DiscreteValues<double>*> unowned2{&dv3, &ddv1};
DiagramDiscreteValues<double> root(unowned2);
EXPECT_EQ(ddv1.num_subdiscretes(), 3);
EXPECT_EQ(ddv1.num_groups(), 7);
EXPECT_EQ(ddv1.get_vector(0).size(), 2); // dv0[0]
EXPECT_EQ(ddv1.get_vector(3).size(), 3); // dv1[1]
EXPECT_EQ(ddv1.get_vector(6).size(), 2); // dv2[1]
EXPECT_EQ(root.num_subdiscretes(), 2);
EXPECT_EQ(root.num_groups(), 10);
EXPECT_EQ(root.get_subdiscrete(SubsystemIndex(0)).num_groups(), 3);
EXPECT_EQ(root.get_subdiscrete(SubsystemIndex(1)).num_groups(), 7);
EXPECT_EQ(root.get_vector(1).size(), 3); // dv3[1]
EXPECT_EQ(root.get_vector(3).size(), 2); // dv0[0]
EXPECT_EQ(root.get_vector(6).size(), 3); // dv1[1]
EXPECT_EQ(root.get_vector(9).size(), 2); // dv2[1]
// Check some of the vector types.
EXPECT_FALSE(is_dynamic_castable<MyVector3d>(&root.get_vector(0))); // dv3[0]
EXPECT_TRUE(is_dynamic_castable<MyVector3d>(&root.get_vector(1))); // dv3[1]
EXPECT_TRUE(is_dynamic_castable<MyVector2d>(&root.get_vector(2))); // dv3[2]
EXPECT_TRUE(is_dynamic_castable<MyVector3d>(&root.get_vector(6))); // dv1[1]
// This is the shadowed Clone() method that preserves the concrete type.
auto root2_ptr = root.Clone();
DiagramDiscreteValues<double>& root2 = *root2_ptr;
// Should have same structure.
EXPECT_EQ(root2.num_subdiscretes(), root.num_subdiscretes());
EXPECT_EQ(root2.num_groups(), root.num_groups());
EXPECT_EQ(root2.get_subdiscrete(SubsystemIndex(0)).num_groups(),
root.get_subdiscrete(SubsystemIndex(0)).num_groups());
EXPECT_EQ(root2.get_subdiscrete(SubsystemIndex(1)).num_groups(),
root.get_subdiscrete(SubsystemIndex(1)).num_groups());
// But different owned BasicVectors, with the same values.
for (int i = 0; i < root.num_groups(); ++i) {
EXPECT_NE(&root.get_vector(i), &root2.get_vector(i));
EXPECT_EQ(root2.get_vector(i).value(), root.get_vector(i).value());
}
// Check that the underlying vector types were preserved by Clone().
EXPECT_FALSE(
is_dynamic_castable<MyVector3d>(&root2.get_vector(0))); // dv3[0]
EXPECT_TRUE(is_dynamic_castable<MyVector3d>(&root2.get_vector(1))); // dv3[1]
EXPECT_TRUE(is_dynamic_castable<MyVector2d>(&root2.get_vector(2))); // dv3[2]
EXPECT_TRUE(is_dynamic_castable<MyVector3d>(&root2.get_vector(6))); // dv1[1]
// To make sure we didn't go too far with ownership, check that writing
// through root2 changes what is seen by its subdiscretes.
EXPECT_EQ(root2.get_vector(6).value()[1], -2.5);
const DiscreteValues<double>& root2_ddv1 =
root2.get_subdiscrete(SubsystemIndex(1));
EXPECT_EQ(root2_ddv1.get_vector(3).value()[1], -2.5);
root2.get_mutable_vector(6).get_mutable_value()[1] = 19.;
EXPECT_EQ(root2.get_vector(6).value()[1], 19.);
EXPECT_EQ(root2_ddv1.get_vector(3).value()[1], 19.);
EXPECT_EQ(ddv1.get_vector(3).value()[1], -2.5); // sanity check
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/system_scalar_converter_test.cc | #include "drake/systems/framework/system_scalar_converter.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/is_dynamic_castable.h"
#include "drake/systems/framework/leaf_system.h"
#include "drake/systems/framework/test_utilities/scalar_conversion.h"
namespace drake {
namespace systems {
namespace {
using symbolic::Expression;
// A system that has non-trivial non-T-typed member data.
// This system can convert between all scalar types.
template <typename T>
class AnyToAnySystem : public LeafSystem<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(AnyToAnySystem);
// User constructor.
explicit AnyToAnySystem(int magic) : magic_(magic) {}
// Copy constructor that converts to a different scalar type.
template <typename U>
explicit AnyToAnySystem(const AnyToAnySystem<U>& other)
: AnyToAnySystem(other.magic()) {}
int magic() const { return magic_; }
private:
int magic_{};
};
// A system that has non-trivial non-T-typed member data.
// This system does not support symbolic form.
template <typename T>
class NonSymbolicSystem : public LeafSystem<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(NonSymbolicSystem);
// User constructor.
explicit NonSymbolicSystem(int magic)
: magic_(magic) {
// Declare input-output relation of `y[0] = copysign(magic, u[0])`.
this->DeclareVectorInputPort(kUseDefaultName, 1);
this->DeclareVectorOutputPort(
kUseDefaultName, 1,
[this](const Context<T>& context, BasicVector<T>* output) {
const auto& input = this->get_input_port(0).Eval(context);
(*output)[0] = test::copysign_int_to_non_symbolic_scalar(
this->magic(), input[0]);
});
}
// Copy constructor that converts to a different scalar type.
template <typename U>
explicit NonSymbolicSystem(const NonSymbolicSystem<U>& other)
: NonSymbolicSystem(other.magic()) {}
int magic() const { return magic_; }
private:
int magic_{};
};
// A system that has non-trivial non-T-typed member data.
// This system can only convert from a scalar type of double.
template <typename T>
class FromDoubleSystem : public LeafSystem<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(FromDoubleSystem);
// User constructor.
explicit FromDoubleSystem(int magic) : magic_(magic) {}
// Copy constructor that converts to a different scalar type. Note that we
// are not templated on U, since FromDoubleSystem can only come from double.
// Note that we need a dummy argument in order to avoid conflicting with our
// copy constructor.
explicit FromDoubleSystem(
const FromDoubleSystem<double>& other, int dummy = 0)
: FromDoubleSystem(other.magic()) {}
int magic() const { return magic_; }
private:
int magic_{};
};
// A subclass of AnyToAnySystem.
template <typename T>
class SubclassOfAnyToAnySystem : public AnyToAnySystem<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SubclassOfAnyToAnySystem);
// User constructor.
SubclassOfAnyToAnySystem() : AnyToAnySystem<T>(22) {}
// Copy constructor that converts to a different scalar type.
template <typename U>
explicit SubclassOfAnyToAnySystem(const SubclassOfAnyToAnySystem<U>&)
: SubclassOfAnyToAnySystem() {}
};
} // namespace
namespace scalar_conversion {
template <> struct Traits<NonSymbolicSystem> : public NonSymbolicTraits {};
template <> struct Traits<FromDoubleSystem> : public FromDoubleTraits {};
} // namespace scalar_conversion
namespace {
template <template <typename> class S, typename T, typename U, int kMagic>
void TestConversionPass() {
// The device under test.
const SystemScalarConverter dut(SystemTypeTag<S>{});
// Do the conversion.
EXPECT_TRUE((dut.IsConvertible<T, U>()));
EXPECT_TRUE(dut.IsConvertible(typeid(T), typeid(U)));
const S<U> original{kMagic};
const std::unique_ptr<System<T>> converted = dut.Convert<T, U>(original);
EXPECT_TRUE(converted != nullptr);
// Confirm that the correct type came out.
const auto* const downcast = dynamic_cast<const S<T>*>(converted.get());
EXPECT_TRUE(downcast != nullptr);
// Confirm that the magic was preserved.
EXPECT_EQ(downcast ? downcast->magic() : 0, kMagic);
}
template <template <typename> class S, typename T, typename U>
void TestConversionFail() {
const SystemScalarConverter dut(SystemTypeTag<S>{});
// Do the conversion.
EXPECT_FALSE((dut.IsConvertible<T, U>()));
EXPECT_FALSE(dut.IsConvertible(typeid(T), typeid(U)));
const S<U> original{0};
const std::unique_ptr<System<T>> converted = dut.Convert<T, U>(original);
// Confirm that nothing came out.
EXPECT_TRUE(converted == nullptr);
}
GTEST_TEST(SystemScalarConverterTest, Empty) {
const SystemScalarConverter dut1;
const SystemScalarConverter dut2(SystemTypeTag<AnyToAnySystem>{});
EXPECT_TRUE(dut1.empty());
EXPECT_FALSE(dut2.empty());
}
GTEST_TEST(SystemScalarConverterTest, DefaualtConstructor) {
// With the default ctor, nothing is convertible.
const SystemScalarConverter dut;
EXPECT_FALSE((dut.IsConvertible<double, double>()));
EXPECT_FALSE((dut.IsConvertible<double, AutoDiffXd>()));
EXPECT_FALSE((dut.IsConvertible<double, Expression>()));
EXPECT_FALSE((dut.IsConvertible<AutoDiffXd, double>()));
EXPECT_FALSE((dut.IsConvertible<AutoDiffXd, AutoDiffXd>()));
EXPECT_FALSE((dut.IsConvertible<AutoDiffXd, Expression>()));
EXPECT_FALSE((dut.IsConvertible<Expression, double>()));
EXPECT_FALSE((dut.IsConvertible<Expression, AutoDiffXd>()));
EXPECT_FALSE((dut.IsConvertible<Expression, Expression>()));
}
GTEST_TEST(SystemScalarConverterTest, TestAnyToAnySystem) {
// We don't support T => T conversion -- that's the copy constructor, which
// is usually disabled.
TestConversionFail<AnyToAnySystem, double, double>();
TestConversionFail<AnyToAnySystem, AutoDiffXd, AutoDiffXd>();
TestConversionFail<AnyToAnySystem, Expression, Expression>();
// We support all remaining combinations of standard types.
TestConversionPass<AnyToAnySystem, double, AutoDiffXd, 1>();
TestConversionPass<AnyToAnySystem, double, Expression, 2>();
TestConversionPass<AnyToAnySystem, AutoDiffXd, double, 3>();
TestConversionPass<AnyToAnySystem, AutoDiffXd, Expression, 4>();
TestConversionPass<AnyToAnySystem, Expression, double, 5>();
TestConversionPass<AnyToAnySystem, Expression, AutoDiffXd, 6>();
}
GTEST_TEST(SystemScalarConverterTest, TestNonSymbolicSystem) {
// The always-disabled cases.
TestConversionFail<NonSymbolicSystem, double, double>();
TestConversionFail<NonSymbolicSystem, AutoDiffXd, AutoDiffXd>();
// All Expression conversions are disabled.
//
// We cannot test TestConversionFail<foo, Expression>, because in order to
// call Convert, we need a reference to the come-from type (Expression), and
// instantiating a NonSymbolicSystem<Expression> does not even compile.
// Instead, we just confirm that the converter claims to not support it.
TestConversionFail<NonSymbolicSystem, Expression, double>();
TestConversionFail<NonSymbolicSystem, Expression, AutoDiffXd>();
const SystemScalarConverter dut(SystemTypeTag<NonSymbolicSystem>{});
EXPECT_FALSE((dut.IsConvertible<double, Expression>()));
EXPECT_FALSE((dut.IsConvertible<AutoDiffXd, Expression>()));
// We support all remaining combinations of standard types.
TestConversionPass<NonSymbolicSystem, double, AutoDiffXd, 1>();
TestConversionPass<NonSymbolicSystem, AutoDiffXd, double, 2>();
}
GTEST_TEST(SystemScalarConverterTest, TestFromDoubleSystem) {
// The always-disabled cases.
TestConversionFail<FromDoubleSystem, double, double>();
TestConversionFail<FromDoubleSystem, AutoDiffXd, AutoDiffXd>();
TestConversionFail<FromDoubleSystem, Expression, Expression>();
// The from-non-double conversions are disabled.
TestConversionFail<FromDoubleSystem, double, Expression>();
TestConversionFail<FromDoubleSystem, AutoDiffXd, Expression>();
TestConversionFail<FromDoubleSystem, Expression, AutoDiffXd>();
TestConversionFail<FromDoubleSystem, double, AutoDiffXd>();
// We support all remaining combinations of standard types.
TestConversionPass<FromDoubleSystem, Expression, double, 1>();
TestConversionPass<FromDoubleSystem, AutoDiffXd, double, 2>();
}
GTEST_TEST(SystemScalarConverterTest, SubclassMismatch) {
// When correctly configured, converting the subclass type is successful.
{
SystemScalarConverter dut(SystemTypeTag<SubclassOfAnyToAnySystem>{});
const SubclassOfAnyToAnySystem<double> original;
const std::unique_ptr<System<AutoDiffXd>> converted =
dut.Convert<AutoDiffXd, double>(original);
EXPECT_NE(converted, nullptr);
}
// When incorrectly configured, converting the subclass type throws.
{
SystemScalarConverter dut(SystemTypeTag<AnyToAnySystem>{});
const SubclassOfAnyToAnySystem<double> original;
EXPECT_THROW(({
try {
dut.Convert<AutoDiffXd, double>(original);
} catch (const std::runtime_error& e) {
EXPECT_THAT(
std::string(e.what()),
testing::MatchesRegex(
"SystemScalarConverter was configured to convert a "
".*::AnyToAnySystem<double> into a "
".*::AnyToAnySystem<drake::AutoDiffXd> but was called with a "
".*::SubclassOfAnyToAnySystem<double> at runtime"));
throw;
}
}), std::runtime_error);
}
// However, if subtype checking is off, the conversion is allowed to upcast.
{
auto dut = SystemScalarConverter::MakeWithoutSubtypeChecking<
AnyToAnySystem>();
const SubclassOfAnyToAnySystem<double> original;
EXPECT_TRUE(is_dynamic_castable<AnyToAnySystem<AutoDiffXd>>(
dut.Convert<AutoDiffXd, double>(original)));
}
}
GTEST_TEST(SystemScalarConverterTest, RemoveUnlessAlsoSupportedBy) {
SystemScalarConverter dut(SystemTypeTag<AnyToAnySystem>{});
const SystemScalarConverter non_symbolic(SystemTypeTag<NonSymbolicSystem>{});
const SystemScalarConverter from_double(SystemTypeTag<FromDoubleSystem>{});
// These are the defaults per TestAnyToAnySystem above.
EXPECT_TRUE((dut.IsConvertible<double, AutoDiffXd>()));
EXPECT_TRUE((dut.IsConvertible<double, Expression>()));
EXPECT_TRUE((dut.IsConvertible<AutoDiffXd, double >()));
EXPECT_TRUE((dut.IsConvertible<AutoDiffXd, Expression>()));
EXPECT_TRUE((dut.IsConvertible<Expression, double >()));
EXPECT_TRUE((dut.IsConvertible<Expression, AutoDiffXd>()));
// We remove symbolic support. Only double <=> AutoDiff remains.
dut.RemoveUnlessAlsoSupportedBy(non_symbolic);
EXPECT_TRUE((dut.IsConvertible< double, AutoDiffXd>()));
EXPECT_TRUE((dut.IsConvertible< AutoDiffXd, double >()));
EXPECT_FALSE((dut.IsConvertible<double, Expression>()));
EXPECT_FALSE((dut.IsConvertible<AutoDiffXd, Expression>()));
EXPECT_FALSE((dut.IsConvertible<Expression, double >()));
EXPECT_FALSE((dut.IsConvertible<Expression, AutoDiffXd>()));
// We remove from-AutoDiff support. Only AutoDiff <= double remains.
dut.RemoveUnlessAlsoSupportedBy(from_double);
EXPECT_TRUE((dut.IsConvertible< AutoDiffXd, double >()));
EXPECT_FALSE((dut.IsConvertible<double, AutoDiffXd>()));
EXPECT_FALSE((dut.IsConvertible<double, Expression>()));
EXPECT_FALSE((dut.IsConvertible<AutoDiffXd, Expression>()));
EXPECT_FALSE((dut.IsConvertible<Expression, double >()));
EXPECT_FALSE((dut.IsConvertible<Expression, AutoDiffXd>()));
// The conversion still actually works.
const AnyToAnySystem<double> system{22};
EXPECT_TRUE(is_dynamic_castable<AnyToAnySystem<AutoDiffXd>>(
dut.Convert<AutoDiffXd, double>(system)));
}
GTEST_TEST(SystemScalarConverterTest, Remove) {
SystemScalarConverter dut(SystemTypeTag<AnyToAnySystem>{});
// These are the defaults per TestAnyToAnySystem above.
EXPECT_TRUE((dut.IsConvertible<double, AutoDiffXd>()));
EXPECT_TRUE((dut.IsConvertible<double, Expression>()));
EXPECT_TRUE((dut.IsConvertible<AutoDiffXd, double >()));
EXPECT_TRUE((dut.IsConvertible<AutoDiffXd, Expression>()));
EXPECT_TRUE((dut.IsConvertible<Expression, double >()));
EXPECT_TRUE((dut.IsConvertible<Expression, AutoDiffXd>()));
// We remove symbolic support. Only double <=> AutoDiff remains.
dut.Remove<double, Expression>();
dut.Remove<AutoDiffXd, Expression>();
dut.Remove<Expression, double >();
dut.Remove<Expression, AutoDiffXd>();
EXPECT_TRUE((dut.IsConvertible< double, AutoDiffXd>()));
EXPECT_FALSE((dut.IsConvertible<double, Expression>()));
EXPECT_TRUE((dut.IsConvertible< AutoDiffXd, double >()));
EXPECT_FALSE((dut.IsConvertible<AutoDiffXd, Expression>()));
EXPECT_FALSE((dut.IsConvertible<Expression, double >()));
EXPECT_FALSE((dut.IsConvertible<Expression, AutoDiffXd>()));
// The conversion still actually works.
const AnyToAnySystem<double> system{22};
EXPECT_TRUE(is_dynamic_castable<AnyToAnySystem<AutoDiffXd>>(
dut.Convert<AutoDiffXd, double>(system)));
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/basic_vector_test.cc | #include "drake/systems/framework/basic_vector.h"
#include <cmath>
#include <sstream>
#include <Eigen/Dense>
#include <gtest/gtest.h>
#include "drake/common/eigen_types.h"
#include "drake/common/fmt_eigen.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/systems/framework/test_utilities/my_vector.h"
namespace drake {
namespace systems {
namespace {
// Tests the initializer_list functionality.
GTEST_TEST(BasicVectorTest, InitializerList) {
const BasicVector<double> empty1; // Default constructor.
const BasicVector<double> empty2{}; // Initializer list.
EXPECT_EQ(0, empty1.size());
EXPECT_EQ(0, empty2.size());
const BasicVector<double> pair{1.0, 2.0};
ASSERT_EQ(2, pair.size());
EXPECT_EQ(1.0, pair[0]);
EXPECT_EQ(2.0, pair[1]);
const BasicVector<double> from_floats{3.0f, 4.0f, 5.0f};
ASSERT_EQ(3, from_floats.size());
EXPECT_EQ(3.0, from_floats[0]);
EXPECT_EQ(4.0, from_floats[1]);
EXPECT_EQ(5.0, from_floats[2]);
const BasicVector<AutoDiffXd> autodiff{22.0};
ASSERT_EQ(1, autodiff.size());
EXPECT_EQ(22.0, autodiff[0].value());
}
GTEST_TEST(BasicVectorTest, Access) {
const BasicVector<double> pair{1.0, 2.0};
EXPECT_EQ(1.0, pair.GetAtIndex(0));
EXPECT_EQ(2.0, pair.GetAtIndex(1));
EXPECT_EQ(Eigen::Vector2d(1.0, 2.0), pair.value());
// To be deprecated: get_value() wraps a VectorBlock around the value.
EXPECT_EQ(pair.value(), pair.get_value());
}
GTEST_TEST(BasicVectorTest, OutOfRange) {
BasicVector<double> pair{1.0, 2.0};
EXPECT_THROW(pair.GetAtIndex(-1), std::exception);
EXPECT_THROW(pair.GetAtIndex(10), std::exception);
EXPECT_THROW(pair.SetAtIndex(-1, 0.0), std::exception);
EXPECT_THROW(pair.SetAtIndex(10, 0.0), std::exception);
}
// Tests SetZero functionality.
GTEST_TEST(BasicVectorTest, SetZero) {
BasicVector<double> vec{1.0, 2.0, 3.0};
EXPECT_EQ(Eigen::Vector3d(1.0, 2.0, 3.0), vec.value());
vec.SetZero();
EXPECT_EQ(Eigen::Vector3d(0, 0, 0), vec.value());
}
// Tests that the BasicVector<double> is initialized to NaN.
GTEST_TEST(BasicVectorTest, DoubleInitiallyNaN) {
BasicVector<double> vec(3);
Eigen::Vector3d expected(NAN, NAN, NAN);
EXPECT_TRUE(CompareMatrices(expected, vec.value(),
Eigen::NumTraits<double>::epsilon(),
MatrixCompareType::absolute));
}
// Tests that the BasicVector<AutoDiffXd> is initialized to NaN.
GTEST_TEST(BasicVectorTest, AutodiffInitiallyNaN) {
BasicVector<AutoDiffXd> vec(3);
EXPECT_TRUE(std::isnan(vec[0].value()));
EXPECT_TRUE(std::isnan(vec[1].value()));
EXPECT_TRUE(std::isnan(vec[2].value()));
}
// Tests that the BasicVector<symbolic::Expression> is initialized to NaN.
GTEST_TEST(BasicVectorTest, SymbolicInitiallyNaN) {
BasicVector<symbolic::Expression> vec(1);
EXPECT_TRUE(symbolic::is_nan(vec.value()[0]));
}
// Tests BasicVector<T>::Make.
GTEST_TEST(BasicVectorTest, Make) {
auto dut1 = BasicVector<double>::Make(1.0, 2.0);
auto dut2 = BasicVector<double>::Make({3.0, 4.0});
EXPECT_TRUE(CompareMatrices(dut1->value(), Eigen::Vector2d(1.0, 2.0)));
EXPECT_TRUE(CompareMatrices(dut2->value(), Eigen::Vector2d(3.0, 4.0)));
}
// Tests that BasicVector<symbolic::Expression>::Make does what it says on
// the tin.
GTEST_TEST(BasicVectorTest, MakeSymbolic) {
auto vec = BasicVector<symbolic::Expression>::Make(
symbolic::Variable("x"),
2.0,
symbolic::Variable("y") + 2.0);
EXPECT_EQ("x", vec->GetAtIndex(0).to_string());
EXPECT_EQ("2", vec->GetAtIndex(1).to_string());
EXPECT_EQ("(2 + y)", vec->GetAtIndex(2).to_string());
}
// Tests that the BasicVector has a size as soon as it is constructed.
GTEST_TEST(BasicVectorTest, Size) {
BasicVector<double> vec(5);
EXPECT_EQ(5, vec.size());
}
// Tests that the BasicVector can be mutated in-place.
GTEST_TEST(BasicVectorTest, Mutate) {
BasicVector<double> vec(2);
vec.get_mutable_value() << 1, 2;
Eigen::Vector2d expected;
expected << 1, 2;
EXPECT_EQ(expected, vec.value());
}
// Tests that the BasicVector can be addressed as an array.
GTEST_TEST(BasicVectorTest, ArrayOperator) {
BasicVector<double> vec(2);
vec[0] = 76;
vec[1] = 42;
Eigen::Vector2d expected;
expected << 76, 42;
EXPECT_EQ(expected, vec.value());
const auto& const_vec = vec;
EXPECT_EQ(76, const_vec[0]);
EXPECT_EQ(42, const_vec[1]);
}
// Tests that the BasicVector can be set from another vector.
GTEST_TEST(BasicVectorTest, SetWholeVector) {
BasicVector<double> vec(2);
vec.get_mutable_value() << 1, 2;
Eigen::Vector2d next_value;
next_value << 3, 4;
vec.set_value(next_value);
EXPECT_EQ(next_value, vec.value());
Eigen::Vector2d another_value;
another_value << 5, 6;
vec.SetFromVector(another_value);
EXPECT_EQ(another_value, vec.value());
EXPECT_THROW(vec.SetFromVector(Eigen::Vector3d::Zero()), std::exception);
}
// Tests that the BasicVector can be set from another vector base.
GTEST_TEST(BasicVectorTest, SetFrom) {
BasicVector<double> vec(2);
vec.get_mutable_value() << 1, 2;
BasicVector<double> next_vec(2);
next_vec.get_mutable_value() << 3, 4;
vec.SetFrom(next_vec);
EXPECT_EQ(next_vec.value(), vec.value());
EXPECT_THROW(vec.SetFrom(BasicVector<double>(3)), std::exception);
}
// Tests that when BasicVector is cloned, its data is preserved.
GTEST_TEST(BasicVectorTest, Clone) {
BasicVector<double> vec(2);
vec.get_mutable_value() << 1, 2;
std::unique_ptr<BasicVector<double>> clone = vec.Clone();
Eigen::Vector2d expected;
expected << 1, 2;
EXPECT_EQ(expected, clone->value());
}
// Tests that an error is thrown when the BasicVector is set from a vector
// of a different size.
GTEST_TEST(BasicVectorTest, ReinitializeInvalid) {
BasicVector<double> vec(2);
Eigen::Vector3d next_value;
next_value << 3, 4, 5;
EXPECT_THROW(vec.set_value(next_value), std::exception);
}
// Tests all += * operations for BasicVector.
GTEST_TEST(BasicVectorTest, PlusEqScaled) {
BasicVector<double> ogvec(2), vec1(2), vec2(2), vec3(2), vec4(2), vec5(2);
Eigen::Vector2d ans1, ans2, ans3, ans4, ans5;
ogvec.SetZero();
vec1.get_mutable_value() << 1, 2;
vec2.get_mutable_value() << 3, 5;
vec3.get_mutable_value() << 7, 11;
vec4.get_mutable_value() << 13, 17;
vec5.get_mutable_value() << 19, 23;
VectorBase<double>& v1 = vec1;
VectorBase<double>& v2 = vec2;
VectorBase<double>& v3 = vec3;
VectorBase<double>& v4 = vec4;
VectorBase<double>& v5 = vec5;
ogvec.PlusEqScaled(2, v1);
ans1 << 2, 4;
EXPECT_EQ(ans1, ogvec.value());
ogvec.SetZero();
ogvec.PlusEqScaled({{2, v1}, {3, v2}});
ans2 << 11, 19;
EXPECT_EQ(ans2, ogvec.value());
ogvec.SetZero();
ogvec.PlusEqScaled({{2, v1}, {3, v2}, {5, v3}});
ans3 << 46, 74;
EXPECT_EQ(ans3, ogvec.value());
ogvec.SetZero();
ogvec.PlusEqScaled({{2, v1}, {3, v2}, {5, v3}, {7, v4}});
ans4 << 137, 193;
EXPECT_EQ(ans4, ogvec.value());
ogvec.SetZero();
ogvec.PlusEqScaled({{2, v1}, {3, v2}, {5, v3}, {7, v4}, {11, v5}});
ans5 << 346, 446;
EXPECT_EQ(ans5, ogvec.value());
}
template <typename T>
class TypedBasicVectorTest : public ::testing::Test {};
using DefaultScalars =
::testing::Types<double, AutoDiffXd, symbolic::Expression>;
TYPED_TEST_SUITE(TypedBasicVectorTest, DefaultScalars);
// Tests ability to stream a BasicVector into a string.
TYPED_TEST(TypedBasicVectorTest, StringStream) {
using T = TypeParam;
BasicVector<T> vec(3);
vec.get_mutable_value() << 1.0, 2.2, 3.3;
std::stringstream s;
s << "hello " << vec << " world";
const std::string expected =
fmt::format("hello {} world", fmt_eigen(vec.value().transpose()));
EXPECT_EQ(s.str(), expected);
}
// Tests ability to stream a BasicVector of size zero into a string.
TYPED_TEST(TypedBasicVectorTest, ZeroLengthStringStream) {
using T = TypeParam;
BasicVector<T> vec(0);
std::stringstream s;
s << "foo [" << vec << "] bar";
const std::string expected =
fmt::format("foo [{}] bar", fmt_eigen(vec.value().transpose()));
EXPECT_EQ(s.str(), expected);
}
// Tests the default set of bounds (empty).
GTEST_TEST(BasicVectorTest, DefaultCalcInequalityConstraint) {
VectorX<double> value = VectorX<double>::Ones(22);
BasicVector<double> vec(1);
Eigen::VectorXd lower, upper;
// Deliberately set lower/upper to size 2, to check if GetElementBounds will
// resize the bounds to empty size.
lower.resize(2);
upper.resize(2);
vec.GetElementBounds(&lower, &upper);
EXPECT_EQ(lower.size(), 0);
EXPECT_EQ(upper.size(), 0);
}
// Tests the protected `::values()` methods.
GTEST_TEST(BasicVectorTest, ValuesAccess) {
MyVector2d dut;
dut[0] = 11.0;
dut[1] = 22.0;
// Values are as expected.
ASSERT_EQ(dut.values().size(), 2);
EXPECT_EQ(dut.values()[0], 11.0);
EXPECT_EQ(dut.values()[1], 22.0);
dut.values()[0] = 33.0;
// The const overload is the same.
const auto& const_dut = dut;
EXPECT_EQ(&dut.values(), &const_dut.values());
EXPECT_EQ(const_dut.values()[0], 33.0);
}
// Tests for reasonable exception message text; because the formatting is
// reused from VectorBase, this effectively tests the formatting for all
// subclasses of VectorBase.
GTEST_TEST(BasicVectorTest, ExceptionMessages) {
BasicVector<double> pair{1.0, 2.0};
DRAKE_EXPECT_THROWS_MESSAGE(
pair.GetAtIndex(-1),
"Index -1 is not within \\[0, 2\\) while accessing .*BasicVector.*");
DRAKE_EXPECT_THROWS_MESSAGE(
pair.GetAtIndex(10),
"Index 10 is not within \\[0, 2\\) while accessing .*BasicVector.*");
DRAKE_EXPECT_THROWS_MESSAGE(
pair.SetFromVector(Eigen::Vector3d::Zero()),
"Operand vector size 3 does not match this .*BasicVector.* size 2");
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/system_test.cc | #include "drake/systems/framework/system.h"
#include <memory>
#include <stdexcept>
#include <Eigen/Dense>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "drake/common/random.h"
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/unused.h"
#include "drake/systems/framework/abstract_value_cloner.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/context.h"
#include "drake/systems/framework/leaf_context.h"
#include "drake/systems/framework/leaf_output_port.h"
#include "drake/systems/framework/system_output.h"
#include "drake/systems/framework/test_utilities/my_vector.h"
namespace drake {
namespace systems {
namespace {
const int kSize = 3;
// Note that Systems in this file are derived directly from drake::System for
// testing purposes. User Systems should be derived only from LeafSystem which
// handles much of the bookkeeping you'll see here, and won't need to call
// methods that are intended only for internal use. Some additional System tests
// are found in leaf_system_test.cc in order to exploit LeafSystem to satisfy
// the many pure virtuals in System.
// This class absorbs most of the boilerplate of deriving directly from
// System<T>. Implementation choices (method bodies, override vs. final) were
// made to support the needs of the derived classes and tests in this file.
template <typename T>
class TestSystemBase : public System<T> {
public:
// @param num_numeric_param_groups
// The number of parameter groups to be allocated. Each group has one
// numeric value.
// @param num_continuous_states
// The size of q. If overriding AllocateTimeDerivatives(), this value
// should match the number of derivatives returned by that function.
explicit TestSystemBase(int num_numeric_params_groups = 0,
int num_continuous_states = 0)
: System<T>(SystemScalarConverter{}),
num_numeric_param_groups_(num_numeric_params_groups),
num_continuous_states_(num_continuous_states) {}
void SetDefaultParameters(const Context<T>&, Parameters<T>*) const override {}
void SetDefaultState(const Context<T>&, State<T>*) const override {}
void AddTriggeredWitnessFunctionToCompositeEventCollection(
Event<T>*, CompositeEventCollection<T>*) const final {
ADD_FAILURE() << "A test called a method that was expected to be unused.";
}
std::unique_ptr<EventCollection<PublishEvent<T>>>
AllocateForcedPublishEventCollection() const final {
return LeafEventCollection<PublishEvent<T>>::MakeForcedEventCollection();
}
std::unique_ptr<EventCollection<DiscreteUpdateEvent<T>>>
AllocateForcedDiscreteUpdateEventCollection() const final {
return LeafEventCollection<
DiscreteUpdateEvent<T>>::MakeForcedEventCollection();
}
std::unique_ptr<EventCollection<UnrestrictedUpdateEvent<T>>>
AllocateForcedUnrestrictedUpdateEventCollection() const final {
return LeafEventCollection<
UnrestrictedUpdateEvent<T>>::MakeForcedEventCollection();
}
std::unique_ptr<ContinuousState<T>> AllocateTimeDerivatives() const override {
auto result = std::make_unique<ContinuousState<T>>();
result->set_system_id(this->get_system_id());
return result;
}
std::unique_ptr<DiscreteValues<T>> AllocateDiscreteVariables()
const override {
auto result = std::make_unique<DiscreteValues<T>>();
result->set_system_id(this->get_system_id());
return result;
}
private:
std::unique_ptr<ContextBase> DoAllocateContext() const final {
auto context = std::make_unique<LeafContext<T>>();
this->InitializeContextBase(context.get());
if (num_numeric_param_groups_ > 0) {
// Each parameter group has a single numeric parameter of zero.
std::vector<std::unique_ptr<BasicVector<T>>> numeric_params;
for (int g = 0; g < num_numeric_param_groups_; ++g) {
numeric_params.emplace_back(
std::make_unique<BasicVector<T>>(std::initializer_list<T>{0.0}));
}
auto parameters =
std::make_unique<Parameters<T>>(std::move(numeric_params));
parameters->set_system_id(this->get_system_id());
context->init_parameters(std::move(parameters));
DRAKE_DEMAND(context->get_parameters().num_numeric_parameter_groups() ==
num_numeric_param_groups_);
}
// Allocate requested continuous state variables.
auto state = std::make_unique<ContinuousState<T>>(
std::make_unique<BasicVector<T>>(num_continuous_states_));
context->init_continuous_state(std::move(state));
return context;
}
std::unique_ptr<CompositeEventCollection<T>>
DoAllocateCompositeEventCollection() const final {
auto result = std::make_unique<LeafCompositeEventCollection<T>>();
result->set_system_id(this->get_system_id());
return result;
}
T DoCalcWitnessValue(const Context<T>&,
const WitnessFunction<T>&) const final {
ADD_FAILURE() << "A test called a method that was expected to be unused.";
return {};
}
void DoApplyDiscreteVariableUpdate(
const EventCollection<DiscreteUpdateEvent<T>>& events,
DiscreteValues<T>* discrete_state, Context<T>* context) const final {
ADD_FAILURE() << "A test called a method that was expected to be unused.";
}
EventStatus DispatchUnrestrictedUpdateHandler(
const Context<T>&, const EventCollection<UnrestrictedUpdateEvent<T>>&,
State<T>*) const final {
ADD_FAILURE() << "A test called a method that was expected to be unused.";
return EventStatus::DidNothing();
}
void DoApplyUnrestrictedUpdate(
const EventCollection<UnrestrictedUpdateEvent<T>>& events,
State<T>* state, Context<T>* context) const final {
ADD_FAILURE() << "A test called a method that was expected to be unused.";
}
std::map<PeriodicEventData, std::vector<const Event<T>*>,
PeriodicEventDataComparator>
DoMapPeriodicEventsByTiming(const Context<T>&) const final {
ADD_FAILURE() << "A test called a method that was expected to be unused.";
return {};
}
std::unique_ptr<AbstractValue> DoAllocateInput(
const InputPort<T>&) const override {
ADD_FAILURE() << "A test called a method that was expected to be unused.";
return {};
}
void DoCalcTimeDerivatives(const Context<T>& context,
ContinuousState<T>* derivatives) const override {}
void DoFindUniquePeriodicDiscreteUpdatesOrThrow(
const char* api_name, const Context<T>& context,
std::optional<PeriodicEventData>* timing,
EventCollection<DiscreteUpdateEvent<T>>* events) const override {
ADD_FAILURE() << "A test called a method that was expected to be unused.";
}
EventStatus DispatchPublishHandler(
const Context<T>& context,
const EventCollection<PublishEvent<T>>& event_info) const override {
ADD_FAILURE() << "A test called a method that was expected to be unused.";
return EventStatus::DidNothing();
}
EventStatus DispatchDiscreteVariableUpdateHandler(
const Context<T>& context,
const EventCollection<DiscreteUpdateEvent<T>>& event_info,
DiscreteValues<T>* discrete_state) const override {
ADD_FAILURE() << "A test called a method that was expected to be unused.";
return EventStatus::DidNothing();
}
std::multimap<int, int> GetDirectFeedthroughs() const override {
ADD_FAILURE() << "A test called a method that was expected to be unused.";
return {};
}
// The numbers of numeric parameter groups or continuous states created when
// allocating a context.
int num_numeric_param_groups_{};
int num_continuous_states_{};
};
// A shell System to test the default implementations.
class TestSystem : public TestSystemBase<double> {
public:
TestSystem() {
this->set_forced_publish_events(
this->AllocateForcedPublishEventCollection());
this->set_forced_discrete_update_events(
this->AllocateForcedDiscreteUpdateEventCollection());
this->set_forced_unrestricted_update_events(
this->AllocateForcedUnrestrictedUpdateEventCollection());
this->set_name("TestSystem");
}
~TestSystem() override {}
using System::AddConstraint; // allow access to protected method.
using System::DeclareInputPort;
const InputPort<double>& AddAbstractInputPort() {
return this->DeclareInputPort(kUseDefaultName, kAbstractValued, 0);
}
LeafOutputPort<double>& AddAbstractOutputPort() {
// Create an abstract output port with dummy alloc and calc.
CacheEntry& cache_entry = this->DeclareCacheEntry(
"null output port", ValueProducer(
0, &ValueProducer::NoopCalc));
// TODO(sherm1) Use implicit_cast when available (from abseil). Several
// places in this test.
auto port = internal::FrameworkFactory::Make<LeafOutputPort<double>>(
this, // implicit_cast<const System<T>*>(this)
this, // implicit_cast<const SystemBase*>(this)
this->get_system_id(),
"y" + std::to_string(num_output_ports()),
OutputPortIndex(this->num_output_ports()),
assign_next_dependency_ticket(),
kAbstractValued, 0, &cache_entry);
LeafOutputPort<double>* const port_ptr = port.get();
this->AddOutputPort(std::move(port));
return *port_ptr;
}
std::multimap<int, int> GetDirectFeedthroughs() const override {
std::multimap<int, int> pairs;
// Report *everything* as having direct feedthrough.
for (int i = 0; i < num_input_ports(); ++i) {
for (int o = 0; o < num_output_ports(); ++o) {
pairs.emplace(i, o);
}
}
return pairs;
}
int get_publish_count() const { return publish_count_; }
int get_update_count() const { return update_count_; }
const std::vector<int>& get_published_numbers() const {
return published_numbers_;
}
const std::vector<int>& get_updated_numbers() const {
return updated_numbers_;
}
// The default publish function.
void MyPublish(const Context<double>& context,
const std::vector<const PublishEvent<double>*>& events) const {
++publish_count_;
}
protected:
EventStatus DispatchPublishHandler(
const Context<double>& context,
const EventCollection<PublishEvent<double>>& events) const final {
const LeafEventCollection<PublishEvent<double>>& leaf_events =
dynamic_cast<const LeafEventCollection<PublishEvent<double>>&>(events);
if (leaf_events.HasEvents()) {
this->MyPublish(context, leaf_events.get_events());
return EventStatus::Succeeded();
}
return EventStatus::DidNothing();
}
EventStatus DispatchDiscreteVariableUpdateHandler(
const Context<double>& context,
const EventCollection<DiscreteUpdateEvent<double>>& events,
DiscreteValues<double>* discrete_state) const final {
const LeafEventCollection<DiscreteUpdateEvent<double>>& leaf_events =
dynamic_cast<const LeafEventCollection<DiscreteUpdateEvent<double>>&>(
events);
if (leaf_events.HasEvents()) {
this->MyCalcDiscreteVariableUpdates(context, leaf_events.get_events(),
discrete_state);
return EventStatus::Succeeded();
}
return EventStatus::DidNothing();
}
// Sets up an arbitrary mapping from the current time to the next discrete
// action, to exercise several different forms of discrete action.
void DoCalcNextUpdateTime(const Context<double>& context,
CompositeEventCollection<double>* event_info,
double* time) const override {
*time = context.get_time() + 1;
if (context.get_time() < 10.0) {
PublishEvent<double> event(TriggerType::kPeriodic);
event.AddToComposite(event_info);
} else {
DiscreteUpdateEvent<double> event(TriggerType::kPeriodic);
event.AddToComposite(event_info);
}
}
// The default update function.
void MyCalcDiscreteVariableUpdates(
const Context<double>& context,
const std::vector<const DiscreteUpdateEvent<double>*>& events,
DiscreteValues<double>* discrete_state) const {
++update_count_;
}
private:
mutable int publish_count_ = 0;
mutable int update_count_ = 0;
mutable std::vector<int> published_numbers_;
mutable std::vector<int> updated_numbers_;
};
class SystemTest : public ::testing::Test {
protected:
void SetUp() override { context_ = system_.CreateDefaultContext(); }
TestSystem system_;
std::unique_ptr<Context<double>> context_;
};
TEST_F(SystemTest, ContextBelongsWithSystem) {
TestSystem system2;
// These just uses a couple of arbitrary methods to test that a Context not
// created by a System throws the appropriate exception.
DRAKE_EXPECT_THROWS_MESSAGE(system2.ForcedPublish(*context_),
"[^]*#framework-context-system-mismatch.*");
DRAKE_EXPECT_THROWS_MESSAGE(system2.SetDefaultContext(context_.get()),
"[^]*#framework-context-system-mismatch.*");
}
TEST_F(SystemTest, MapVelocityToConfigurationDerivatives) {
auto state_vec1 = BasicVector<double>::Make({1.0, 2.0, 3.0});
BasicVector<double> state_vec2(kSize);
system_.MapVelocityToQDot(*context_, *state_vec1, &state_vec2);
EXPECT_EQ(1.0, state_vec2[0]);
EXPECT_EQ(2.0, state_vec2[1]);
EXPECT_EQ(3.0, state_vec2[2]);
// Test Eigen specialized function specially.
system_.MapVelocityToQDot(*context_, state_vec1->CopyToVector(), &state_vec2);
EXPECT_EQ(1.0, state_vec2[0]);
EXPECT_EQ(2.0, state_vec2[1]);
EXPECT_EQ(3.0, state_vec2[2]);
}
TEST_F(SystemTest, MapConfigurationDerivativesToVelocity) {
auto state_vec1 = BasicVector<double>::Make({1.0, 2.0, 3.0});
BasicVector<double> state_vec2(kSize);
system_.MapQDotToVelocity(*context_, *state_vec1, &state_vec2);
EXPECT_EQ(1.0, state_vec2[0]);
EXPECT_EQ(2.0, state_vec2[1]);
EXPECT_EQ(3.0, state_vec2[2]);
// Test Eigen specialized function specially.
system_.MapQDotToVelocity(*context_, state_vec1->CopyToVector(), &state_vec2);
EXPECT_EQ(1.0, state_vec2[0]);
EXPECT_EQ(2.0, state_vec2[1]);
EXPECT_EQ(3.0, state_vec2[2]);
}
TEST_F(SystemTest, ConfigurationDerivativeVelocitySizeMismatch) {
auto state_vec1 = BasicVector<double>::Make({1.0, 2.0, 3.0});
BasicVector<double> state_vec2(kSize + 1);
EXPECT_THROW(system_.MapQDotToVelocity(*context_, *state_vec1, &state_vec2),
std::runtime_error);
}
TEST_F(SystemTest, VelocityConfigurationDerivativeSizeMismatch) {
auto state_vec1 = BasicVector<double>::Make({1.0, 2.0, 3.0});
BasicVector<double> state_vec2(kSize + 1);
EXPECT_THROW(system_.MapVelocityToQDot(*context_, *state_vec1, &state_vec2),
std::runtime_error);
}
// Tests that default publishing is invoked when no other handler is registered
// in DoCalcNextUpdateTime.
TEST_F(SystemTest, DiscretePublish) {
context_->SetTime(5.0);
auto event_info = system_.AllocateCompositeEventCollection();
system_.CalcNextUpdateTime(*context_, event_info.get());
const auto& events =
dynamic_cast<const LeafCompositeEventCollection<double>*>(
event_info.get())->get_publish_events().get_events();
EXPECT_EQ(events.size(), 1);
EXPECT_EQ(events.front()->get_trigger_type(),
TriggerType::kPeriodic);
const EventStatus status =
system_.Publish(*context_, event_info->get_publish_events());
EXPECT_TRUE(status.succeeded());
EXPECT_EQ(1, system_.get_publish_count());
}
// Tests that the default DoEvalDiscreteVariableUpdates is invoked when no other
// handler is registered in DoCalcNextUpdateTime.
TEST_F(SystemTest, DiscreteUpdate) {
context_->SetTime(15.0);
auto event_info = system_.AllocateCompositeEventCollection();
system_.CalcNextUpdateTime(*context_, event_info.get());
std::unique_ptr<DiscreteValues<double>> update =
system_.AllocateDiscreteVariables();
const EventStatus status = system_.CalcDiscreteVariableUpdate(
*context_, event_info->get_discrete_update_events(), update.get());
EXPECT_TRUE(status.succeeded());
EXPECT_EQ(1, system_.get_update_count());
}
// Tests that port references remain valid even if lots of other ports are added
// to the system, forcing a vector resize.
TEST_F(SystemTest, PortReferencesAreStable) {
const auto& first_input = system_.AddAbstractInputPort();
const auto& first_output = system_.AddAbstractOutputPort();
for (int i = 0; i < 1000; i++) {
system_.AddAbstractInputPort();
system_.AddAbstractOutputPort();
}
EXPECT_EQ(1001, system_.num_input_ports());
EXPECT_EQ(1001, system_.num_output_ports());
// Check for address equality.
EXPECT_EQ(&first_input, &system_.get_input_port(0));
EXPECT_EQ(&first_output, &system_.get_output_port(0));
// Check for valid content.
EXPECT_EQ(kAbstractValued, first_input.get_data_type());
EXPECT_EQ(kAbstractValued, first_output.get_data_type());
}
// Tests the convenience method for the case when we have exactly one port.
TEST_F(SystemTest, ExactlyOneInputPortConvenience) {
// No ports: fail.
DRAKE_EXPECT_THROWS_MESSAGE(system_.get_input_port(),
".*does not have any inputs");
// One port: pass.
system_.DeclareInputPort("one", kVectorValued, 2);
EXPECT_EQ(&system_.get_input_port(), &system_.get_input_port(0));
// One deprecated port: pass.
const_cast<InputPort<double>&>(system_.get_input_port(0))
.set_deprecation("deprecated");
EXPECT_EQ(&system_.get_input_port(), &system_.get_input_port(0));
// Two ports (one non-deprecated): pass.
system_.DeclareInputPort("two", kVectorValued, 2);
EXPECT_EQ(&system_.get_input_port(), &system_.get_input_port(1));
// Three ports (two non-deprecated): fail.
system_.DeclareInputPort("three", kVectorValued, 2);
DRAKE_EXPECT_THROWS_MESSAGE(system_.get_input_port(), ".*has 3 inputs.*");
// Three ports (one non-deprecated): pass.
const_cast<InputPort<double>&>(system_.get_input_port(1))
.set_deprecation("deprecated");
EXPECT_EQ(&system_.get_input_port(), &system_.get_input_port(2));
// Three deprecated ports: fail
const_cast<InputPort<double>&>(system_.get_input_port(2))
.set_deprecation("deprecated");
DRAKE_EXPECT_THROWS_MESSAGE(system_.get_input_port(), ".*has 3 inputs.*");
}
// Tests the convenience method for the case when we have exactly one port.
TEST_F(SystemTest, ExactlyOneOutputPortConvenience) {
// No ports: fail.
DRAKE_EXPECT_THROWS_MESSAGE(system_.get_output_port(),
".*does not have any outputs");
// One port: pass.
system_.AddAbstractOutputPort();
EXPECT_EQ(&system_.get_output_port(), &system_.get_output_port(0));
// One deprecated port: pass.
const_cast<OutputPort<double>&>(system_.get_output_port(0))
.set_deprecation("deprecated");
EXPECT_EQ(&system_.get_output_port(), &system_.get_output_port(0));
// Two ports (one non-deprecated): pass.
system_.AddAbstractOutputPort();
EXPECT_EQ(&system_.get_output_port(), &system_.get_output_port(1));
// Three ports (two non-deprecated): fail.
system_.AddAbstractOutputPort();
DRAKE_EXPECT_THROWS_MESSAGE(system_.get_output_port(), ".*has 3 outputs.*");
// Three ports (one non-deprecated): pass.
const_cast<OutputPort<double>&>(system_.get_output_port(1))
.set_deprecation("deprecated");
EXPECT_EQ(&system_.get_output_port(), &system_.get_output_port(2));
// Three deprecated ports: fail.
const_cast<OutputPort<double>&>(system_.get_output_port(2))
.set_deprecation("deprecated");
DRAKE_EXPECT_THROWS_MESSAGE(system_.get_output_port(), ".*has 3 outputs.*");
}
TEST_F(SystemTest, PortNameTest) {
const auto& unnamed_input =
system_.DeclareInputPort(kUseDefaultName, kVectorValued, 2);
const auto& named_input =
system_.DeclareInputPort("my_input", kVectorValued, 3);
const auto& named_abstract_input =
system_.DeclareInputPort("abstract", kAbstractValued, 0);
EXPECT_EQ(unnamed_input.get_name(), "u0");
EXPECT_EQ(named_input.get_name(), "my_input");
EXPECT_EQ(named_abstract_input.get_name(), "abstract");
// Duplicate port names should throw.
DRAKE_EXPECT_THROWS_MESSAGE(
system_.DeclareInputPort("my_input", kAbstractValued, 0),
".*already has an input port named.*");
// Test string-based get_input_port accessors.
EXPECT_EQ(&system_.GetInputPort("u0"), &unnamed_input);
EXPECT_EQ(&system_.GetInputPort("my_input"), &named_input);
EXPECT_EQ(&system_.GetInputPort("abstract"), &named_abstract_input);
EXPECT_EQ(system_.HasInputPort("u0"), true);
EXPECT_EQ(system_.HasInputPort("fake_name"), false);
// Test output port names.
const auto& output_port = system_.AddAbstractOutputPort();
EXPECT_EQ(output_port.get_name(), "y0");
EXPECT_EQ(&system_.GetOutputPort("y0"), &output_port);
EXPECT_EQ(system_.HasOutputPort("y0"), true);
EXPECT_EQ(system_.HasOutputPort("fake_name"), false);
// Requesting a non-existing port name should throw.
DRAKE_EXPECT_THROWS_MESSAGE(
system_.GetInputPort("not_my_input"),
".*does not have an input port named.*");
DRAKE_EXPECT_THROWS_MESSAGE(
system_.GetOutputPort("not_my_output"),
".*does not have an output port named.*");
// Error messages should mention valid ports.
DRAKE_EXPECT_THROWS_MESSAGE(
system_.GetInputPort("not_my_input"),
".*valid port names: .*u0.*");
DRAKE_EXPECT_THROWS_MESSAGE(
system_.GetOutputPort("not_my_output"),
".*valid port names: .*y0.*");
}
TEST_F(SystemTest, PortNameNoPortsTest) {
DRAKE_EXPECT_THROWS_MESSAGE(
system_.GetInputPort("not_my_input"),
".* it has no input ports.*");
DRAKE_EXPECT_THROWS_MESSAGE(
system_.GetOutputPort("not_my_output"),
".* it has no output ports.*");
}
TEST_F(SystemTest, PortSelectionTest) {
// Input ports.
EXPECT_EQ(system_.get_input_port_selection(InputPortSelection::kNoInput),
nullptr);
EXPECT_EQ(system_.get_input_port_selection(
InputPortSelection::kUseFirstInputIfItExists),
nullptr);
const auto& input_port =
system_.DeclareInputPort("my_input", kVectorValued, 3);
EXPECT_EQ(system_.get_input_port_selection(
InputPortSelection::kUseFirstInputIfItExists),
&input_port);
EXPECT_EQ(system_.get_input_port_selection(InputPortIndex{0}),
&system_.get_input_port(0));
// Output ports.
EXPECT_EQ(system_.get_output_port_selection(OutputPortSelection::kNoOutput),
nullptr);
EXPECT_EQ(system_.get_output_port_selection(
OutputPortSelection::kUseFirstOutputIfItExists),
nullptr);
const auto& output_port = system_.AddAbstractOutputPort();
EXPECT_EQ(system_.get_output_port_selection(
OutputPortSelection::kUseFirstOutputIfItExists),
&output_port);
EXPECT_EQ(system_.get_output_port_selection(OutputPortIndex{0}),
&system_.get_output_port(0));
}
// Tests the constraint list logic.
TEST_F(SystemTest, SystemConstraintTest) {
EXPECT_EQ(system_.num_constraints(), 0);
EXPECT_THROW(system_.get_constraint(SystemConstraintIndex(0)),
std::out_of_range);
ContextConstraintCalc<double> calc = [](
const Context<double>& context, Eigen::VectorXd* value) {
unused(context);
(*value)[0] = 1.0;
};
const double kInf = std::numeric_limits<double>::infinity();
SystemConstraintIndex test_constraint =
system_.AddConstraint(std::make_unique<SystemConstraint<double>>(
&system_, calc, SystemConstraintBounds(Vector1d(0), std::nullopt),
"test"));
EXPECT_EQ(test_constraint, 0);
DRAKE_EXPECT_NO_THROW(system_.get_constraint(test_constraint));
const auto& constraint_ref = system_.get_constraint(test_constraint);
EXPECT_EQ(constraint_ref.description(), "test");
EXPECT_TRUE(constraint_ref.get_system_id().has_value());
EXPECT_EQ(*constraint_ref.get_system_id(), context_->get_system_id());
const double tol = 1e-6;
EXPECT_TRUE(system_.CheckSystemConstraintsSatisfied(*context_, tol));
ContextConstraintCalc<double> calc_false = [](
const Context<double>& context, Eigen::VectorXd* value) {
unused(context);
(*value)[0] = -1.0;
};
system_.AddConstraint(std::make_unique<SystemConstraint<double>>(
&system_, calc_false, SystemConstraintBounds(Vector1d(0), Vector1d(kInf)),
"bad constraint"));
EXPECT_FALSE(system_.CheckSystemConstraintsSatisfied(*context_, tol));
}
// Tests that by default, transmogrification fails appropriately.
// (For testing transmogrification success, we rely on leaf_system_test.)
TEST_F(SystemTest, TransmogrifyNotSupported) {
// Use the static method.
EXPECT_THROW(System<double>::ToAutoDiffXd<System>(system_), std::exception);
EXPECT_THROW(System<double>::ToSymbolic<System>(system_), std::exception);
EXPECT_THROW(
(System<double>::ToScalarType<AutoDiffXd, TestSystemBase>(system_)),
std::exception);
EXPECT_THROW(
(System<double>::ToScalarType<symbolic::Expression, TestSystemBase>(
system_)),
std::exception);
// Use the instance method that throws.
EXPECT_THROW(system_.ToAutoDiffXd(), std::exception);
EXPECT_THROW(system_.ToSymbolic(), std::exception);
EXPECT_THROW(system_.ToScalarType<AutoDiffXd>(), std::exception);
EXPECT_THROW(system_.ToScalarType<symbolic::Expression>(),
std::exception);
// Use the instance method that returns nullptr.
EXPECT_EQ(system_.ToAutoDiffXdMaybe(), nullptr);
EXPECT_EQ(system_.ToSymbolicMaybe(), nullptr);
EXPECT_EQ(system_.ToScalarTypeMaybe<AutoDiffXd>(), nullptr);
EXPECT_EQ(system_.ToScalarTypeMaybe<symbolic::Expression>(), nullptr);
// Spot check the specific converter object.
EXPECT_FALSE((
system_.get_system_scalar_converter().IsConvertible<double, double>()));
}
// Tests IsDifferenceEquationSystem works for this one System. Additional
// test coverage is provided in linear_system_test.cc and diagram_test.cc.
TEST_F(SystemTest, IsDifferenceEquationSystem) {
double period = 1.23;
EXPECT_FALSE(system_.IsDifferenceEquationSystem(&period));
// Confirm that the return parameter was not changed.
EXPECT_EQ(period, 1.23);
}
// Tests IsDifferentialEquationSystem works for this one System. Additional
// test coverage is provided in linear_system_test.cc and diagram_test.cc.
TEST_F(SystemTest, IsDifferentialEquationSystem) {
EXPECT_TRUE(system_.IsDifferentialEquationSystem());
system_.AddAbstractInputPort();
EXPECT_FALSE(system_.IsDifferentialEquationSystem());
}
// System used to test some contracts about setting default values in a Context
// (as documented on the SetDefaultInvocationContract test).
class TestDefaultSystem final : public TestSystemBase<double> {
public:
TestDefaultSystem()
: TestSystemBase<double>(/* num_numeric_params_groups= */ 1,
/* num_continuous_states= */ 1) {
this->set_name("TestDefaultSystem");
}
void SetDefaultParameters(const Context<double>& context,
Parameters<double>* parameters) const final {
DRAKE_DEMAND(context.get_parameters().num_numeric_parameter_groups() == 1);
BasicVector<double>& param = parameters->get_mutable_numeric_parameter(0);
param[0] = kMagicValue;
}
// The state simply copies the parameter value over. If the default parameters
// have been evaluated *first*, then the continuous state should contain the
// magic number.
void SetDefaultState(const Context<double>& context,
State<double>* state) const final {
const BasicVector<double>& param =
context.get_parameters().get_numeric_parameter(0);
state->get_mutable_continuous_state().get_mutable_vector()[0] = param[0];
}
constexpr static double kMagicValue = 17.5;
};
// Confirms the documented contract that the default parameters always get set
// before default state.
GTEST_TEST(SystemDefaultTest, SetDefaultInvocationContract) {
TestDefaultSystem system;
auto context = system.CreateDefaultContext();
EXPECT_EQ(context->get_state().get_continuous_state()[0],
TestDefaultSystem::kMagicValue);
}
template <typename T>
using TestTypedVector = MyVector<T, 1>;
// A shell System for AbstractValue IO test.
template <typename T>
class ValueIOTestSystem : public TestSystemBase<T> {
public:
// Has 4 input and 2 output ports.
// The first input / output pair are abstract type, but assumed to be
// std::string.
// The second input / output pair are vector type with length 1.
// There are two other vector-valued random input ports.
ValueIOTestSystem() {
this->set_forced_publish_events(
this->AllocateForcedPublishEventCollection());
this->set_forced_discrete_update_events(
this->AllocateForcedDiscreteUpdateEventCollection());
this->set_forced_unrestricted_update_events(
this->AllocateForcedUnrestrictedUpdateEventCollection());
this->DeclareInputPort(kUseDefaultName, kAbstractValued, 0);
this->AddOutputPort(internal::FrameworkFactory::Make<LeafOutputPort<T>>(
this, // implicit_cast<const System<T>*>(this)
this, // implicit_cast<const SystemBase*>(this)
this->get_system_id(),
"absport",
OutputPortIndex(this->num_output_ports()),
this->assign_next_dependency_ticket(),
kAbstractValued, 0 /* size */,
&this->DeclareCacheEntry(
"absport", &ValueIOTestSystem::CalcStringOutput)));
this->DeclareInputPort(kUseDefaultName, kVectorValued, 1);
this->DeclareInputPort("uniform", kVectorValued, 1,
RandomDistribution::kUniform);
this->DeclareInputPort("gaussian", kVectorValued, 1,
RandomDistribution::kGaussian);
this->AddOutputPort(internal::FrameworkFactory::Make<LeafOutputPort<T>>(
this, // implicit_cast<const System<T>*>(this)
this, // implicit_cast<const SystemBase*>(this)
this->get_system_id(),
"vecport",
OutputPortIndex(this->num_output_ports()),
this->assign_next_dependency_ticket(),
kVectorValued, 1 /* size */,
&this->DeclareCacheEntry(
"vecport", BasicVector<T>(1),
&ValueIOTestSystem::CalcVectorOutput)));
this->set_name("ValueIOTestSystem");
}
~ValueIOTestSystem() override {}
const InputPort<T>& AddAbstractInputPort() {
return this->DeclareInputPort(kUseDefaultName, kAbstractValued, 0);
}
std::unique_ptr<AbstractValue> DoAllocateInput(
const InputPort<T>& input_port) const override {
if (input_port.get_index() == 0) {
return AbstractValue::Make<std::string>();
} else {
return std::make_unique<Value<BasicVector<T>>>(TestTypedVector<T>{});
}
}
std::multimap<int, int> GetDirectFeedthroughs() const override {
std::multimap<int, int> pairs;
// Report *everything* as having direct feedthrough.
for (int i = 0; i < this->num_input_ports(); ++i) {
for (int o = 0; o < this->num_output_ports(); ++o) {
pairs.emplace(i, o);
}
}
return pairs;
}
// Appends "output" to input(0) for output(0).
void CalcStringOutput(const ContextBase& context,
std::string* output) const {
const std::string* str_in =
this->template EvalInputValue<std::string>(context, 0);
*output = *str_in + "output";
}
// Sets output(1) = 2 * input(1).
void CalcVectorOutput(const ContextBase& context_base,
BasicVector<T>* output) const {
const Context<T>& context = dynamic_cast<const Context<T>&>(context_base);
const BasicVector<T>* vec_in = this->EvalVectorInput(context, 1);
output->get_mutable_value() = 2 * vec_in->get_value();
}
};
// Just creates System and Context without providing values for inputs, to
// allow for lots of error conditions.
class SystemInputErrorTest : public ::testing::Test {
protected:
void SetUp() override {
context_ = system_.CreateDefaultContext();
}
ValueIOTestSystem<double> system_;
std::unique_ptr<Context<double>> context_;
};
// A BasicVector-derived type we can complain about in the next test.
template <typename T>
class WrongVector : public MyVector<T, 2> {
public:
using MyVector<T, 2>::MyVector;
};
// Test error messages from the EvalInput methods.
TEST_F(SystemInputErrorTest, CheckMessages) {
ASSERT_EQ(system_.num_input_ports(), 4);
// Sanity check that this works with a good port number.
DRAKE_EXPECT_NO_THROW(system_.get_input_port(1));
// Try some illegal port numbers.
DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(
system_.get_input_port(-1),
".*get_input_port.*negative.*-1.*illegal.*");
DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(
system_.EvalVectorInput(*context_, -1),
".*EvalVectorInput.*negative.*-1.*illegal.*");
DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(
system_.EvalAbstractInput(*context_, -2),
".*EvalAbstractInput.*negative.*-2.*illegal.*");
DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(
system_.EvalInputValue<int>(*context_, -3),
".*EvalInputValue.*negative.*-3.*illegal.*");
DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(
system_.get_input_port(9),
".*get_input_port.*no input port.*9.*only.*4.*");
DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(
system_.EvalVectorInput(*context_, 9),
".*EvalVectorInput.*no input port.*9.*only.*4.*");
DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(
system_.EvalAbstractInput(*context_, 10),
".*EvalAbstractInput.*no input port.*10.*only.*4.*");
DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(
system_.EvalInputValue<int>(*context_, 11),
".*EvalInputValue.*no input port.*11.*only.*4.*");
// No ports have values yet.
EXPECT_EQ(system_.EvalVectorInput(*context_, 1), nullptr);
EXPECT_EQ(system_.EvalAbstractInput(*context_, 1), nullptr);
EXPECT_EQ(system_.EvalInputValue<int>(*context_, 1), nullptr);
// Assign values to all ports. All but port 0 are BasicVector ports.
system_.AllocateFixedInputs(context_.get());
DRAKE_EXPECT_NO_THROW(
system_.EvalVectorInput(*context_, 2)); // BasicVector OK.
DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(
system_.EvalVectorInput<WrongVector>(*context_, 2),
".*EvalVectorInput.*expected.*WrongVector"
".*input port.*2.*actual.*MyVector.*");
DRAKE_EXPECT_NO_THROW(
system_.EvalInputValue<BasicVector<double>>(*context_, 1));
DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(
system_.EvalInputValue<int>(*context_, 1),
".*EvalInputValue.*expected.*int.*input port.*1.*actual.*MyVector.*");
// Now induce errors that only apply to abstract-valued input ports.
EXPECT_EQ(*system_.EvalInputValue<std::string>(*context_, 0), "");
DRAKE_EXPECT_NO_THROW(system_.EvalAbstractInput(*context_, 0));
DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(
system_.EvalVectorInput(*context_, 0),
".*EvalVectorInput.*vector port required.*input port.*0.*"
"was declared abstract.*");
DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(
system_.EvalInputValue<double>(*context_, 0),
".*EvalInputValue.*expected.*double.*input port.*0.*actual.*string.*");
}
// Provides values for some of the inputs and sets up for outputs.
class SystemIOTest : public ::testing::Test {
protected:
void SetUp() override {
context_ = test_sys_.CreateDefaultContext();
output_ = test_sys_.AllocateOutput();
// make string input
test_sys_.get_input_port(0).FixValue(context_.get(), "input");
// make vector input
test_sys_.get_input_port(1).FixValue(context_.get(), 2.0);
}
ValueIOTestSystem<double> test_sys_;
std::unique_ptr<Context<double>> context_;
std::unique_ptr<SystemOutput<double>> output_;
};
TEST_F(SystemIOTest, SystemValueIOTest) {
test_sys_.CalcOutput(*context_, output_.get());
EXPECT_EQ(context_->num_input_ports(), 4);
EXPECT_EQ(output_->num_ports(), 2);
EXPECT_EQ(output_->get_data(0)->get_value<std::string>(),
std::string("inputoutput"));
EXPECT_EQ(output_->get_vector_data(1)->get_value()(0), 4);
// Connected inputs ports can be evaluated. (Port #1 was set to [2]).
const auto* basic_vector = test_sys_.EvalVectorInput(*context_, 1);
ASSERT_NE(basic_vector, nullptr);
ASSERT_EQ(basic_vector->size(), 1);
EXPECT_EQ(basic_vector->GetAtIndex(0), 2.0);
// Disconnected inputs are nullptr.
EXPECT_EQ(test_sys_.EvalVectorInput(*context_, 2), nullptr);
// Test AllocateInput*
// Second input is not (yet) a TestTypedVector, since I haven't called the
// Allocate methods directly yet.
EXPECT_EQ(dynamic_cast<const TestTypedVector<double> *>(
test_sys_.EvalVectorInput(*context_, 1)),
nullptr);
// Now allocate.
test_sys_.AllocateFixedInputs(context_.get());
// First input should have been re-allocated to the empty string.
EXPECT_EQ(test_sys_.EvalAbstractInput(*context_, 0)->get_value<std::string>(),
"");
// Second input should now be of type TestTypedVector.
EXPECT_NE(dynamic_cast<const TestTypedVector<double> *>(
test_sys_.EvalVectorInput(*context_, 1)),
nullptr);
}
// Checks that the input ports randomness labels were set as expected.
TEST_F(SystemIOTest, RandomInputPortTest) {
EXPECT_FALSE(test_sys_.get_input_port(0).is_random());
EXPECT_FALSE(test_sys_.get_input_port(1).is_random());
EXPECT_TRUE(test_sys_.get_input_port(2).is_random());
EXPECT_TRUE(test_sys_.get_input_port(3).is_random());
EXPECT_FALSE(test_sys_.get_input_port(0).get_random_type());
EXPECT_FALSE(test_sys_.get_input_port(1).get_random_type());
EXPECT_EQ(test_sys_.get_input_port(2).get_random_type(),
RandomDistribution::kUniform);
EXPECT_EQ(test_sys_.get_input_port(3).get_random_type(),
RandomDistribution::kGaussian);
}
// Tests that FixInputPortsFrom allocates ports of the same dimension as the
// source context, with the values computed by the source system, and that
// double values in vector-valued ports are explicitly converted to AutoDiffXd.
TEST_F(SystemIOTest, TransmogrifyAndFix) {
ValueIOTestSystem<AutoDiffXd> dest_system;
auto dest_context = dest_system.AllocateContext();
dest_system.FixInputPortsFrom(test_sys_, *context_, dest_context.get());
EXPECT_EQ(
dest_system.EvalAbstractInput(*dest_context, 0)->get_value<std::string>(),
"input");
const TestTypedVector<AutoDiffXd>* fixed_vec =
dest_system.EvalVectorInput<TestTypedVector>(*dest_context, 1);
EXPECT_NE(fixed_vec, nullptr);
EXPECT_EQ(2, fixed_vec->GetAtIndex(0).value());
EXPECT_EQ(0, fixed_vec->GetAtIndex(0).derivatives().size());
}
// Confirm that FixInputPortsFrom does *not* convert type-dependent abstract
// input ports.
// TODO(5454) Once transmogrification of scalar-dependent abstract values is
// implemented, this test and the corresponding @throws documentation on
// System::FixInputPortsFrom can simply be removed (as we no longer have to
// track this undesirable behavior) .
TEST_F(SystemIOTest, FixFromTypeDependentAbstractInput) {
// Adds an abstract input port with type BasicVector<T>.
const auto& typed_input = test_sys_.AddAbstractInputPort();
// Confirm that the type is indeed BasicVector<double>.
std::unique_ptr<AbstractValue> input_value =
test_sys_.AllocateInputAbstract(typed_input);
DRAKE_EXPECT_NO_THROW(input_value->get_value<BasicVector<double>>());
const auto context = test_sys_.CreateDefaultContext();
typed_input.FixValue(context.get(),
BasicVector<double>(Eigen::VectorXd::Zero(1)));
ValueIOTestSystem<AutoDiffXd> autodiff_system;
autodiff_system.AddAbstractInputPort();
auto autodiff_context = autodiff_system.CreateDefaultContext();
DRAKE_EXPECT_THROWS_MESSAGE(autodiff_system.FixInputPortsFrom(
test_sys_, *context, autodiff_context.get()),
".*System::FixInputPortTypeCheck.*");
}
// This class implements various computational methods so we can check that
// they get invoked properly. The particular results don't mean anything.
// As above, lots of painful bookkeeping here that is normally buried by
// LeafSystem.
class ComputationTestSystem final : public TestSystemBase<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ComputationTestSystem)
// Requesting three continuous states to match AllocateTimeDerivatives().
ComputationTestSystem()
: TestSystemBase<double>(/* num_numeric_params_groups= */ 0,
/* num_continuous_states= */ 3) {
DeclareInputPort("u0", kVectorValued, 1);
}
// Just u0.
std::unique_ptr<AbstractValue> DoAllocateInput(
const InputPort<double>& input_port) const final {
DRAKE_DEMAND(input_port.get_index() == 0);
return std::make_unique<Value<BasicVector<double>>>(1);
}
// One q, one v, one z.
std::unique_ptr<ContinuousState<double>> AllocateTimeDerivatives()
const final {
auto result = std::make_unique<ContinuousState<double>>(
std::make_unique<BasicVector<double>>(3), 1, 1, 1); // q, v, z
result->set_system_id(this->get_system_id());
return result;
}
// Verify that the number of calls is as expected.
void ExpectCount(int xcdot, int pe, int ke, int pc, int pnc) const {
EXPECT_EQ(xcdot, xcdot_count_);
EXPECT_EQ(pe, pe_count_);
EXPECT_EQ(ke, ke_count_);
EXPECT_EQ(pc, pc_count_);
EXPECT_EQ(pnc, pnc_count_);
}
private:
// Two discrete variable groups of lengths 2 and 4.
std::unique_ptr<DiscreteValues<double>> AllocateDiscreteVariables()
const final {
std::vector<std::unique_ptr<BasicVector<double>>> data;
data.emplace_back(std::make_unique<BasicVector<double>>(2));
data.emplace_back(std::make_unique<BasicVector<double>>(4));
auto result = std::make_unique<DiscreteValues<double>>(std::move(data));
result->set_system_id(this->get_system_id());
return result;
}
// Derivatives can depend on time. Here x = (-1, -2, -3) * t.
void DoCalcTimeDerivatives(const Context<double>& context,
ContinuousState<double>* derivatives) const final {
EXPECT_EQ(derivatives->size(), 3);
const double t = context.get_time();
(*derivatives)[0] = -1 * t;
(*derivatives)[1] = -2 * t;
(*derivatives)[2] = -3 * t;
++xcdot_count_;
}
double DoCalcPotentialEnergy(const Context<double>& context) const final {
unused(context);
++pe_count_;
return 1.;
}
double DoCalcKineticEnergy(const Context<double>& context) const final {
unused(context);
++ke_count_;
return 2.;
}
double DoCalcConservativePower(const Context<double>& context) const final {
unused(context);
++pc_count_;
return 3.;
}
// Non-conservative power can depend on time. Here it is 4*t.
double DoCalcNonConservativePower(
const Context<double>& context) const final {
++pnc_count_;
return 4. * context.get_time();
}
mutable int xcdot_count_{};
mutable int pe_count_{};
mutable int ke_count_{};
mutable int pc_count_{};
mutable int pnc_count_{};
};
// Provides values for some of the inputs and sets up for outputs.
class ComputationTest : public ::testing::Test {
protected:
void SetUp() final {
context_->EnableCaching();
}
ComputationTestSystem test_sys_;
std::unique_ptr<Context<double>> context_ =
test_sys_.CreateDefaultContext();
};
TEST_F(ComputationTest, Eval) {
context_->SetTime(1.);
// xcdot, pe, ke, pc, pnc
test_sys_.ExpectCount(0, 0, 0, 0, 0);
EXPECT_EQ(test_sys_.EvalTimeDerivatives(*context_)[0], -1.);
EXPECT_EQ(test_sys_.EvalTimeDerivatives(*context_)[1], -2.);
EXPECT_EQ(test_sys_.EvalTimeDerivatives(*context_)[2], -3.);
// Caching should have kept us to a single derivative evaluation.
test_sys_.ExpectCount(1, 0, 0, 0, 0);
EXPECT_EQ(test_sys_.EvalPotentialEnergy(*context_), 1.);
test_sys_.ExpectCount(1, 1, 0, 0, 0);
EXPECT_EQ(test_sys_.EvalKineticEnergy(*context_), 2.);
test_sys_.ExpectCount(1, 1, 1, 0, 0);
EXPECT_EQ(test_sys_.EvalConservativePower(*context_), 3.);
test_sys_.ExpectCount(1, 1, 1, 1, 0);
EXPECT_EQ(test_sys_.EvalNonConservativePower(*context_), 4.);
test_sys_.ExpectCount(1, 1, 1, 1, 1);
// These should not require re-evaluation.
EXPECT_EQ(test_sys_.EvalPotentialEnergy(*context_), 1.);
EXPECT_EQ(test_sys_.EvalKineticEnergy(*context_), 2.);
EXPECT_EQ(test_sys_.EvalConservativePower(*context_), 3.);
EXPECT_EQ(test_sys_.EvalNonConservativePower(*context_), 4.);
test_sys_.ExpectCount(1, 1, 1, 1, 1);
// Each of the Calc methods should cause computation.
auto derivatives = test_sys_.AllocateTimeDerivatives();
test_sys_.CalcTimeDerivatives(*context_, derivatives.get());
test_sys_.ExpectCount(2, 1, 1, 1, 1);
EXPECT_EQ((*derivatives)[1], -2.);
EXPECT_EQ(test_sys_.CalcPotentialEnergy(*context_), 1.);
test_sys_.ExpectCount(2, 2, 1, 1, 1);
EXPECT_EQ(test_sys_.CalcKineticEnergy(*context_), 2.);
test_sys_.ExpectCount(2, 2, 2, 1, 1);
EXPECT_EQ(test_sys_.CalcConservativePower(*context_), 3.);
test_sys_.ExpectCount(2, 2, 2, 2, 1);
EXPECT_EQ(test_sys_.CalcNonConservativePower(*context_), 4.);
test_sys_.ExpectCount(2, 2, 2, 2, 2);
// TODO(sherm1) Pending resolution of issue #9171 we can be more precise
// about dependencies here. For now we'll just verify that changing
// some significant variables causes recomputation, not that *only*
// significant variables cause recomputation.
context_->SetTime(2.);
EXPECT_EQ(test_sys_.EvalTimeDerivatives(*context_)[0], -2.);
EXPECT_EQ(test_sys_.EvalTimeDerivatives(*context_)[1], -4.);
EXPECT_EQ(test_sys_.EvalTimeDerivatives(*context_)[2], -6.);
test_sys_.ExpectCount(3, 2, 2, 2, 2); // Above is just one evaluation.
EXPECT_EQ(test_sys_.EvalPotentialEnergy(*context_), 1.);
EXPECT_EQ(test_sys_.EvalKineticEnergy(*context_), 2.);
EXPECT_EQ(test_sys_.EvalConservativePower(*context_), 3.);
EXPECT_EQ(test_sys_.EvalNonConservativePower(*context_), 8.);
test_sys_.ExpectCount(3, 2, 2, 2, 3); // Only pnc depends on time.
// Modify an input. Derivatives are recomputed, but PE, KE, PC are not.
const Eigen::VectorXd u0 = Eigen::VectorXd::Constant(1, 0.0);
test_sys_.get_input_port(0).FixValue(context_.get(), u0);
EXPECT_EQ(test_sys_.EvalTimeDerivatives(*context_)[0], -2.);
test_sys_.ExpectCount(4, 2, 2, 2, 3);
EXPECT_EQ(test_sys_.EvalPotentialEnergy(*context_), 1.);
EXPECT_EQ(test_sys_.EvalKineticEnergy(*context_), 2.);
EXPECT_EQ(test_sys_.EvalConservativePower(*context_), 3.);
EXPECT_EQ(test_sys_.EvalNonConservativePower(*context_), 8.);
test_sys_.ExpectCount(4, 2, 2, 2, 4); // Only pnc depends on input.
// This should mark all state variables as changed and force recomputation.
context_->get_mutable_state();
EXPECT_EQ(test_sys_.EvalTimeDerivatives(*context_)[2], -6.); // Again.
test_sys_.ExpectCount(5, 2, 2, 2, 4);
EXPECT_EQ(test_sys_.EvalPotentialEnergy(*context_), 1.);
test_sys_.ExpectCount(5, 3, 2, 2, 4);
EXPECT_EQ(test_sys_.EvalKineticEnergy(*context_), 2.);
test_sys_.ExpectCount(5, 3, 3, 2, 4);
EXPECT_EQ(test_sys_.EvalConservativePower(*context_), 3.);
test_sys_.ExpectCount(5, 3, 3, 3, 4);
EXPECT_EQ(test_sys_.EvalNonConservativePower(*context_), 8.); // Again.
test_sys_.ExpectCount(5, 3, 3, 3, 5);
// Check that the reported time derivatives cache entry is the right one.
context_->SetTime(3.); // Invalidate.
const CacheEntry& entry = test_sys_.get_time_derivatives_cache_entry();
const int64_t serial_number =
entry.get_cache_entry_value(*context_).serial_number();
test_sys_.EvalTimeDerivatives(*context_);
EXPECT_NE(entry.get_cache_entry_value(*context_).serial_number(),
serial_number);
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/value_producer_test.cc | #include "drake/systems/framework/value_producer.h"
#include <stdexcept>
#include <string>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/systems/framework/abstract_value_cloner.h"
#include "drake/systems/framework/leaf_context.h"
namespace drake {
namespace systems {
namespace {
using AllocateCallback = ValueProducer::AllocateCallback;
using CalcCallback = ValueProducer::CalcCallback;
// The permitted argument types to specify Calc are:
// - (1) `calc` is a member function pointer with an output argument.
// - (2) `calc` is a member function pointer with a return value.
// - (3) `calc` is a std::function with an output argument.
// - (4) `calc` is a std::function with a return value.
// - (5) `calc` is a generic CalcCallback.
// The permitted argument types to specify Allocate are:
// - (a) `allocate` is via the default constructor.
// - (b) `allocate` is via user-supplied model_value.
// - (c) `allocate` is a member function pointer.
// - (d) `allocate` is a generic AllocateCallback.
// In the below, we'll declare functions and/or literal values that cover all
// of these options, so that we can easily mix and match them in test cases.
// All combinations are tested below except for (5a) which doesn't make sense.
// For readability, we'll spell out (1) as "one" and (a) as "alpha", etc.
class MyClass {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MyClass)
MyClass() = default;
// &MyClass::CalcOne is a valid argument for series (1).
void CalcOne(const Context<double>&, std::string* out) const {
*out = "one";
}
// &MyClass::CalcTwo is a valid argument for series (2).
std::string CalcTwo(const Context<double>&) const {
return "two";
}
// &MyClass::AllocateCharlie is a valid argument for series (c).
std::unique_ptr<std::string> AllocateCharlie() const {
return std::make_unique<std::string>("charlie");
}
};
// std::function(&CalcThree) is a valid argument for series (3).
//
// Note that `&CalcThree` on its own would fail template argument deduction,
// so for function pointers we must help the compiler by spelling out the
// std::function conversion. In the typical case a user will write a lambda
// lambda instead of a function pointer, so it's not a big deal in practice.
void CalcThree(const Context<double>&, std::string* out) {
*out = "three";
}
// std::function(&CalcFour) is a valid argument for series (4).
//
// Note that `&CalcFour` on its own would fail template argument deduction,
// so for function pointers we must help the compiler by spelling out the
// std::function conversion. In the typical case a user will write a lambda
// instead of a function pointer, so it's not a big deal in practice.
std::string CalcFour(const Context<double>&) {
return "four";
}
// &CalcFive is a valid argument for series (5).
void CalcFive(const ContextBase&, AbstractValue* out) {
out->set_value<std::string>("five");
}
// &AllocateDelta is a valid argument for series (d).
std::unique_ptr<AbstractValue> AllocateDelta() {
return AbstractValue::Make<std::string>("delta");
}
// kBadCalcOne is an null argument for series (1).
void (MyClass::* const kBadCalcOne)(const Context<double>&, std::string*) const
= nullptr;
// kBadCalcTwo is an null argument for series (2).
std::string (MyClass::* const kBadCalcTwo)(const Context<double>&) const
= nullptr;
// std::function(kBadCalcThree) is an null argument for series (3).
void (* const kBadCalcThree)(const Context<double>&, std::string*)
= nullptr;
// std::function(kBadCalcFour) is an null argument for series (4).
std::string (* const kBadCalcFour)(const Context<double>&)
= nullptr;
// kBadCalcFive is an null argument for series (5).
void (* const kBadCalcFive)(const ContextBase&, AbstractValue*)
= nullptr;
// kBadAllocateCharlie is an null argument for series (c).
std::unique_ptr<std::string> (MyClass::* const kBadAllocateCharlie)() const
= nullptr;
// kBadAllocateDelta is an null argument for series (d).
std::unique_ptr<AbstractValue> (* const kBadAllocateDelta)()
= nullptr;
// kBadInstance provides a typed null when a SomeInstance is needed.
const MyClass* const kBadInstance = nullptr;
class ValueProducerTest : public ::testing::Test {
protected:
// Given a device under test, check that its Allocate and Calc produce the
// given strings.
void CheckValues(
const ValueProducer& dut,
std::string_view expected_allocate_value,
std::string_view expected_calc_value) {
EXPECT_TRUE(dut.is_valid());
std::unique_ptr<AbstractValue> output = dut.Allocate();
ASSERT_NE(output, nullptr);
EXPECT_EQ(output->get_value<std::string>(), expected_allocate_value);
dut.Calc(context_, output.get());
EXPECT_EQ(output->get_value<std::string>(), expected_calc_value);
}
// kBravo is a valid argument for series (b).
const std::string kBravo{"bravo"};
// Dummy values for convenience.
const MyClass my_class_{};
const LeafContext<double> context_{};
};
// Test the default constructor, as well as that operations on a default-
// constructed object produce suitable results (including operations on
// copies of a default-constructed object).
TEST_F(ValueProducerTest, DefaultCtor) {
auto storage = AbstractValue::Make<int>(0);
const ValueProducer empty;
EXPECT_FALSE(empty.is_valid());
DRAKE_EXPECT_THROWS_MESSAGE(
empty.Allocate(),
".* null Allocate.*");
DRAKE_EXPECT_THROWS_MESSAGE(
empty.Calc(context_, storage.get()),
".* null Calc.*");
const ValueProducer empty_copy(empty);
EXPECT_FALSE(empty_copy.is_valid());
DRAKE_EXPECT_THROWS_MESSAGE(
empty_copy.Allocate(),
".* null Allocate.*");
DRAKE_EXPECT_THROWS_MESSAGE(
empty_copy.Calc(context_, storage.get()),
".* null Calc.*");
}
// Check that the given constructor arguments throw a null pointer exception.
#define DRAKE_CHECK_CTOR_NULL(constructor_args) \
DRAKE_EXPECT_THROWS_MESSAGE(ValueProducer constructor_args, \
".* null .*");
TEST_F(ValueProducerTest, AlphaOne) {
const ValueProducer dut(&my_class_, &MyClass::CalcOne);
CheckValues(dut, "", "one");
DRAKE_CHECK_CTOR_NULL((kBadInstance, &MyClass::CalcOne));
DRAKE_CHECK_CTOR_NULL((&my_class_, kBadCalcOne));
}
TEST_F(ValueProducerTest, AlphaTwo) {
const ValueProducer dut(&my_class_, &MyClass::CalcTwo);
CheckValues(dut, "", "two");
DRAKE_CHECK_CTOR_NULL((kBadInstance, &MyClass::CalcTwo));
DRAKE_CHECK_CTOR_NULL((&my_class_, kBadCalcTwo));
}
TEST_F(ValueProducerTest, AlphaThree) {
// N.B. We use {} not () to avoid the "most vexing parse".
const ValueProducer dut{std::function(CalcThree)};
CheckValues(dut, "", "three");
DRAKE_CHECK_CTOR_NULL((std::function(kBadCalcThree)));
}
TEST_F(ValueProducerTest, AlphaFour) {
// N.B. We use {} not () to avoid the "most vexing parse".
const ValueProducer dut{std::function(CalcFour)};
CheckValues(dut, "", "four");
DRAKE_CHECK_CTOR_NULL((std::function(kBadCalcFour)));
}
// N.B. Per ValueProducer API docs, there is no AlphaFive (aka (5a)).
TEST_F(ValueProducerTest, BravoTwo) {
const ValueProducer dut(&my_class_, kBravo, &MyClass::CalcTwo);
CheckValues(dut, "bravo", "two");
DRAKE_CHECK_CTOR_NULL((kBadInstance, kBravo, &MyClass::CalcTwo));
DRAKE_CHECK_CTOR_NULL((&my_class_, kBravo, kBadCalcTwo));
}
TEST_F(ValueProducerTest, BravoThree) {
const ValueProducer dut(kBravo, std::function(CalcThree));
CheckValues(dut, "bravo", "three");
DRAKE_CHECK_CTOR_NULL((kBravo, std::function(kBadCalcThree)));
}
TEST_F(ValueProducerTest, BravoFour) {
const ValueProducer dut(kBravo, std::function(CalcFour));
CheckValues(dut, "bravo", "four");
DRAKE_CHECK_CTOR_NULL((kBravo, std::function(kBadCalcFour)));
}
TEST_F(ValueProducerTest, BravoFive) {
const ValueProducer dut(kBravo, &CalcFive);
CheckValues(dut, "bravo", "five");
DRAKE_CHECK_CTOR_NULL((kBravo, kBadCalcFive));
}
TEST_F(ValueProducerTest, CharlieOne) {
const ValueProducer dut(
&my_class_, &MyClass::AllocateCharlie, &MyClass::CalcOne);
CheckValues(dut, "charlie", "one");
DRAKE_CHECK_CTOR_NULL((
kBadInstance, &MyClass::AllocateCharlie, &MyClass::CalcOne));
DRAKE_CHECK_CTOR_NULL((
&my_class_, kBadAllocateCharlie, &MyClass::CalcOne));
DRAKE_CHECK_CTOR_NULL((
&my_class_, &MyClass::AllocateCharlie, kBadCalcOne));
}
TEST_F(ValueProducerTest, CharlieTwo) {
const ValueProducer dut(
&my_class_, &MyClass::AllocateCharlie, &MyClass::CalcTwo);
CheckValues(dut, "charlie", "two");
DRAKE_CHECK_CTOR_NULL((
kBadInstance, &MyClass::AllocateCharlie, &MyClass::CalcTwo));
DRAKE_CHECK_CTOR_NULL((
&my_class_, kBadAllocateCharlie, &MyClass::CalcTwo));
DRAKE_CHECK_CTOR_NULL((
&my_class_, &MyClass::AllocateCharlie, kBadCalcTwo));
}
TEST_F(ValueProducerTest, CharlieThree) {
const ValueProducer dut(
&my_class_, &MyClass::AllocateCharlie, std::function(CalcThree));
CheckValues(dut, "charlie", "three");
DRAKE_CHECK_CTOR_NULL((
kBadInstance, &MyClass::AllocateCharlie, std::function(CalcThree)));
DRAKE_CHECK_CTOR_NULL((
&my_class_, kBadAllocateCharlie, std::function(CalcThree)));
DRAKE_CHECK_CTOR_NULL((
&my_class_, &MyClass::AllocateCharlie, std::function(kBadCalcThree)));
}
TEST_F(ValueProducerTest, CharlieFour) {
const ValueProducer dut(
&my_class_, &MyClass::AllocateCharlie, std::function(CalcFour));
CheckValues(dut, "charlie", "four");
DRAKE_CHECK_CTOR_NULL((
kBadInstance, &MyClass::AllocateCharlie, std::function(CalcFour)));
DRAKE_CHECK_CTOR_NULL((
&my_class_, kBadAllocateCharlie, std::function(CalcFour)));
DRAKE_CHECK_CTOR_NULL((
&my_class_, &MyClass::AllocateCharlie, std::function(kBadCalcFour)));
}
TEST_F(ValueProducerTest, CharlieFive) {
const ValueProducer dut(&my_class_, &MyClass::AllocateCharlie, &CalcFive);
CheckValues(dut, "charlie", "five");
DRAKE_CHECK_CTOR_NULL((kBadInstance, &MyClass::AllocateCharlie, &CalcFive));
DRAKE_CHECK_CTOR_NULL((&my_class_, kBadAllocateCharlie, &CalcFive));
DRAKE_CHECK_CTOR_NULL((&my_class_, &MyClass::AllocateCharlie, kBadCalcFive));
}
TEST_F(ValueProducerTest, DeltaOne) {
const ValueProducer dut(&my_class_, AllocateDelta, &MyClass::CalcOne);
CheckValues(dut, "delta", "one");
DRAKE_CHECK_CTOR_NULL((kBadInstance, AllocateDelta, &MyClass::CalcOne));
DRAKE_CHECK_CTOR_NULL((&my_class_, kBadAllocateDelta, &MyClass::CalcOne));
DRAKE_CHECK_CTOR_NULL((&my_class_, AllocateDelta, kBadCalcOne));
}
TEST_F(ValueProducerTest, DeltaTwo) {
const ValueProducer dut(&my_class_, AllocateDelta, &MyClass::CalcTwo);
CheckValues(dut, "delta", "two");
DRAKE_CHECK_CTOR_NULL((kBadInstance, AllocateDelta, &MyClass::CalcTwo));
DRAKE_CHECK_CTOR_NULL((&my_class_, kBadAllocateDelta, &MyClass::CalcTwo));
DRAKE_CHECK_CTOR_NULL((&my_class_, AllocateDelta, kBadCalcTwo));
}
TEST_F(ValueProducerTest, DeltaThree) {
const ValueProducer dut(AllocateDelta, std::function(CalcThree));
CheckValues(dut, "delta", "three");
DRAKE_CHECK_CTOR_NULL((kBadAllocateDelta, std::function(CalcThree)));
DRAKE_CHECK_CTOR_NULL((AllocateDelta, std::function(kBadCalcThree)));
}
TEST_F(ValueProducerTest, DeltaFour) {
const ValueProducer dut(AllocateDelta, std::function(CalcFour));
CheckValues(dut, "delta", "four");
DRAKE_CHECK_CTOR_NULL((kBadAllocateDelta, std::function(CalcFour)));
DRAKE_CHECK_CTOR_NULL((AllocateDelta, std::function(kBadCalcFour)));
}
TEST_F(ValueProducerTest, DeltaFive) {
const ValueProducer dut(AllocateDelta, &CalcFive);
CheckValues(dut, "delta", "five");
DRAKE_CHECK_CTOR_NULL((kBadAllocateDelta, &CalcFive));
DRAKE_CHECK_CTOR_NULL((AllocateDelta, kBadCalcFive));
}
#undef DRAKE_CHECK_CTOR_NULL
// The below example is repeated in the documentation; keep it in sync.
TEST_F(ValueProducerTest, DocumentationExample1) {
// This line is omitted from the documentation, for brevity.
using T = double;
// Documentation example begins here.
std::function calc = [](const Context<T>& context, std::string* output) {
*output = std::to_string(context.get_time());
};
ValueProducer producer(calc);
std::unique_ptr<AbstractValue> storage = producer.Allocate();
const LeafContext<T> context;
producer.Calc(context, storage.get());
EXPECT_THAT(storage->get_value<std::string>(), ::testing::StartsWith("0.0"));
}
// The below example is repeated in the documentation; keep it in sync.
TEST_F(ValueProducerTest, DocumentationExample2) {
// This line is omitted from the documentation, for brevity.
using T = double;
// Documentation example begins here. We use a different class name vs the
// documentation, to avoid shadowing warnings.
class MyClazz {
public: // This line is omitted from the documentation, for brevity.
void MyCalc(const Context<T>& context, std::string* output) const {
*output = std::to_string(context.get_time());
}
};
MyClazz my_class;
ValueProducer foo = ValueProducer(&my_class, &MyClazz::MyCalc);
}
// The below example is repeated in the documentation; keep it in sync.
TEST_F(ValueProducerTest, DocumentationExample3) {
// We use a different class name vs the documentation, to avoid shadowing
// warnings.
class MyClazz {
public: // This line is omitted from the documentation, for brevity.
double MyCalc(const Context<double>& context) const {
return context.get_time();
}
};
MyClazz my_class;
ValueProducer foo = ValueProducer(&my_class, &MyClazz::MyCalc);
}
// The below example is repeated in the documentation; keep it in sync.
TEST_F(ValueProducerTest, DocumentationExample4) {
// This line is omitted from the documentation, for brevity.
using T = double;
// Documentation example begins here. We use a different class name vs the
// documentation, to avoid shadowing warnings.
class MyClazz {
public: // This line is omitted from the documentation, for brevity.
void MyCalc(const Context<T>& context, BasicVector<T>* output) const {
output->get_mutable_value()[0] = context.get_time();
}
};
MyClazz my_class;
BasicVector<T> model_value(1);
ValueProducer foo = ValueProducer(
&my_class, model_value, &MyClazz::MyCalc);
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |
/home/johnshepherd/drake/systems/framework | /home/johnshepherd/drake/systems/framework/test/input_port_test.cc | #include "drake/systems/framework/input_port.h"
#include <gtest/gtest.h>
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/framework/leaf_system.h"
#include "drake/systems/framework/test_utilities/my_vector.h"
namespace drake {
namespace systems {
namespace {
class DummySystem final : public LeafSystem<double> {
public:
using SystemBase::get_system_id;
};
// The mocked-up return value for our DoEval stub, below.
const AbstractValue* g_do_eval_result = nullptr;
// Returns g_do_eval_result.
const AbstractValue* DoEval(const ContextBase&) {
return g_do_eval_result;
}
// We need to define this to compile, but it should never be invoked.
std::unique_ptr<AbstractValue> DoAlloc() {
return nullptr;
}
GTEST_TEST(InputPortTest, VectorTest) {
using T = double;
DummySystem dummy_system;
dummy_system.set_name("dummy");
const auto context_ptr = dummy_system.CreateDefaultContext();
const auto& context = *context_ptr;
const System<T>* const system = &dummy_system;
internal::SystemMessageInterface* const system_interface = &dummy_system;
const std::string name{"port_name"};
const InputPortIndex index{2};
const DependencyTicket ticket;
const PortDataType data_type = kVectorValued;
const int size = 3;
const std::optional<RandomDistribution> random_type = std::nullopt;
auto dut = internal::FrameworkFactory::Make<InputPort<T>>(
system, system_interface, dummy_system.get_system_id(), name, index,
ticket, data_type, size, random_type, &DoEval, &DoAlloc);
// Check basic getters.
EXPECT_EQ(dut->get_name(), name);
EXPECT_EQ(dut->get_data_type(), data_type);
EXPECT_EQ(dut->size(), size);
EXPECT_EQ(dut->GetFullDescription(),
"InputPort[2] (port_name) of System ::dummy (DummySystem)");
EXPECT_EQ(&dut->get_system(), system);
// Check HasValue.
g_do_eval_result = nullptr;
EXPECT_EQ(dut->HasValue(context), false);
const Vector3<T> data(1.0, 2.0, 3.0);
const Value<BasicVector<T>> new_value{MyVector3d(data)};
g_do_eval_result = &new_value;
EXPECT_EQ(dut->HasValue(context), true);
// Check Eval with various ValueType possibilities.
const auto& eval_eigen = dut->Eval(context);
const BasicVector<T>& eval_basic = dut->Eval<BasicVector<T>>(context);
const MyVector3d& eval_myvec3 = dut->Eval<MyVector3d>(context);
const AbstractValue& eval_abs = dut->Eval<AbstractValue>(context);
EXPECT_EQ(eval_eigen, data);
EXPECT_EQ(eval_basic.CopyToVector(), data);
EXPECT_EQ(eval_myvec3.CopyToVector(), data);
EXPECT_EQ(eval_abs.get_value<BasicVector<T>>().CopyToVector(), data);
// Check error messages.
DRAKE_EXPECT_THROWS_MESSAGE(
dut->Eval<std::string>(context),
"InputPort::Eval..: wrong value type std::string specified; "
"actual type was drake::systems::MyVector<double,3> "
"for InputPort.*2.*of.*dummy.*DummySystem.*");
DRAKE_EXPECT_THROWS_MESSAGE(
dut->Eval<MyVector2d>(context),
"InputPort::Eval..: wrong value type .*MyVector<double,2> specified; "
"actual type was .*MyVector<double,3> "
"for InputPort.*2.*of.*dummy.*DummySystem.*");
}
GTEST_TEST(InputPortTest, AbstractTest) {
using T = double;
DummySystem dummy_system;
dummy_system.set_name("dummy");
const auto context_ptr = dummy_system.CreateDefaultContext();
const auto& context = *context_ptr;
const System<T>* const system = &dummy_system;
internal::SystemMessageInterface* const system_interface = &dummy_system;
const std::string name{"port_name"};
const InputPortIndex index{2};
const DependencyTicket ticket;
const PortDataType data_type = kAbstractValued;
const int size = 0;
const std::optional<RandomDistribution> random_type = std::nullopt;
auto dut = internal::FrameworkFactory::Make<InputPort<T>>(
system, system_interface, dummy_system.get_system_id(), name, index,
ticket, data_type, size, random_type, &DoEval, &DoAlloc);
// Check basic getters.
EXPECT_EQ(dut->get_name(), name);
EXPECT_EQ(dut->get_data_type(), data_type);
EXPECT_EQ(dut->size(), size);
EXPECT_EQ(dut->GetFullDescription(),
"InputPort[2] (port_name) of System ::dummy (DummySystem)");
EXPECT_EQ(&dut->get_system(), system);
// Check HasValue.
g_do_eval_result = nullptr;
EXPECT_EQ(dut->HasValue(context), false);
const std::string data{"foo"};
const Value<std::string> new_value{data};
g_do_eval_result = &new_value;
EXPECT_EQ(dut->HasValue(context), true);
// Check Eval with various ValueType possibilities.
const std::string& eval_str = dut->Eval<std::string>(context);
const AbstractValue& eval_abs = dut->Eval<AbstractValue>(context);
EXPECT_EQ(eval_str, data);
EXPECT_EQ(eval_abs.get_value<std::string>(), data);
DRAKE_EXPECT_THROWS_MESSAGE(
dut->Eval(context),
"InputPort::Eval..: wrong value type .*BasicVector<double> specified; "
"actual type was std::string "
"for InputPort.*2.*of.*dummy.*DummySystem.*");
DRAKE_EXPECT_THROWS_MESSAGE(
dut->Eval<BasicVector<T>>(context),
"InputPort::Eval..: wrong value type .*BasicVector<double> specified; "
"actual type was std::string "
"for InputPort.*2.*of.*dummy.*DummySystem.*");
DRAKE_EXPECT_THROWS_MESSAGE(
dut->Eval<MyVector3d>(context),
"InputPort::Eval..: wrong value type .*BasicVector<double> specified; "
"actual type was std::string "
"for InputPort.*2.*of.*dummy.*DummySystem.*");
DRAKE_EXPECT_THROWS_MESSAGE(
dut->Eval<int>(context),
"InputPort::Eval..: wrong value type int specified; "
"actual type was std::string "
"for InputPort.*2.*of.*dummy.*DummySystem.*");
}
// This struct is for testing the FixValue() variants.
struct SystemWithInputPorts final : public LeafSystem<double> {
public:
SystemWithInputPorts()
: basic_vec_port{DeclareVectorInputPort("basic_vec_port", 3)},
derived_vec_port{DeclareVectorInputPort(
"derived_vec_port", MyVector3d(Eigen::Vector3d(1., 2., 3.)))},
int_port{DeclareAbstractInputPort("int_port", Value<int>(5))},
double_port{
DeclareAbstractInputPort("double_port", Value<double>(1.25))},
string_port{DeclareAbstractInputPort("string_port",
Value<std::string>("hello"))},
// To check that FixValue() properly invalidates dependents, make a
// cache entry that depends only on an input port.
cache_entry{this->DeclareCacheEntry(
"depends_on_int_port", &SystemWithInputPorts::CalcCacheEntry,
{this->input_port_ticket(int_port.get_index())})},
dependent_cache_entry{this->DeclareCacheEntry(
"depends_on_cache_entry",
&SystemWithInputPorts::CalcDependentCacheEntry,
{cache_entry.ticket()})} {}
void CalcCacheEntry(const Context<double>& context, int* value) const {
*value = int_port.Eval<int>(context);
}
void CalcDependentCacheEntry(const Context<double>& context,
int* value) const {
*value = cache_entry.Eval<int>(context);
}
InputPort<double>& basic_vec_port;
InputPort<double>& derived_vec_port;
InputPort<double>& int_port;
InputPort<double>& double_port;
InputPort<double>& string_port;
CacheEntry& cache_entry;
CacheEntry& dependent_cache_entry;
};
// Test the FixValue() method. Note that the conversion of its value argument
// to an AbstractValue is handled by internal::ValueToAbstractValue which has
// its own unit tests. Here we need just check the input-port specific
// behavior for vector and abstract input ports.
// Also for sanity, make sure the returned FixedInputPortValue object works,
// although its API is so awful no one should use it.
GTEST_TEST(InputPortTest, FixValueTests) {
SystemWithInputPorts dut;
std::unique_ptr<Context<double>> context = dut.CreateDefaultContext();
// None of the ports should have a value initially.
for (int i = 0; i < dut.num_input_ports(); ++i) {
EXPECT_FALSE(dut.get_input_port(i).HasValue(*context));
}
// First pound on the vector ports.
// An Eigen vector value should be stored as a BasicVector.
const Eigen::Vector3d expected_vec(10., 20., 30.);
dut.basic_vec_port.FixValue(&*context, expected_vec);
EXPECT_EQ(dut.basic_vec_port.Eval(*context), expected_vec);
EXPECT_EQ(
dut.basic_vec_port.Eval<BasicVector<double>>(*context).CopyToVector(),
expected_vec);
DRAKE_EXPECT_THROWS_MESSAGE(
dut.basic_vec_port.Eval<std::string>(*context),
".*wrong value type.*std::string.*actual type.*BasicVector.*");
// TODO(sherm1) It would be nice to make this work rather than throw.
DRAKE_EXPECT_THROWS_MESSAGE(
dut.basic_vec_port.Eval<Eigen::Vector3d>(*context),
".*wrong value type.*Eigen.*actual type.*BasicVector.*");
// Pass a more complicated Eigen object; should still work.
const Eigen::Vector4d long_vec(.25, .5, .75, 1.);
dut.basic_vec_port.FixValue(&*context, 2. * long_vec.tail(3));
EXPECT_EQ(dut.basic_vec_port.Eval(*context),
2. * Eigen::Vector3d(.5, .75, 1.));
// Should return a runtime error if the size is wrong.
DRAKE_EXPECT_THROWS_MESSAGE(
dut.basic_vec_port.FixValue(&*context, long_vec.segment<2>(1)),
".*expected.*size=3.*actual.*size=2.*");
// A BasicVector-derived type should be acceptable to vector ports with
// either a BasicVector model or the derived-type model (sizes must match).
const MyVector3d my_vector(expected_vec);
dut.basic_vec_port.FixValue(&*context, my_vector);
dut.derived_vec_port.FixValue(&*context, my_vector);
// Either way the concrete type should be preserved.
EXPECT_EQ(dut.basic_vec_port.Eval<MyVector3d>(*context).CopyToVector(),
expected_vec);
EXPECT_EQ(dut.derived_vec_port.Eval<MyVector3d>(*context).CopyToVector(),
expected_vec);
// A plain BasicVector should work in the BasicVector-modeled port but
// NOT in the MyVector3-modeled port.
const BasicVector<double> basic_vector3({7., 8., 9.});
dut.basic_vec_port.FixValue(&*context, basic_vector3); // (2)
// TODO(sherm1) This shouldn't work, but does. See issue #9669.
dut.derived_vec_port.FixValue(&*context, basic_vector3);
// This is the right type, wrong size for the vector ports.
const MyVector2d my_vector2(Eigen::Vector2d{19., 20.});
DRAKE_EXPECT_THROWS_MESSAGE(
dut.basic_vec_port.FixValue(&*context, my_vector2),
".*expected.*size=3.*actual.*size=2.*");
DRAKE_EXPECT_THROWS_MESSAGE(
dut.derived_vec_port.FixValue(&*context, my_vector2),
".*expected.*size=3.*actual.*size=2.*");
// Now try the abstract ports.
dut.int_port.FixValue(&*context, 17);
EXPECT_EQ(dut.int_port.Eval<int>(*context), 17);
DRAKE_EXPECT_THROWS_MESSAGE(
dut.int_port.FixValue(&*context, 1.25),
".*expected value of type int.*actual type was double.*");
dut.double_port.FixValue(&*context, 1.25);
EXPECT_EQ(dut.double_port.Eval<double>(*context), 1.25);
// Without an explicit template argument, FixValue() won't do numerical
// conversions.
DRAKE_EXPECT_THROWS_MESSAGE(
dut.double_port.FixValue(&*context, 4),
".*expected value of type double.*actual type was int.*");
// But an explicit template argument can serve as a workaround.
dut.double_port.FixValue<double>(&*context, 4);
EXPECT_EQ(dut.double_port.Eval<double>(*context), 4.0);
// Use the string port for a variety of tests:
// - the port value can be set as a string or char* constant
// - the generic AbstractValue API works
// - we can use the returned FixedInputPortValue object to change the value
// Check the basics.
dut.string_port.FixValue(&*context, std::string("dummy"));
EXPECT_EQ(dut.string_port.Eval<std::string>(*context), "dummy");
// Test special case API for C string constant, treated as an std::string.
dut.string_port.FixValue(&*context, "a c string");
EXPECT_EQ(dut.string_port.Eval<std::string>(*context), "a c string");
// Test that we can take an AbstractValue or Value<T> object as input.
const Value<int> int_value(42);
const AbstractValue& int_value_as_abstract = Value<int>(43);
dut.int_port.FixValue(&*context, int_value);
EXPECT_EQ(dut.int_port.Eval<int>(*context), 42);
dut.int_port.FixValue(&*context, int_value_as_abstract);
EXPECT_EQ(dut.int_port.Eval<int>(*context), 43);
// We should only accept the right kind of abstract value.
DRAKE_EXPECT_THROWS_MESSAGE(
dut.string_port.FixValue(&*context, int_value),
".*expected.*type std::string.*actual type was int.*");
auto& fixed_value =
dut.string_port.FixValue(&*context, Value<std::string>("abstract"));
EXPECT_EQ(dut.string_port.Eval<std::string>(*context), "abstract");
// FixedInputPortValue has a very clunky interface, but let's make sure we
// at least got the right object.
fixed_value.GetMutableData()->get_mutable_value<std::string>() =
"replacement string";
EXPECT_EQ(dut.string_port.Eval<std::string>(*context), "replacement string");
// All of the ports should have values by now.
for (int i = 0; i < dut.num_input_ports(); ++i) {
EXPECT_TRUE(dut.get_input_port(i).HasValue(*context));
}
}
GTEST_TEST(InputPortTest, FixValueCacheInvalidationTests) {
SystemWithInputPorts dut;
std::unique_ptr<Context<double>> context = dut.CreateDefaultContext();
EXPECT_FALSE(dut.int_port.HasValue(*context));
EXPECT_TRUE(dut.cache_entry.is_out_of_date(*context));
EXPECT_TRUE(dut.dependent_cache_entry.is_out_of_date(*context));
// Can't evaluate the cache entry if input has no value.
EXPECT_THROW(dut.cache_entry.Eval<int>(*context), std::exception);
dut.int_port.FixValue(&*context, 19);
EXPECT_TRUE(dut.int_port.HasValue(*context));
// Note: we're getting a _reference_ to the cache value so we'll see changes.
const int& cached_value = dut.cache_entry.Eval<int>(*context);
EXPECT_FALSE(dut.cache_entry.is_out_of_date(*context));
EXPECT_EQ(cached_value, 19);
EXPECT_TRUE(dut.dependent_cache_entry.is_out_of_date(*context));
const int& dependent_cached_value =
dut.dependent_cache_entry.Eval<int>(*context);
EXPECT_EQ(dependent_cached_value, 19);
dut.int_port.FixValue(&*context, -3); // Should invalidate dependents.
EXPECT_TRUE(dut.cache_entry.is_out_of_date(*context));
EXPECT_TRUE(dut.dependent_cache_entry.is_out_of_date(*context));
EXPECT_EQ(cached_value, 19); // Out-of-date values are still there.
EXPECT_EQ(dependent_cached_value, 19);
dut.dependent_cache_entry.Eval<int>(*context); // Updates cache_entry also.
EXPECT_EQ(dependent_cached_value, -3);
EXPECT_FALSE(dut.cache_entry.is_out_of_date(*context));
EXPECT_EQ(cached_value, -3);
// Once more to make sure this wasn't a fluke.
dut.int_port.FixValue(&*context, 123);
EXPECT_TRUE(dut.cache_entry.is_out_of_date(*context));
EXPECT_TRUE(dut.dependent_cache_entry.is_out_of_date(*context));
}
// For a subsystem embedded in a diagram, test that we can query, fix, and
// evaluate that subsystem's input ports using only a Context for that
// subsystem (rather than the whole Diagram context).
GTEST_TEST(InputPortTest, ContextForEmbeddedSystem) {
DiagramBuilder<double> builder;
auto* system = builder.AddSystem<SystemWithInputPorts>();
auto diagram = builder.Build();
// Create a context just for the System.
auto context = system->CreateDefaultContext();
// Verify that we can tell that ports have no values using this Context.
EXPECT_FALSE(system->basic_vec_port.HasValue(*context));
EXPECT_FALSE(system->int_port.HasValue(*context));
EXPECT_FALSE(system->double_port.HasValue(*context));
EXPECT_FALSE(system->string_port.HasValue(*context));
// Set the values.
const int kIntValue = 42;
const double kDoubleValue = 13.25;
const std::string kStringValue("abstract");
const Eigen::Vector3d kVectorValue(10., 20., 30.);
// Now fix the values.
system->basic_vec_port.FixValue(context.get(), kVectorValue);
system->int_port.FixValue(context.get(), kIntValue);
system->double_port.FixValue(context.get(), kDoubleValue);
system->string_port.FixValue(context.get(), kStringValue);
// Now verify the values.
EXPECT_EQ(kVectorValue, system->basic_vec_port.Eval(*context));
EXPECT_EQ(kIntValue, system->int_port.Eval<int>(*context));
EXPECT_EQ(kDoubleValue, system->double_port.Eval<double>(*context));
EXPECT_EQ(kStringValue, system->string_port.Eval<std::string>(*context));
// When given an inapproprate context, we fail-fast.
auto diagram_context = diagram->CreateDefaultContext();
DRAKE_EXPECT_THROWS_MESSAGE(
system->int_port.HasValue(*diagram_context),
".*Context.*was not created for this InputPort.*");
DRAKE_EXPECT_THROWS_MESSAGE(
system->int_port.Eval<int>(*diagram_context),
".*Context.*was not created for this InputPort.*");
}
GTEST_TEST(InputPortTest, Allocate) {
SystemWithInputPorts system;
// Vector-valued input-port.
const auto vec_abstract_value = system.basic_vec_port.Allocate();
const auto& basic_vector =
vec_abstract_value->get_value<BasicVector<double>>();
EXPECT_EQ(basic_vector.size(), 3);
// Abstract-valued input-port.
const auto int_abstract_value = system.int_port.Allocate();
const int int_value = int_abstract_value->get_value<int>();
EXPECT_EQ(int_value, 5);
}
} // namespace
} // namespace systems
} // namespace drake
| 0 |