-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
system_base.cc
307 lines (259 loc) · 12.2 KB
/
system_base.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#include "drake/systems/framework/system_base.h"
#include <atomic>
#include <fmt/format.h>
#include "drake/common/unused.h"
#include "drake/systems/framework/fixed_input_port_value.h"
namespace {
// Output a string like "System::EvalInput()".
std::string FmtFunc(const char* func) {
return fmt::format("System::{}()", func);
}
}
namespace drake {
namespace systems {
SystemBase::~SystemBase() {}
internal::SystemId SystemBase::get_next_id() {
return internal::SystemId::get_new_id();
}
std::string SystemBase::GetSystemPathname() const {
const std::string parent_path =
get_parent_service() ? get_parent_service()->GetParentPathname()
: std::string();
return parent_path + internal::SystemMessageInterface::path_separator() +
GetSystemName();
}
CacheEntry& SystemBase::DeclareCacheEntry(
std::string description, ValueProducer value_producer,
std::set<DependencyTicket> prerequisites_of_calc) {
return DeclareCacheEntryWithKnownTicket(
assign_next_dependency_ticket(), std::move(description),
std::move(value_producer), std::move(prerequisites_of_calc));
}
CacheEntry& SystemBase::DeclareCacheEntryWithKnownTicket(
DependencyTicket known_ticket, std::string description,
ValueProducer value_producer,
std::set<DependencyTicket> prerequisites_of_calc) {
// If the prerequisite list is empty the CacheEntry constructor will throw
// a logic error.
const CacheIndex index(num_cache_entries());
cache_entries_.emplace_back(std::make_unique<CacheEntry>(
this, index, known_ticket, std::move(description),
std::move(value_producer), std::move(prerequisites_of_calc)));
CacheEntry& new_entry = *cache_entries_.back();
return new_entry;
}
void SystemBase::InitializeContextBase(ContextBase* context_ptr) const {
DRAKE_DEMAND(context_ptr != nullptr);
ContextBase& context = *context_ptr;
// Initialization should happen only once per Context.
DRAKE_DEMAND(
!internal::SystemBaseContextBaseAttorney::is_context_base_initialized(
context));
internal::SystemBaseContextBaseAttorney::set_system_name(
&context, get_name());
internal::SystemBaseContextBaseAttorney::set_system_id(
&context, system_id_);
// Add the independent-source trackers and wire them up appropriately. That
// includes input ports since their dependencies are external.
CreateSourceTrackers(&context);
DependencyGraph& graph = context.get_mutable_dependency_graph();
// Create the Context cache containing a CacheEntryValue corresponding to
// each CacheEntry, add a DependencyTracker and subscribe it to its
// prerequisites as specified in the CacheEntry. Cache entries are
// necessarily ordered such that the first cache entry can depend only
// on the known source trackers created above, the second may depend on
// those plus the first, and so on. Circular dependencies are not permitted.
Cache& cache = context.get_mutable_cache();
for (CacheIndex index(0); index < num_cache_entries(); ++index) {
const CacheEntry& entry = get_cache_entry(index);
CacheEntryValue& cache_value = cache.CreateNewCacheEntryValue(
entry.cache_index(), entry.ticket(), entry.description(),
entry.prerequisites(), &graph);
// TODO(sherm1) Supply initial value on creation instead and get rid of
// this separate call.
cache_value.SetInitialValue(entry.Allocate());
if (entry.is_disabled_by_default())
cache_value.disable_caching();
}
// Create the output port trackers yᵢ here. Nothing in this System may
// depend on them; subscribers will be input ports from peer subsystems or
// an exported output port in the parent Diagram. The associated cache entries
// were just created above. Any intra-system prerequisites are set up now.
for (const auto& oport : output_ports_) {
internal::SystemBaseContextBaseAttorney::AddOutputPort(
&context, oport->get_index(), oport->ticket(),
oport->GetPrerequisite());
}
internal::SystemBaseContextBaseAttorney::mark_context_base_initialized(
&context);
}
// Set up trackers for variable-numbered independent sources: discrete and
// abstract state, numerical and abstract parameters, and input ports.
// The generic trackers like "all parameters" are already present in the
// supplied Context, but we have to subscribe them to the individual
// elements now.
void SystemBase::CreateSourceTrackers(ContextBase* context_ptr) const {
ContextBase& context = *context_ptr;
// Define a lambda to do the repeated work below: create trackers for
// individual entities and subscribe the group tracker to each of them.
auto make_trackers = [&context](
DependencyTicket subscriber_ticket,
const std::vector<TrackerInfo>& system_ticket_info,
void (*add_ticket_to_context)(ContextBase*, DependencyTicket)) {
DependencyGraph& graph = context.get_mutable_dependency_graph();
DependencyTracker& subscriber =
graph.get_mutable_tracker(subscriber_ticket);
for (const auto& info : system_ticket_info) {
auto& source_tracker =
graph.CreateNewDependencyTracker(info.ticket, info.description);
add_ticket_to_context(&context, info.ticket);
subscriber.SubscribeToPrerequisite(&source_tracker);
}
};
// Allocate trackers for each discrete variable group xdᵢ, and subscribe
// the "all discrete variables" tracker xd to those.
make_trackers(
xd_ticket(), discrete_state_tickets_,
&internal::SystemBaseContextBaseAttorney::AddDiscreteStateTicket);
// Allocate trackers for each abstract state variable xaᵢ, and subscribe
// the "all abstract variables" tracker xa to those.
make_trackers(
xa_ticket(), abstract_state_tickets_,
&internal::SystemBaseContextBaseAttorney::AddAbstractStateTicket);
// Allocate trackers for each numeric parameter pnᵢ and each abstract
// parameter paᵢ, and subscribe the pn and pa trackers to them.
make_trackers(
pn_ticket(), numeric_parameter_tickets_,
&internal::SystemBaseContextBaseAttorney::AddNumericParameterTicket);
make_trackers(
pa_ticket(), abstract_parameter_tickets_,
&internal::SystemBaseContextBaseAttorney::AddAbstractParameterTicket);
// Allocate trackers for each input port uᵢ, and subscribe the "all input
// ports" tracker u to them. Doesn't use TrackerInfo so can't use the lambda.
for (const auto& iport : input_ports_) {
internal::SystemBaseContextBaseAttorney::AddInputPort(
&context, iport->get_index(), iport->ticket(),
MakeFixInputPortTypeChecker(iport->get_index()));
}
}
// The only way for a system to evaluate its own input port is if that
// port is fixed. In that case the port's value is in the corresponding
// subcontext and we can just return it. Otherwise, the port obtains its value
// from some other system and we need our parent's help to get access to
// that system.
const AbstractValue* SystemBase::EvalAbstractInputImpl(
const char* func, const ContextBase& context,
InputPortIndex port_index) const {
if (port_index >= num_input_ports())
ThrowInputPortIndexOutOfRange(func, port_index);
const FixedInputPortValue* const free_port_value =
context.MaybeGetFixedInputPortValue(port_index);
if (free_port_value != nullptr)
return &free_port_value->get_value(); // A fixed input port.
// The only way to satisfy an input port of a root System is to make it fixed.
// Since it wasn't fixed, it is unconnected.
if (get_parent_service() == nullptr) return nullptr;
// If this is a root Context, our parent can't evaluate it.
if (context.is_root_context()) return nullptr;
// This is not the root System, and the port isn't fixed, so ask our parent to
// evaluate it.
return get_parent_service()->EvalConnectedSubsystemInputPort(
*internal::SystemBaseContextBaseAttorney::get_parent_base(context),
get_input_port_base(port_index));
}
void SystemBase::ThrowNegativePortIndex(const char* func,
int port_index) const {
DRAKE_DEMAND(port_index < 0);
throw std::out_of_range(
fmt::format("{}: negative port index {} is illegal. (System {})",
FmtFunc(func), port_index, GetSystemPathname()));
}
void SystemBase::ThrowInputPortIndexOutOfRange(const char* func,
InputPortIndex port) const {
throw std::out_of_range(fmt::format(
"{}: there is no input port with index {} because there "
"are only {} input ports in system {}.",
FmtFunc(func), port, num_input_ports(), GetSystemPathname()));
}
void SystemBase::ThrowOutputPortIndexOutOfRange(const char* func,
OutputPortIndex port) const {
throw std::out_of_range(fmt::format(
"{}: there is no output port with index {} because there "
"are only {} output ports in system {}.",
FmtFunc(func), port,
num_output_ports(), GetSystemPathname()));
}
void SystemBase::ThrowNotAVectorInputPort(const char* func,
InputPortIndex port) const {
throw std::logic_error(fmt::format(
"{}: vector port required, but input port '{}' (index {}) was declared "
"abstract. Even if the actual value is a vector, use "
"EvalInputValue<V> instead for an abstract port containing a vector "
"of type V. (System {})",
FmtFunc(func), get_input_port_base(port).get_name(), port,
GetSystemPathname()));
}
void SystemBase::ThrowInputPortHasWrongType(
const char* func, InputPortIndex port, const std::string& expected_type,
const std::string& actual_type) const {
ThrowInputPortHasWrongType(
func, GetSystemPathname(), port, get_input_port_base(port).get_name(),
expected_type, actual_type);
}
void SystemBase::ThrowInputPortHasWrongType(
const char* func, const std::string& system_pathname, InputPortIndex port,
const std::string& port_name, const std::string& expected_type,
const std::string& actual_type) {
throw std::logic_error(fmt::format(
"{}: expected value of type {} for input port '{}' (index {}) "
"but the actual type was {}. (System {})",
FmtFunc(func), expected_type, port_name, port, actual_type,
system_pathname));
}
void SystemBase::ThrowCantEvaluateInputPort(const char* func,
InputPortIndex port) const {
throw std::logic_error(
fmt::format("{}: input port '{}' (index {}) is neither connected nor "
"fixed so cannot be evaluated. (System {})",
FmtFunc(func), get_input_port_base(port).get_name(), port,
GetSystemPathname()));
}
void SystemBase::ThrowValidateContextMismatch(
const ContextBase& context) const {
throw std::logic_error(fmt::format(
"Context was not created for {} system {}; it was created for system {}",
this->GetSystemType(), this->GetSystemPathname(),
context.GetSystemPathname()));
}
void SystemBase::ThrowNotCreatedForThisSystemImpl(
const std::string& nice_type_name, internal::SystemId id) const {
if (!id.is_valid()) {
throw std::logic_error(fmt::format(
"{} was not associated with any System but should have been "
"created for {} System {}",
nice_type_name, GetSystemType(), GetSystemPathname()));
} else {
throw std::logic_error(fmt::format("{} was not created for {} System {}",
nice_type_name, GetSystemType(),
GetSystemPathname()));
}
}
std::string SystemBase::GetUnsupportedScalarConversionMessage(
const std::type_info& source_type,
const std::type_info& destination_type) const {
unused(source_type);
return fmt::format(
"System {} of type {} does not support scalar conversion to type {}",
GetSystemPathname(), GetSystemType(),
NiceTypeName::Get(destination_type));
}
namespace internal {
std::string DiagramSystemBaseAttorney::GetUnsupportedScalarConversionMessage(
const SystemBase& system, const std::type_info& source_type,
const std::type_info& destination_type) {
return system.GetUnsupportedScalarConversionMessage(
source_type, destination_type);
}
} // namespace internal
} // namespace systems
} // namespace drake