-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
system_base.cc
639 lines (561 loc) · 24.7 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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
#include "drake/systems/framework/system_base.h"
#include <algorithm>
#include <atomic>
#include <limits>
#include <mutex>
#include <regex>
#include <stdexcept>
#include <unordered_set>
#include <fmt/format.h>
#include "drake/common/hash.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::GetMemoryObjectName() const {
// Remove the template parameter(s).
const std::string type_name_without_templates = std::regex_replace(
NiceTypeName::Get(*this), std::regex("<.*>$"), std::string());
// Replace "::" with "/" because ":" is System::GetSystemPathname's separator.
// TODO(sherm1) Change the separator to "/" and avoid this!
const std::string default_name = std::regex_replace(
type_name_without_templates, std::regex(":+"), std::string("/"));
// Append the address spelled like "@0123456789abcdef".
const uintptr_t address = reinterpret_cast<uintptr_t>(this);
return fmt::format("{}@{:0>16x}", default_name, address);
}
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();
}
namespace {
/* Returns a copy of the given text, with HTML's special characters replaced
with their safe equivalents. */
std::string HtmlEscape(std::string_view text) {
std::string result;
for (char ch : text) {
// N.B. This works fine even with utf-8 text.
if (ch == '<') {
result += "<";
continue;
}
if (ch == '>') {
result += ">";
continue;
}
if (ch == '&') {
result += "&";
continue;
}
result += ch;
}
return result;
}
} // namespace
std::string SystemBase::GetGraphvizString(
std::optional<int> max_depth,
const std::map<std::string, std::string>& options) const {
const GraphvizFragment result = GetGraphvizFragment(max_depth, options);
return fmt::format(
"digraph _{} {{\n"
"rankdir=LR\n"
"{}"
"}}\n",
system_id_, fmt::join(result.fragments, ""));
}
SystemBase::GraphvizFragment SystemBase::GetGraphvizFragment(
std::optional<int> max_depth,
const std::map<std::string, std::string>& options) const {
DRAKE_THROW_UNLESS(max_depth.value_or(0) >= 0);
GraphvizFragmentParams params;
params.max_depth = max_depth.value_or(std::numeric_limits<int>::max());
params.options = options;
params.node_id = fmt::format("s{}", system_id_.get_value());
// The header opens with our class name, sans namespaces and templates.
const std::string system_type = std::regex_replace(
NiceTypeName::RemoveNamespaces(NiceTypeName::Get(*this)),
std::regex("<.*>$"), std::string());
params.header_lines.push_back(
fmt::format("<B>{}</B>", HtmlEscape(system_type)));
// If we have a name, then add it to the header.
const std::string system_name = this->get_name();
if (!system_name.empty() && system_name != this->GetMemoryObjectName()) {
params.header_lines.push_back(
fmt::format("name={}", HtmlEscape(system_name)));
}
return DoGetGraphvizFragment(params);
}
SystemBase::GraphvizFragment SystemBase::DoGetGraphvizFragment(
const GraphvizFragmentParams& params) const {
GraphvizFragment result;
// Unpack the options.
const bool split_in_twain = [¶ms]() {
auto iter = params.options.find("split");
return (iter != params.options.end()) && (iter->second == "I/O");
}();
const std::string node_id_input =
split_in_twain ? params.node_id + "in" : params.node_id;
const std::string node_id_output =
split_in_twain ? params.node_id + "out" : params.node_id;
// Prepare some helpful constants.
const int num_inputs = num_input_ports();
const int num_outputs = num_output_ports();
const int min_num_inputs_outputs = std::min(num_inputs, num_outputs);
const int max_num_inputs_outputs = std::max(num_inputs, num_outputs);
result.input_ports.reserve(num_inputs);
result.output_ports.reserve(num_outputs);
// Prepare a table of port labels. Input ports are on the left (col 0), and
// output ports are on the right (col 1). A nullopt label indicates that the
// <TD> cell should not be emitted. This is also a convenient time to populate
// our result's list of port identifiers.
MatrixX<std::optional<std::string>> port_labels(max_num_inputs_outputs, 2);
{
std::vector<std::string> labels_input =
GetGraphvizPortLabels(/* input= */ true);
std::vector<std::string> labels_output =
GetGraphvizPortLabels(/* input= */ false);
for (int i = 0; i < num_inputs; ++i) {
port_labels(i, 0) = std::move(labels_input[i]);
result.input_ports.push_back(fmt::format("{}:u{}", node_id_input, i));
}
for (int i = 0; i < num_outputs; ++i) {
port_labels(i, 1) = std::move(labels_output[i]);
result.output_ports.push_back(fmt::format("{}:y{}", node_id_output, i));
}
}
// Prepare the table's styling. We'll expand the shorter of the two columns to
// match the other, longer column.
MatrixX<std::string> port_styles(max_num_inputs_outputs, 2);
if (num_inputs != num_outputs) {
const int shorter_col = num_inputs < num_outputs ? 0 : 1;
if (min_num_inputs_outputs == 1) {
// When the shorter column is just a single port, expand that port to fill
// the entire column.
port_styles(0, shorter_col) =
fmt::format("ROWSPAN=\"{}\"", max_num_inputs_outputs);
} else {
// Otherwise, use a (single) greyed-out cell to fill up the remainder.
const int filler_row = min_num_inputs_outputs;
const int remainder = max_num_inputs_outputs - min_num_inputs_outputs;
port_labels(filler_row, shorter_col) = "";
port_styles(filler_row, shorter_col) =
fmt::format("COLOR=\"grey\" ROWSPAN=\"{}\" SIDES=\"{}\"", remainder,
shorter_col == 0 ? "BL" : "BR");
}
}
// When in split_in_twain mode, we'll emit two nodes (the input node, then the
// output node); otherwise we'll emit just one node.
const int num_nodes = split_in_twain ? 2 : 1;
for (int node = 0; node < num_nodes; ++node) {
DRAKE_DEMAND(split_in_twain || node_id_input == node_id_output);
const std::string& node_id = (node == 0) ? node_id_input : node_id_output;
const int node_num_rows =
(split_in_twain && node == 0) ? num_inputs
: (split_in_twain && node == 1) ? num_outputs
: max_num_inputs_outputs;
// Open the node, along with its label table and the table's header row.
result.fragments.push_back(fmt::format(
R"""({} [shape=none, border=0, label=<
<TABLE BORDER="0" CELLSPACING="0">
<TR><TD BORDER="1" COLSPAN="2">
{}
</TD></TR>
)""",
node_id, fmt::join(params.header_lines, "<BR/>\n")));
// Print the input and/or output port rows.
for (int i = 0; i < node_num_rows; ++i) {
result.fragments.push_back("<TR>\n");
for (int j = 0; j < 2; ++j) {
if (split_in_twain && j != node) {
// The dead column of a twained node is just a single dotted box.
if (i == 0) {
result.fragments.push_back(fmt::format(
R"""(<TD BORDER="1" STYLE="dotted" COLOR="cadetblue" ROWSPAN="{}">
<FONT COLOR="cadetblue">(split)</FONT>
</TD>
)""",
(j == 0) ? num_outputs : num_inputs));
}
continue;
}
if (port_labels(i, j).has_value()) {
result.fragments.push_back(fmt::format(
R"""(<TD PORT="{}{}" BORDER="1" {}>{}</TD>
)""",
(j == 0 ? 'u' : 'y'), i, port_styles(i, j), *port_labels(i, j)));
}
}
result.fragments.push_back("</TR>\n");
}
// Close the table, label, attributes, and node.
result.fragments.push_back(
R"""(</TABLE>
>];
)""");
}
return result;
}
std::vector<std::string> SystemBase::GetGraphvizPortLabels(bool input) const {
const int num_ports = input ? num_input_ports() : num_output_ports();
std::vector<std::string> result;
result.reserve(num_ports);
for (int i = 0; i < num_ports; ++i) {
const PortBase& port = [&]() -> const PortBase& {
if (input)
return GetInputPortBaseOrThrow("", i, /* warn_deprecated = */ false);
else
return GetOutputPortBaseOrThrow("", i, /* warn_deprecated = */ false);
}();
std::string label = HtmlEscape(port.get_name());
// For deprecated ports, use strikethrough and a unicode headstone (🪦).
if (port.get_deprecation().has_value()) {
label = fmt::format("<S>{}</S>\xF0\x9F\xAA\xA6", label);
}
// For ports that cannot carry any data, grey out the name.
if (port.get_data_type() == PortDataType::kVectorValued &&
port.size() == 0) {
label = fmt::format(R"""(<FONT COLOR="grey">{}</FONT>)""", label);
}
result.push_back(std::move(label));
}
return result;
}
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);
if (input_ports_[port_index]->get_deprecation().has_value())
WarnPortDeprecation(/* is_input = */ true, 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 {
const char* const info_link =
"For more information about Context-System mismatches, see "
"https://drake.mit.edu/"
"troubleshooting.html#framework-context-system-mismatch";
// Check if we are a subsystem within a Diagram and the user passed us the
// root context instead of our subsystem context. In that case, we can provide
// a more specific error message.
if (get_parent_service() != nullptr) {
// N.B. get_parent_service() is only non-null for subsystems in Diagrams.
const internal::SystemId root_id =
get_parent_service()->GetRootSystemBase().get_system_id();
if (context.get_system_id() == root_id) {
throw std::logic_error(fmt::format(
"A function call on a {} system named '{}' was passed the root "
"Diagram's Context instead of the appropriate subsystem Context. "
"Use GetMyContextFromRoot() or similar to acquire the appropriate "
"subsystem Context.\n{}",
this->GetSystemType(), this->GetSystemPathname(), info_link));
}
}
// Check if the context is a sub-context whose root context was created by
// this Diagram. In that case, we can provide a more specific error message.
const ContextBase& root_context = [&context]() -> const ContextBase& {
const ContextBase* iterator = &context;
while (true) {
const ContextBase* parent =
internal::SystemBaseContextBaseAttorney::get_parent_base(*iterator);
if (parent == nullptr) {
return *iterator;
}
iterator = parent;
}
}();
if (root_context.get_system_id() == get_system_id()) {
throw std::logic_error(fmt::format(
"A function call on the root Diagram was passed a subcontext "
"associated with its subsystem named '{}' instead of the root "
"context. When calling a function on a the root Digram, you must "
"pass a reference to the root Context, not a subcontext.\n{}",
context.GetSystemPathname(), info_link));
}
throw std::logic_error(fmt::format(
"A function call on a {} system named '{}' was passed the Context of "
"a system named '{}' instead of the appropriate subsystem Context.\n{}",
this->GetSystemType(), this->GetSystemPathname(),
context.GetSystemPathname(), info_link));
}
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()));
}
}
void SystemBase::WarnPortDeprecation(bool is_input, int port_index) const {
// Locate the deprecated PortBase (while sanity-checking our arguments).
PortBase* port;
if (is_input) {
port = input_ports_.at(port_index).get();
} else {
port = output_ports_.at(port_index).get();
}
DRAKE_DEMAND(port != nullptr);
DRAKE_DEMAND(port->get_deprecation().has_value());
// If this port object has already been warned about, then return quickly.
std::atomic<bool>* const deprecation_already_warned =
internal::PortBaseAttorney::deprecation_already_warned(port);
const bool had_already_warned = deprecation_already_warned->exchange(true);
if (had_already_warned) {
return;
}
// The had_already_warned above is a *per instance* warning, for performance.
// We'd like to warn at most once *per process*; therefore, we have a second
// layer of checking, using a unique lookup key for SystemType + PortBase.
drake::internal::FNV1aHasher hash;
hash_append(hash, this->GetSystemType());
hash_append(hash, is_input);
hash_append(hash, port->get_name());
const size_t key = size_t{hash};
static std::mutex g_mutex;
static std::unordered_set<size_t> g_warned_hash;
{
std::lock_guard lock(g_mutex);
const bool inserted = g_warned_hash.insert(key).second;
if (!inserted) {
// The key was already in the map, which means that we've already
// warned about this port name on this particular system subclass.
return;
}
}
// We hadn't warned yet, so we'll warn now.
const std::string& description = port->GetFullDescription();
const std::string& deprecation = port->get_deprecation().value();
const char* const message = deprecation.size() ? deprecation.c_str() :
"no deprecation details were provided";
drake::log()->warn("{} is deprecated: {}", description, message);
}
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);
}
std::vector<std::string> DiagramSystemBaseAttorney::GetGraphvizPortLabels(
const SystemBase& system, bool input) {
return system.GetGraphvizPortLabels(input);
}
} // namespace internal
} // namespace systems
} // namespace drake