Drake
random_source.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <memory>
4 #include <random>
5 #include <vector>
6 
8 #include "drake/common/unused.h"
11 
12 namespace drake {
13 namespace systems {
14 
15 namespace internal {
16 
17 template <typename Generator = std::mt19937>
18 typename Generator::result_type generate_unique_seed();
19 
20 /// State for a given random distribution and generator. This owns both the
21 /// distribution and the generator.
22 template <typename Distribution, typename Generator = std::mt19937>
23 class RandomState {
24  public:
26 
27  typedef typename Generator::result_type Seed;
28 
29  explicit RandomState(Seed seed) : generator_(seed) {}
30 
31  /// Generate the next random value with the given distribution.
32  double GetNextValue() { return distribution_(generator_); }
33 
34  private:
35  // TODO(russt): Obtain consistent results across multiple platforms (#4361).
36  Generator generator_;
37  Distribution distribution_;
38 };
39 
40 /// A source block which generates random numbers at a fixed sampling interval,
41 /// with a zero-order hold between samples. For continuous-time systems, this
42 /// can be interpreted as a band-limited approximation of continuous white noise
43 /// (with a power-spectral density of the form Ts * sinc^2( omega * Ts ), where
44 /// Ts is the sampling interval.
45 ///
46 /// @tparam Distribution A class modeling the c++ RandomNumberDistribution
47 /// concept.
48 /// http://en.cppreference.com/w/cpp/concept/RandomNumberDistribution
49 ///
50 /// @note User code should not instantiate this class directly, but
51 /// should use systems::UniformRandomSource, systems::GaussianRandomSource, and
52 /// systems::ExponentialRandomSource systems instead.
53 ///
54 /// @note This system is only defined for the double scalar type.
55 ///
56 /// @note The hard-coding of (default) distribution parameters is imposed
57 /// intentionally to simplify analysis (by forcing systems taking noise inputs
58 /// to implement the shifting/scaling, the system itself contains all of the
59 /// necessary information for stochastic analysis).
60 ///
61 /// @see @ref stochastic_systems, UniformRandomSource, GaussianRandomSource,
62 /// ExponentialRandomSource.
63 ///
64 /// @ingroup primitive_systems
65 template <typename Distribution, typename Generator = std::mt19937>
66 class RandomSource : public LeafSystem<double> {
67  public:
69 
70  typedef internal::RandomState<Distribution, Generator> RandomState;
71  typedef typename RandomState::Seed Seed;
72 
73  /// Constructs the RandomSource system.
74  /// @param num_outputs The dimension of the (single) vector output port.
75  /// @param sampling_interval_sec The sampling interval in seconds.
76  RandomSource(int num_outputs, double sampling_interval_sec)
77  : seed_(generate_unique_seed()) {
78  this->DeclarePeriodicUnrestrictedUpdate(sampling_interval_sec, 0.);
79  this->DeclareVectorOutputPort(BasicVector<double>(num_outputs),
80  &RandomSource::CopyStateToOutput);
81  this->DeclareDiscreteState(num_outputs);
82  this->DeclareAbstractState(AbstractValue::Make(RandomState(seed_)));
83  }
84 
85  private:
86  // Computes a random number and stores it in the discrete state.
87  void DoCalcUnrestrictedUpdate(
88  const Context<double>&,
90  State<double>* state) const override {
91  auto& random_state =
92  state->template get_mutable_abstract_state<RandomState>(0);
93  auto& updates = state->get_mutable_discrete_state();
94  for (int i = 0; i < updates.size(); i++) {
95  updates[i] = random_state.GetNextValue();
96  }
97  }
98 
99  std::unique_ptr<AbstractValues> AllocateAbstractState() const override {
100  return std::make_unique<AbstractValues>(
102  }
103 
104  void SetDefaultState(const Context<double>& context,
105  State<double>* state) const override {
106  unused(context);
107  auto& random_state =
108  state->template get_mutable_abstract_state<RandomState>(0);
109  random_state = RandomState(seed_);
110  auto& values = state->get_mutable_discrete_state();
111  for (int i = 0; i < values.size(); i++) {
112  values[i] = random_state.GetNextValue();
113  }
114  }
115 
116  void SetRandomState(const Context<double>& context, State<double>* state,
117  RandomGenerator* generator) const override {
118  unused(context);
119  auto& random_state =
120  state->template get_mutable_abstract_state<RandomState>(0);
121  random_state = RandomState((*generator)());
122  auto& values = state->get_mutable_discrete_state();
123  for (int i = 0; i < values.size(); i++) {
124  values[i] = random_state.GetNextValue();
125  }
126  }
127 
128  // Output is the zero-order hold of the discrete state.
129  void CopyStateToOutput(const Context<double>& context,
130  BasicVector<double>* output) const {
131  output->SetFromVector(context.get_discrete_state(0).CopyToVector());
132  }
133 
134  const Seed seed_;
135 };
136 
137 } // namespace internal
138 
139 /// Generates uniformly distributed random numbers in the interval [0,1].
140 ///
141 /// @see internal::RandomSource
142 /// @ingroup primitive_systems
145 
146 /// Generates normally distributed random numbers with mean zero and unit
147 /// covariance.
148 ///
149 /// @see internal::RandomSource
150 /// @ingroup primitive_systems
153 
154 /// Generates exponentially distributed random numbers with mean, standard
155 /// deviation, and scale parameter (aka 1/λ) set to one.
156 ///
157 /// @see internal::RandomSource
158 /// @ingroup primitive_systems
161 
162 /// For each subsystem input port in @p builder that is (a) not yet connected
163 /// and (b) labeled as random in the InputPort, this method will add a
164 /// new RandomSource system of the appropriate type and connect it to the
165 /// subsystem input port.
166 ///
167 /// @param sampling_interval_sec interval to be used for all new sources.
168 /// @returns the total number of RandomSource systems added.
169 ///
170 /// @see @ref stochastic_systems
171 int AddRandomInputs(double sampling_interval_sec,
172  DiagramBuilder<double>* builder);
173 
174 } // namespace systems
175 } // namespace drake
RandomState(const RandomState &)=default
DiscreteValues< T > & get_mutable_discrete_state()
Definition: state.h:63
int i
Definition: reset_after_move_test.cc:51
Definition: automotive_demo.cc:90
std::mt19937 RandomGenerator
Defines the implementation of the stdc++ concept UniformRandomBitGenerator to be used by the Systems ...
Definition: system.h:72
A source block which generates random numbers at a fixed sampling interval, with a zero-order hold be...
Definition: random_source.h:66
double GetNextValue()
Generate the next random value with the given distribution.
Definition: random_source.h:32
This class represents an unrestricted update event.
Definition: event.h:482
internal::RandomSource< std::exponential_distribution< double > > ExponentialRandomSource
Generates exponentially distributed random numbers with mean, standard deviation, and scale parameter...
Definition: random_source.h:160
internal::RandomSource< std::uniform_real_distribution< double > > UniformRandomSource
Generates uniformly distributed random numbers in the interval [0,1].
Definition: random_source.h:144
std::vector< double > vector
Definition: translator_test.cc:20
void SetFromVector(const Eigen::Ref< const VectorX< T >> &value) override
Replaces the entire vector with the contents of value.
Definition: basic_vector.h:104
internal::RandomSource< std::normal_distribution< double > > GaussianRandomSource
Generates normally distributed random numbers with mean zero and unit covariance. ...
Definition: random_source.h:152
#define DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Classname)
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN defaults the special member functions for copy-construction, copy-assignment, move-construction, and move-assignment.
Definition: drake_copyable.h:57
State for a given random distribution and generator.
Definition: random_source.h:23
Generator::result_type Seed
Definition: random_source.h:27
A superclass template that extends System with some convenience utilities that are not applicable to ...
Definition: leaf_system.h:84
static std::unique_ptr< AbstractValue > Make(const T &value)
Returns an AbstractValue containing the given value.
Definition: value.h:201
const DiscreteValues< T > & get_discrete_state() const
Returns a reference to the entire discrete state, which may consist of multiple discrete state vector...
Definition: context.h:145
int AddRandomInputs(double sampling_interval_sec, DiagramBuilder< double > *builder)
For each subsystem input port in builder that is (a) not yet connected and (b) labeled as random in t...
Definition: random_source.cc:20
#define DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Classname)
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN deletes the special member functions for copy-construction, copy-assignment, move-construction, and move-assignment.
Definition: drake_copyable.h:33
RandomState::Seed Seed
Definition: random_source.h:71
void unused(const Args &...)
Documents the argument(s) as unused, placating GCC&#39;s -Wunused-parameter warning.
Definition: unused.h:51
Provides careful macros to selectively enable or disable the special member functions for copy-constr...
Generator::result_type generate_unique_seed()
Definition: random_source.cc:10