-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
simulator_test.cc
3021 lines (2580 loc) · 120 KB
/
simulator_test.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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "drake/systems/analysis/simulator.h"
#include <cmath>
#include <complex>
#include <functional>
#include <map>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <unsupported/Eigen/AutoDiff>
#include "drake/common/autodiff.h"
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/test_utilities/is_dynamic_castable.h"
#include "drake/common/text_logging.h"
#include "drake/systems/analysis/explicit_euler_integrator.h"
#include "drake/systems/analysis/implicit_euler_integrator.h"
#include "drake/systems/analysis/runge_kutta2_integrator.h"
#include "drake/systems/analysis/runge_kutta3_integrator.h"
#include "drake/systems/analysis/test_utilities/controlled_spring_mass_system.h"
#include "drake/systems/analysis/test_utilities/logistic_system.h"
#include "drake/systems/analysis/test_utilities/my_spring_mass_system.h"
#include "drake/systems/analysis/test_utilities/spring_mass_system.h"
#include "drake/systems/analysis/test_utilities/stateless_system.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/framework/event.h"
#include "drake/systems/primitives/constant_vector_source.h"
#include "drake/systems/primitives/integrator.h"
#include "drake/systems/primitives/vector_log_sink.h"
using drake::systems::WitnessFunction;
using drake::systems::Simulator;
using drake::systems::RungeKutta3Integrator;
using drake::systems::ImplicitEulerIntegrator;
using drake::systems::ExplicitEulerIntegrator;
using LogisticSystem = drake::systems::analysis_test::LogisticSystem<double>;
using StatelessSystem = drake::systems::analysis_test::StatelessSystem<double>;
using Eigen::AutoDiffScalar;
using Eigen::NumTraits;
using std::complex;
using testing::ElementsAre;
using testing::ElementsAreArray;
// N.B. internal::GetPreviousNormalizedValue() is tested separately in
// simulator_denorm_test.cc.
namespace drake {
namespace systems {
namespace {
// @TODO(edrumwri): Use test fixtures to streamline this file and promote reuse.
// Stateless system with a DoCalcTimeDerivatives implementation. This class
// will serve to confirm that the time derivative calculation is not called.
class StatelessSystemPlusDerivs : public systems::LeafSystem<double> {
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(StatelessSystemPlusDerivs);
public:
StatelessSystemPlusDerivs() {}
bool was_do_calc_time_derivatives_called() const {
return do_calc_time_derivatives_called_;
}
private:
void DoCalcTimeDerivatives(
const Context<double>& context,
ContinuousState<double>* derivatives) const override {
// Modifying system members in DoCalcTimeDerivatives() is an anti-pattern.
// It is done here only to simplify the testing code.
do_calc_time_derivatives_called_ = true;
}
mutable bool do_calc_time_derivatives_called_{false};
};
// Empty diagram
class StatelessDiagram : public Diagram<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(StatelessDiagram);
explicit StatelessDiagram(double offset) {
DiagramBuilder<double> builder;
// Add the empty system (and its witness function).
stateless_ = builder.AddSystem<StatelessSystem>(offset,
WitnessFunctionDirection::kCrossesZero);
stateless_->set_name("stateless_diagram");
builder.BuildInto(this);
}
void set_publish_callback(
std::function<void(const Context<double>&)> callback) {
stateless_->set_publish_callback(callback);
}
private:
StatelessSystem* stateless_ = nullptr;
};
// Diagram for testing witness functions.
class ExampleDiagram : public Diagram<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ExampleDiagram);
explicit ExampleDiagram(double offset) {
DiagramBuilder<double> builder;
// Add the empty system (and its witness function).
stateless_diag_ = builder.AddSystem<StatelessDiagram>(offset);
stateless_diag_->set_name("diagram_of_stateless_diagram");
builder.BuildInto(this);
}
void set_publish_callback(
std::function<void(const Context<double>&)> callback) {
stateless_diag_->set_publish_callback(callback);
}
private:
StatelessDiagram* stateless_diag_ = nullptr;
};
// Tests that DoCalcTimeDerivatives() is not called when the system has no
// continuous state.
GTEST_TEST(SimulatorTest, NoUnexpectedDoCalcTimeDerivativesCall) {
// Construct the simulation using the RK2 (fixed step) integrator with a small
// time step.
StatelessSystemPlusDerivs system;
const double final_time = 1.0;
const double h = 1e-3;
Simulator<double> simulator(system);
simulator.reset_integrator<RungeKutta2Integrator<double>>(h);
simulator.AdvanceTo(final_time);
// Verify no derivative calculations.
EXPECT_FALSE(system.was_do_calc_time_derivatives_called());
}
// Tests that simulation only takes a single step when there is no continuous
// state, regardless of the integrator maximum step size (and no discrete state
// or events).
GTEST_TEST(SimulatorTest, NoContinuousStateYieldsSingleStep) {
const double final_time = 1.0;
StatelessSystem system(
final_time + 1, /* publish time *after* final time */
WitnessFunctionDirection::kCrossesZero);
// Construct the simulation using the RK2 (fixed step) integrator with a small
// time step.
const double h = 1e-3;
Simulator<double> simulator(system);
simulator.reset_integrator<RungeKutta2Integrator<double>>(h);
simulator.AdvanceTo(final_time);
EXPECT_EQ(simulator.get_num_steps_taken(), 1);
}
// Tests ability of simulation to identify the proper number of witness function
// triggerings going from negative to non-negative witness function evaluation
// using a Diagram. This particular example uses an empty system and a clock as
// the witness function, which makes it particularly easy to determine when the
// witness function should trigger.
GTEST_TEST(SimulatorTest, DiagramWitness) {
// Set empty system to trigger when time is +1.
const double trigger_time = 1.0;
ExampleDiagram system(trigger_time);
double publish_time = -1;
int num_publishes = 0;
system.set_publish_callback([&](const Context<double>& context) {
num_publishes++;
publish_time = context.get_time();
});
const double h = 1;
Simulator<double> simulator(system);
simulator.reset_integrator<RungeKutta2Integrator<double>>(h);
simulator.set_publish_at_initialization(false);
simulator.set_publish_every_time_step(false);
simulator.get_mutable_context().SetTime(0);
simulator.AdvanceTo(1);
// Publication should occur at witness function crossing.
EXPECT_EQ(1, num_publishes);
EXPECT_EQ(publish_time, trigger_time);
}
// A composite system using the logistic system with the clock-based
// witness function.
class CompositeSystem : public analysis_test::LogisticSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(CompositeSystem);
CompositeSystem(double k, double alpha, double nu, double trigger_time)
: LogisticSystem(k, alpha, nu), trigger_time_(trigger_time) {
this->DeclareContinuousState(1);
logistic_witness_ = this->MakeWitnessFunction(
"logistic witness", WitnessFunctionDirection::kCrossesZero,
&CompositeSystem::GetStateValue,
&CompositeSystem::CallLogisticsCallback);
clock_witness_ = this->MakeWitnessFunction(
"clock witness", WitnessFunctionDirection::kCrossesZero,
&CompositeSystem::CalcClockWitness,
&CompositeSystem::CallLogisticsCallback);
}
const WitnessFunction<double>* get_logistic_witness() const {
return logistic_witness_.get();
}
const WitnessFunction<double>* get_clock_witness() const {
return clock_witness_.get();
}
protected:
void DoGetWitnessFunctions(
const Context<double>&,
std::vector<const WitnessFunction<double>*>* w) const override {
w->push_back(clock_witness_.get());
w->push_back(logistic_witness_.get());
}
private:
double GetStateValue(const Context<double>& context) const {
return context.get_continuous_state()[0];
}
// The witness function is the time value itself plus the offset value.
double CalcClockWitness(const Context<double>& context) const {
return context.get_time() - trigger_time_;
}
void CallLogisticsCallback(const Context<double>& context,
const PublishEvent<double>& event) const {
LogisticSystem<double>::InvokePublishCallback(context, event);
}
const double trigger_time_;
std::unique_ptr<WitnessFunction<double>> logistic_witness_;
std::unique_ptr<WitnessFunction<double>> clock_witness_;
};
// An empty system using two clock witnesses.
class TwoWitnessStatelessSystem : public LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(TwoWitnessStatelessSystem);
explicit TwoWitnessStatelessSystem(double off1, double off2)
: offset1_(off1), offset2_(off2) {
PublishEvent<double> event([](const System<double>& system,
const Context<double>& callback_context,
const PublishEvent<double>& callback_event) {
dynamic_cast<const TwoWitnessStatelessSystem&>(system).PublishOnWitness(
callback_context, callback_event);
return EventStatus::Succeeded();
});
witness1_ = this->MakeWitnessFunction(
"clock witness1", WitnessFunctionDirection::kCrossesZero,
&TwoWitnessStatelessSystem::CalcClockWitness1, event);
witness2_ = this->MakeWitnessFunction(
"clock witness2", WitnessFunctionDirection::kCrossesZero,
&TwoWitnessStatelessSystem::CalcClockWitness2, event);
}
void set_publish_callback(
std::function<void(const Context<double>&)> callback) {
publish_callback_ = callback;
}
private:
void DoGetWitnessFunctions(
const Context<double>&,
std::vector<const WitnessFunction<double>*>* w) const override {
w->push_back(witness1_.get());
w->push_back(witness2_.get());
}
void PublishOnWitness(const Context<double>& context,
const PublishEvent<double>&) const {
if (publish_callback_ != nullptr) publish_callback_(context);
}
// The witness function is the time value itself minus the offset value.
double CalcClockWitness1(const Context<double>& context) const {
return context.get_time() - offset1_;
}
// The witness function is the time value itself minus the offset value.
double CalcClockWitness2(const Context<double>& context) const {
return context.get_time() - offset2_;
}
std::unique_ptr<WitnessFunction<double>> witness1_, witness2_;
const double offset1_;
const double offset2_;
std::function<void(const Context<double>&)> publish_callback_{nullptr};
};
// Disables non-witness based publishing for witness function testing.
void DisableDefaultPublishing(Simulator<double>* s) {
s->set_publish_at_initialization(false);
s->set_publish_every_time_step(false);
}
// Initializes the Simulator's integrator to fixed step mode for witness
// function related tests.
void InitFixedStepIntegratorForWitnessTesting(Simulator<double>* s, double h) {
s->reset_integrator<RungeKutta2Integrator<double>>(h);
s->get_mutable_integrator().set_fixed_step_mode(true);
s->get_mutable_integrator().set_maximum_step_size(h);
DisableDefaultPublishing(s);
}
// Initializes the Simulator's integrator to variable step mode for witness
// function related tests.
void InitVariableStepIntegratorForWitnessTesting(Simulator<double>* s) {
s->reset_integrator<RungeKutta3Integrator<double>>();
DisableDefaultPublishing(s);
}
// Tests witness function isolation when operating in fixed step mode without
// specifying accuracy (i.e., no isolation should be performed, and the witness
// function should trigger at the end of the step). See
// Simulator::GetCurrentWitnessTimeIsolation() for more information.
GTEST_TEST(SimulatorTest, FixedStepNoIsolation) {
LogisticSystem system(1e-8, 100, 1);
double publish_time = 0;
system.set_publish_callback([&](const Context<double>& context) {
publish_time = context.get_time();
});
const double h = 1e-3;
Simulator<double> simulator(system);
InitFixedStepIntegratorForWitnessTesting(&simulator, h);
Context<double>& context = simulator.get_mutable_context();
context.get_mutable_continuous_state()[0] = -1;
simulator.AdvanceTo(h);
// Verify that no witness isolation is done.
EXPECT_FALSE(simulator.GetCurrentWitnessTimeIsolation());
// Verify that the witness function triggered at h.
EXPECT_EQ(publish_time, h);
}
// Tests the witness function isolation window gets smaller *when Simulator
// uses a variable step integrator* as the accuracy in the context becomes
// tighter. See Simulator::GetCurrentWitnessTimeIsolation() for documentation of
// this effect. Note that we cannot guarantee that the witness function zero is
// isolated to greater accuracy because variable step integration implies that
// we will not know the brackets on the interval input to the witness isolation
// function- simulating with low accuracy could inadvertently isolate a
// zero to perfect tolerance because the step taken by the integrator
// fortuitously lands on the zero.
GTEST_TEST(SimulatorTest, VariableStepIsolation) {
// Set empty system to trigger when time is +1 (setting is arbitrary for this
// test).
StatelessSystem system(1.0, WitnessFunctionDirection::kCrossesZero);
double publish_time = 0;
system.set_publish_callback([&](const Context<double>& context){
publish_time = context.get_time();
});
Simulator<double> simulator(system);
InitVariableStepIntegratorForWitnessTesting(&simulator);
Context<double>& context = simulator.get_mutable_context();
// Set the initial accuracy in the context.
double accuracy = 1.0;
context.SetAccuracy(accuracy);
// Set the initial empty system evaluation.
double eval = std::numeric_limits<double>::infinity();
// Loop, decreasing accuracy as we go.
while (accuracy > 1e-8) {
// Verify that the isolation window is computed.
std::optional<double> iso_win = simulator.GetCurrentWitnessTimeIsolation();
EXPECT_TRUE(iso_win);
// Verify that the new evaluation is closer to zero than the old one.
EXPECT_LT(iso_win.value(), eval);
eval = iso_win.value();
// Increase the accuracy, which should shrink the isolation window when
// next retrieved.
accuracy *= 0.1;
context.SetAccuracy(accuracy);
}
}
// Tests that witness function isolation accuracy increases with increasing
// accuracy in the context. This test uses fixed step integration, which implies
// a particular mechanism for the witness window isolation length (see
// Simulator::GetCurrentWitnessTimeIsolation()). This function tests that the
// accuracy of the witness function isolation time increases as accuracy
// (in the Context) is increased.
GTEST_TEST(SimulatorTest, FixedStepIncreasingIsolationAccuracy) {
// Set empty system to trigger when time is +1.
StatelessSystem system(1.0, WitnessFunctionDirection::kCrossesZero);
double publish_time = 0;
system.set_publish_callback([&](const Context<double>& context){
publish_time = context.get_time();
});
const double h = 10;
Simulator<double> simulator(system);
InitFixedStepIntegratorForWitnessTesting(&simulator, h);
Context<double>& context = simulator.get_mutable_context();
// Get the (one) witness function.
std::vector<const WitnessFunction<double>*> witness;
system.GetWitnessFunctions(context, &witness);
DRAKE_DEMAND(witness.size() == 1);
// Set the initial accuracy in the context.
double accuracy = 1.0;
context.SetAccuracy(accuracy);
// Set the initial empty system evaluation.
double eval = std::numeric_limits<double>::infinity();
// Loop, decreasing accuracy as we go.
while (accuracy > 1e-8) {
// (Re)set the time and initial state.
context.SetTime(0);
simulator.Initialize();
// Simulate to h.
simulator.AdvanceTo(h);
// CalcWitnessValue the witness function.
context.SetTime(publish_time);
double new_eval = witness.front()->CalcWitnessValue(context);
// Verify that the new evaluation is closer to zero than the old one.
EXPECT_LT(new_eval, eval);
eval = new_eval;
// Increase the accuracy.
accuracy *= 0.1;
context.SetAccuracy(accuracy);
}
}
// Tests ability of simulation to identify the witness function triggering
// over an interval *where both witness functions change sign from the beginning
// to the end of the interval.
GTEST_TEST(SimulatorTest, MultipleWitnesses) {
// Set up the trigger time.
const double trigger_time = 1e-2;
// Create a CompositeSystem, which uses two witness functions.
CompositeSystem system(1e-8, 100, 1, trigger_time);
std::vector<std::pair<double, const WitnessFunction<double> *>> triggers;
system.set_publish_callback([&](const Context<double> &context) {
// Get the witness functions.
std::vector<const WitnessFunction<double> *> witnesses;
system.GetWitnessFunctions(context, &witnesses);
DRAKE_DEMAND(witnesses.size() == 2);
// CalcWitnessValue them.
double clock_eval = witnesses.front()->CalcWitnessValue(context);
double logistic_eval = witnesses.back()->CalcWitnessValue(context);
// Store the one that evaluates closest to zero.
if (std::abs(clock_eval) < std::abs(logistic_eval)) {
triggers.emplace_back(context.get_time(), witnesses.front());
} else {
// They should not be very close to one another.
const double tol = 1e-8;
DRAKE_ASSERT(std::abs(logistic_eval - clock_eval) > tol);
triggers.emplace_back(context.get_time(), witnesses.back());
}
});
const double h = 1e-3;
Simulator<double> simulator(system);
DisableDefaultPublishing(&simulator);
simulator.reset_integrator<ImplicitEulerIntegrator<double>>();
simulator.get_mutable_integrator().set_maximum_step_size(h);
simulator.get_mutable_integrator().set_target_accuracy(0.1);
// Set initial time and state.
Context<double>& context = simulator.get_mutable_context();
context.get_mutable_continuous_state()[0] = -1;
context.SetTime(0);
// Isolate witness functions to high accuracy.
const double tol = 1e-10;
context.SetAccuracy(tol);
// Simulate.
simulator.AdvanceTo(0.1);
// We expect exactly two triggerings.
ASSERT_EQ(triggers.size(), 2);
// Check that the witnesses triggered in the order we expect.
EXPECT_EQ(system.get_logistic_witness(), triggers.front().second);
EXPECT_EQ(system.get_clock_witness(), triggers.back().second);
// We expect that the clock witness will trigger second at a time of ~1s.
EXPECT_NEAR(triggers.back().first, trigger_time, tol);
}
// Tests ability of simulation to identify two witness functions triggering
// at the identical time over an interval.
GTEST_TEST(SimulatorTest, MultipleWitnessesIdentical) {
// Create a StatelessSystem that uses two identical witness functions.
TwoWitnessStatelessSystem system(1.0, 1.0);
bool published = false;
std::unique_ptr<Simulator<double>> simulator;
system.set_publish_callback([&](const Context<double> &context) {
// Get the witness functions.
std::vector<const WitnessFunction<double> *> witnesses;
system.GetWitnessFunctions(context, &witnesses);
DRAKE_DEMAND(witnesses.size() == 2);
// CalcWitnessValue them.
double w1 = witnesses.front()->CalcWitnessValue(context);
double w2 = witnesses.back()->CalcWitnessValue(context);
// Verify both are equivalent.
EXPECT_EQ(w1, w2);
// Verify that they are triggering.
std::optional<double> iso_time =
simulator->GetCurrentWitnessTimeIsolation();
EXPECT_TRUE(iso_time);
EXPECT_LT(std::abs(w1), iso_time.value());
// Indicate that the method has been called.
published = true;
});
const double h = 2;
simulator = std::make_unique<Simulator<double>>(system);
DisableDefaultPublishing(simulator.get());
simulator->get_mutable_integrator().set_maximum_step_size(h);
// Isolate witness functions to high accuracy.
const double tol = 1e-12;
simulator->get_mutable_context().SetAccuracy(tol);
// Simulate.
simulator->AdvanceTo(10);
// Verify one publish.
EXPECT_TRUE(published);
}
// Tests ability of simulation to identify two witness functions triggering
// over an interval where (a) both functions change sign over the interval and
// (b) after the interval is "chopped down" (to isolate the first witness
// triggering), the second witness does not trigger.
//
// How this function tests this functionality: Both functions will change sign
// over the interval [0, 2.1]. Since the first witness function triggers at
// t=1.0, isolating the firing time should cause the second witness to no longer
// trigger (at t=1.0). When the Simulator continues stepping (i.e., after the
// event corresponding to the first witness function is handled), the second
// witness should then be triggered at t=2.0.
GTEST_TEST(SimulatorTest, MultipleWitnessesStaggered) {
// Set the trigger times.
const double first_time = 1.0;
const double second_time = 2.0;
// Create a StatelessSystem that uses clock witnesses.
TwoWitnessStatelessSystem system(first_time, second_time);
std::vector<double> publish_times;
system.set_publish_callback([&](const Context<double> &context) {
publish_times.push_back(context.get_time());
});
const double h = 3;
Simulator<double> simulator(system);
DisableDefaultPublishing(&simulator);
simulator.get_mutable_integrator().set_maximum_step_size(h);
// Isolate witness functions to high accuracy.
const double tol = 1e-12;
simulator.get_mutable_context().SetAccuracy(tol);
// Get the isolation interval tolerance.
const std::optional<double> iso_tol =
simulator.GetCurrentWitnessTimeIsolation();
EXPECT_TRUE(iso_tol);
// Simulate to right after the second one should have triggered.
simulator.AdvanceTo(2.1);
// Verify two publishes.
EXPECT_EQ(publish_times.size(), 2);
// Verify that the publishes are at the expected times.
EXPECT_NEAR(publish_times.front(), first_time, iso_tol.value());
EXPECT_NEAR(publish_times.back(), second_time, iso_tol.value());
}
// Tests ability of simulation to identify the proper number of witness function
// triggerings going from negative to non-negative witness function evaluation.
// This particular example uses an empty system and a clock as the witness
// function, which makes it particularly easy to determine when the witness
// function should trigger.
GTEST_TEST(SimulatorTest, WitnessTestCountSimpleNegToZero) {
// Set empty system to trigger when time is +1.
StatelessSystem system(+1, WitnessFunctionDirection::kCrossesZero);
int num_publishes = 0;
system.set_publish_callback([&](const Context<double>& context){
num_publishes++;
});
const double h = 1;
Simulator<double> simulator(system);
InitFixedStepIntegratorForWitnessTesting(&simulator, h);
Context<double>& context = simulator.get_mutable_context();
context.SetTime(0);
simulator.AdvanceTo(1);
// Publication should occur at witness function crossing.
EXPECT_EQ(1, num_publishes);
}
// Tests ability of simulation to identify the proper number of witness function
// triggerings going from zero to positive witness function evaluation. This
// particular example uses an empty system and a clock as the witness function,
// which makes it particularly easy to determine when the witness function
// should trigger.
GTEST_TEST(SimulatorTest, WitnessTestCountSimpleZeroToPos) {
// Set empty system to trigger when time is zero.
StatelessSystem system(0, WitnessFunctionDirection::kCrossesZero);
int num_publishes = 0;
system.set_publish_callback([&](const Context<double>& context){
num_publishes++;
});
const double h = 1;
Simulator<double> simulator(system);
InitFixedStepIntegratorForWitnessTesting(&simulator, h);
Context<double>& context = simulator.get_mutable_context();
context.SetTime(0);
simulator.AdvanceTo(1);
// Verify that no publication is performed when stepping to 1.
EXPECT_EQ(0, num_publishes);
}
// Tests ability of simulation to identify the proper number of witness function
// triggerings (zero) for a positive-to-negative trigger. Uses the same empty
// system from WitnessTestCountSimple.
GTEST_TEST(SimulatorTest, WitnessTestCountSimplePositiveToNegative) {
// Set empty system to trigger when time is +1.
StatelessSystem system(+1, WitnessFunctionDirection::
kPositiveThenNonPositive);
int num_publishes = 0;
system.set_publish_callback([&](const Context<double>& context){
num_publishes++;
});
const double h = 1;
Simulator<double> simulator(system);
InitFixedStepIntegratorForWitnessTesting(&simulator, h);
Context<double>& context = simulator.get_mutable_context();
context.SetTime(0);
simulator.AdvanceTo(2);
// Publication should not occur (witness function should initially evaluate
// to a negative value, then will evolve to a positive value).
EXPECT_EQ(0, num_publishes);
}
// Tests ability of simulation to identify the proper number of witness function
// triggerings (zero) for a negative-to-positive trigger. Uses the same empty
// system from WitnessTestCountSimple.
GTEST_TEST(SimulatorTest, WitnessTestCountSimpleNegativeToPositive) {
StatelessSystem system(0, WitnessFunctionDirection::
kNegativeThenNonNegative);
int num_publishes = 0;
system.set_publish_callback([&](const Context<double>& context){
num_publishes++;
});
const double h = 1;
Simulator<double> simulator(system);
InitFixedStepIntegratorForWitnessTesting(&simulator, h);
Context<double>& context = simulator.get_mutable_context();
context.SetTime(-1);
simulator.AdvanceTo(1);
// Publication should occur at witness function crossing.
EXPECT_EQ(1, num_publishes);
}
// Tests ability of simulation to identify the proper number of witness function
// triggerings. This particular example, the logistic function, is particularly
// challenging for detecting exactly one zero crossing under the
// parameterization in use. The logic system's state just barely crosses zero
// (at t << 1) and then hovers around zero afterward.
GTEST_TEST(SimulatorTest, WitnessTestCountChallenging) {
LogisticSystem system(1e-8, 100, 1);
int num_publishes = 0;
system.set_publish_callback([&](const Context<double>& context){
num_publishes++;
});
const double h = 1e-6;
Simulator<double> simulator(system);
InitFixedStepIntegratorForWitnessTesting(&simulator, h);
Context<double>& context = simulator.get_mutable_context();
context.get_mutable_continuous_state()[0] = -1;
simulator.AdvanceTo(1e-4);
// Publication should occur only at witness function crossing.
EXPECT_EQ(1, num_publishes);
}
// A system that publishes with a period of 1s and offset of 0.5s and also
// publishes when a witness function triggers (happens when a time is crossed).
class PeriodicPublishWithTimedWitnessSystem final : public LeafSystem<double> {
public:
explicit PeriodicPublishWithTimedWitnessSystem(double witness_trigger_time) {
// Declare the periodic publish.
this->DeclarePeriodicPublishEvent(
1.0, 0.5, &PeriodicPublishWithTimedWitnessSystem::PublishPeriodic);
// Declare the publish event for the witness trigger.
PublishEvent<double> event([](const System<double>& system,
const Context<double>& callback_context,
const PublishEvent<double>& callback_event) {
dynamic_cast<const PeriodicPublishWithTimedWitnessSystem&>(system)
.PublishWitness(callback_context, callback_event);
return EventStatus::Succeeded();
});
witness_ = this->MakeWitnessFunction(
"timed_witness", WitnessFunctionDirection::kPositiveThenNonPositive,
[witness_trigger_time](const Context<double>& context) {
return witness_trigger_time - context.get_time();
},
event);
}
double periodic_publish_time() const { return periodic_publish_time_; }
double witness_publish_time() const { return witness_publish_time_; }
private:
std::unique_ptr<WitnessFunction<double>> witness_;
mutable double periodic_publish_time_{-1.0};
mutable double witness_publish_time_{-1.0};
void DoGetWitnessFunctions(
const Context<double>&,
std::vector<const WitnessFunction<double>*>* w) const {
*w = { witness_.get() };
}
// Modifying system members in System callbacks is an anti-pattern.
// It is done here (and below) only to simplify the testing code.
void PublishPeriodic(const Context<double>& context) const {
ASSERT_LT(periodic_publish_time_, 0.0);
periodic_publish_time_ = context.get_time();
}
void PublishWitness(const Context<double>& context,
const PublishEvent<double>&) const {
ASSERT_LT(witness_publish_time_, 0.0);
witness_publish_time_ = context.get_time();
}
};
// Tests ability of simulation to properly handle a sequence of a timed event
// and a witnessed triggered event. All three combinations of sequences are
// tested: witnessed then timed, timed then witnessed, and both triggering
// simultaneously.
GTEST_TEST(SimulatorTest, WitnessAndTimedSequences) {
// System will publish at 0.5. Witness function triggers at the specified
// time.
PeriodicPublishWithTimedWitnessSystem sys_25(0.25), sys_50(0.5), sys_75(0.75);
// Note: setting accuracy in the Context will not guarantee that the values
// in the tests are satisfied to the same accuracy. The test tolerances might
// need to be slightly adjusted in the future (with different integrators,
// adjustments to the witness isolation interval, etc.)
const double accuracy = 1e-12;
Simulator<double> sim_25(sys_25);
sim_25.get_mutable_context().SetAccuracy(accuracy);
sim_25.AdvanceTo(1.0);
EXPECT_NEAR(sys_25.witness_publish_time(), 0.25, accuracy);
// Timed events (here and below) should be bit exact.
EXPECT_EQ(sys_25.periodic_publish_time(), 0.5);
Simulator<double> sim_50(sys_50);
sim_50.get_mutable_context().SetAccuracy(accuracy);
sim_50.AdvanceTo(1.0);
EXPECT_NEAR(sys_50.witness_publish_time(), 0.5, accuracy);
EXPECT_EQ(sys_50.periodic_publish_time(), 0.5);
Simulator<double> sim_75(sys_75);
sim_75.get_mutable_context().SetAccuracy(accuracy);
sim_75.AdvanceTo(1.0);
EXPECT_NEAR(sys_75.witness_publish_time(), 0.75, accuracy);
EXPECT_EQ(sys_75.periodic_publish_time(), 0.5);
}
// TODO(edrumwri): Add tests for verifying that correct interval returned
// in the case of multiple witness functions. See issue #6184.
GTEST_TEST(SimulatorTest, SecondConstructor) {
// Create the spring-mass system and context.
analysis_test::MySpringMassSystem<double> spring_mass(1., 1., 0.);
auto context = spring_mass.CreateDefaultContext();
// Mark the context with an arbitrary value.
context->SetTime(3.);
/// Construct the simulator with the created context.
Simulator<double> simulator(spring_mass, std::move(context));
// Verify that context pointers are equivalent.
EXPECT_EQ(simulator.get_context().get_time(), 3.);
}
GTEST_TEST(SimulatorTest, MiscAPI) {
analysis_test::MySpringMassSystem<double> spring_mass(1., 1., 0.);
Simulator<double> simulator(spring_mass); // Use default Context.
// Default realtime rate should be zero.
EXPECT_TRUE(simulator.get_target_realtime_rate() == 0.);
simulator.set_target_realtime_rate(1.25);
EXPECT_TRUE(simulator.get_target_realtime_rate() == 1.25);
EXPECT_TRUE(std::isnan(simulator.get_actual_realtime_rate()));
// Set the integrator default step size.
const double h = 1e-3;
// Create the integrator.
simulator.reset_integrator<ExplicitEulerIntegrator<double>>(h);
// Initialize the simulator first.
simulator.Initialize();
}
GTEST_TEST(SimulatorTest, ContextAccess) {
analysis_test::MySpringMassSystem<double> spring_mass(1., 1., 0.);
Simulator<double> simulator(spring_mass); // Use default Context.
// Set the integrator default step size.
const double h = 1e-3;
// Create the integrator.
simulator.reset_integrator<ExplicitEulerIntegrator<double>>(h);
// Initialize the simulator first.
simulator.Initialize();
// Try some other context stuff.
simulator.get_mutable_context().SetTime(3.);
EXPECT_EQ(simulator.get_context().get_time(), 3.);
EXPECT_TRUE(simulator.has_context());
simulator.release_context();
EXPECT_FALSE(simulator.has_context());
DRAKE_EXPECT_THROWS_MESSAGE(simulator.Initialize(),
".*Initialize.*Context.*not.*set.*");
// Create another context.
auto ucontext = spring_mass.CreateDefaultContext();
ucontext->SetTime(3.);
simulator.reset_context(std::move(ucontext));
EXPECT_EQ(simulator.get_context().get_time(), 3.);
EXPECT_TRUE(simulator.has_context());
simulator.reset_context(nullptr);
EXPECT_FALSE(simulator.has_context());
}
// Try a purely continuous system with no sampling.
GTEST_TEST(SimulatorTest, SpringMassNoSample) {
const double kSpring = 300.0; // N/m
const double kMass = 2.0; // kg
// Set the integrator default step size.
const double h = 1e-3;
analysis_test::MySpringMassSystem<double> spring_mass(kSpring, kMass, 0.);
Simulator<double> simulator(spring_mass); // Use default Context.
// Set initial condition using the Simulator's internal Context.
spring_mass.set_position(&simulator.get_mutable_context(), 0.1);
// Create the integrator.
simulator.reset_integrator<ExplicitEulerIntegrator<double>>(h);
simulator.set_target_realtime_rate(0.5);
// Request forced-publishes at every internal step.
simulator.set_publish_at_initialization(true);
simulator.set_publish_every_time_step(true);
// Set the integrator and initialize the simulator.
simulator.Initialize();
// Simulate for 1 second.
simulator.AdvanceTo(1.);
EXPECT_NEAR(simulator.get_context().get_time(), 1., 1e-8);
EXPECT_EQ(simulator.get_num_steps_taken(), 1000);
EXPECT_EQ(simulator.get_num_discrete_updates(), 0);
EXPECT_EQ(spring_mass.get_publish_count(), 1001);
EXPECT_EQ(spring_mass.get_update_count(), 0);
// Current time is 1. An earlier final time should fail.
EXPECT_THROW(simulator.AdvanceTo(0.5), std::runtime_error);
}
// Test ability to swap integrators mid-stream.
GTEST_TEST(SimulatorTest, ResetIntegratorTest) {
const double kSpring = 300.0; // N/m
const double kMass = 2.0; // kg
// set the integrator default step size
const double h = 1e-3;
analysis_test::MySpringMassSystem<double> spring_mass(kSpring, kMass, 0.);
Simulator<double> simulator(spring_mass); // Use default Context.
// Set initial condition using the Simulator's internal Context.
spring_mass.set_position(&simulator.get_mutable_context(), 0.1);
// Get the context.
Context<double>& context = simulator.get_mutable_context();
// Create the integrator with the simple spelling.
simulator.reset_integrator<ExplicitEulerIntegrator<double>>(h);
// Set the integrator and initialize the simulator
simulator.Initialize();
// Simulate for 1/2 second.
simulator.AdvanceTo(0.5);
// Reset the integrator.
simulator.reset_integrator<RungeKutta2Integrator<double>>(h);
// Simulate to 1 second..
simulator.AdvanceTo(1.);
EXPECT_NEAR(context.get_time(), 1., 1e-8);
// Number of steps will have been reset.
EXPECT_EQ(simulator.get_num_steps_taken(), 500);
}
// Because of arbitrary possible delays we can't do a very careful test of
// the realtime rate control. However, we can at least say that the simulation
// should not proceed much *faster* than the rate we select.
GTEST_TEST(SimulatorTest, RealtimeRate) {
analysis_test::MySpringMassSystem<double> spring_mass(1., 1., 0.);
Simulator<double> simulator(spring_mass); // Use default Context.
simulator.set_target_realtime_rate(1.); // No faster than 1X real time.
simulator.get_mutable_integrator().set_maximum_step_size(0.001);
simulator.get_mutable_context().SetTime(0.);
simulator.Initialize();
simulator.AdvanceTo(1.); // Simulate for 1 simulated second.
EXPECT_TRUE(simulator.get_actual_realtime_rate() <= 1.1);
simulator.set_target_realtime_rate(5.); // No faster than 5X real time.
simulator.get_mutable_context().SetTime(0.);
simulator.Initialize();
simulator.AdvanceTo(1.); // Simulate for 1 more simulated second.
EXPECT_TRUE(simulator.get_actual_realtime_rate() <= 5.1);
}
// Tests that if publishing every time step is disabled and publish on
// initialization is enabled, publish only happens on initialization.
GTEST_TEST(SimulatorTest, DisablePublishEveryTimestep) {
analysis_test::MySpringMassSystem<double> spring_mass(1., 1., 0.);
Simulator<double> simulator(spring_mass); // Use default Context.
simulator.set_publish_at_initialization(true);
simulator.set_publish_every_time_step(false);
simulator.get_mutable_context().SetTime(0.);
simulator.Initialize();
// Publish should happen on initialization.
EXPECT_EQ(1, simulator.get_num_publishes());
// Simulate for 1 simulated second. Publish should not happen.
simulator.AdvanceTo(1.);
EXPECT_EQ(1, simulator.get_num_publishes());
}
// Repeat the previous test but now the continuous steps are interrupted
// by a discrete sample every 1/30 second. The step size doesn't divide that