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 
7 #include "drake/common/drake_copyable.h"
8 #include "drake/common/unused.h"
9 #include "drake/systems/framework/diagram_builder.h"
10 #include "drake/systems/framework/leaf_system.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:
25  typedef typename Generator::result_type Seed;
26  static constexpr Seed default_seed = Generator::default_seed;
27 
28  explicit RandomState(Seed seed) : generator_(seed) {}
29 
30  /// Generate the next random value with the given distribution.
31  double GetNextValue() { return distribution_(generator_); }
32 
33  private:
34  // TODO(russt): Obtain consistent results across multiple platforms (#4361).
35  Generator generator_;
36  Distribution distribution_;
37 };
38 
39 /// A source block which generates random numbers at a fixed sampling interval,
40 /// with a zero-order hold between samples. For continuous-time systems, this
41 /// can be interpreted as a band-limited approximation of continuous white noise
42 /// (with a power-spectral density of the form Ts * sinc^2( omega * Ts ), where
43 /// Ts is the sampling interval.
44 ///
45 /// @tparam Distribution A class modeling the c++ RandomNumberDistribution
46 /// concept.
47 /// http://en.cppreference.com/w/cpp/concept/RandomNumberDistribution
48 ///
49 /// @note User code should not instantiate this class directly, but
50 /// should use systems::UniformRandomSource, systems::GaussianRandomSource, and
51 /// systems::ExponentialRandomSource systems instead.
52 ///
53 /// @note This system is only defined for the double scalar type.
54 ///
55 /// @note The hard-coding of (default) distribution parameters is imposed
56 /// intentionally to simplify analysis (by forcing systems taking noise inputs
57 /// to implement the shifting/scaling, the system itself contains all of the
58 /// necessary information for stochastic analysis).
59 ///
60 /// @see @ref stochastic_systems, UniformRandomSource, GaussianRandomSource,
61 /// ExponentialRandomSource.
62 ///
63 /// @ingroup primitive_systems
64 template <typename Distribution, typename Generator = std::mt19937>
65 class RandomSource : public LeafSystem<double> {
66  public:
68 
69  typedef internal::RandomState<Distribution, Generator> RandomState;
70  typedef typename RandomState::Seed Seed;
71 
72  /// Constructs the RandomSource system.
73  /// @param num_outputs The dimension of the (single) vector output port.
74  /// @param sampling_interval_sec The sampling interval in seconds.
75  RandomSource(int num_outputs, double sampling_interval_sec)
76  : seed_(generate_unique_seed()) {
77  this->DeclarePeriodicUnrestrictedUpdate(sampling_interval_sec, 0.);
78  this->DeclareVectorOutputPort(BasicVector<double>(num_outputs),
79  &RandomSource::CopyStateToOutput);
80  this->DeclareDiscreteState(num_outputs);
81  this->DeclareAbstractState(AbstractValue::Make(RandomState(seed_)));
82  }
83 
84  /// Initializes the random number generator. This must be set before
85  /// the (abstract) state is allocated to take effect.
86  void set_random_seed(Seed seed) { seed_ = seed; }
87 
88  private:
89  // Computes a random number and stores it in the discrete state.
90  void DoCalcUnrestrictedUpdate(
91  const Context<double>&,
93  State<double>* state) const override {
94  auto& random_state =
95  state->template get_mutable_abstract_state<RandomState>(0);
96  auto& updates = state->get_mutable_discrete_state();
97  const int N = updates.size();
98  for (int i = 0; i < N; i++) {
99  updates[i] = random_state.GetNextValue();
100  }
101  }
102 
103  std::unique_ptr<AbstractValues> AllocateAbstractState() const override {
104  return std::make_unique<AbstractValues>(
106  }
107 
108  // Output is the zero-order hold of the discrete state.
109  void CopyStateToOutput(const Context<double>& context,
110  BasicVector<double>* output) const {
111  output->SetFromVector(context.get_discrete_state(0).CopyToVector());
112  }
113 
115 };
116 
117 } // namespace internal
118 
119 /// Generates uniformly distributed random numbers in the interval [0,1].
120 ///
121 /// @see internal::RandomSource
122 /// @ingroup primitive_systems
125 
126 /// Generates normally distributed random numbers with mean zero and unit
127 /// covariance.
128 ///
129 /// @see internal::RandomSource
130 /// @ingroup primitive_systems
133 
134 /// Generates exponentially distributed random numbers with mean, standard
135 /// deviation, and scale parameter (aka 1/λ) set to one.
136 ///
137 /// @see internal::RandomSource
138 /// @ingroup primitive_systems
141 
142 /// For each subsystem input port in @p builder that is (a) not yet connected
143 /// and (b) labeled as random in the InputPortDescriptor, this method will add a
144 /// new RandomSource system of the appropriate type and connect it to the
145 /// subsystem input port.
146 ///
147 /// @param sampling_interval_sec interval to be used for all new sources.
148 /// @returns the total number of RandomSource systems added.
149 ///
150 /// @see @ref stochastic_systems
151 int AddRandomInputs(double sampling_interval_sec,
152  DiagramBuilder<double>* builder);
153 
154 } // namespace systems
155 } // namespace drake
DiscreteValues< T > & get_mutable_discrete_state()
Definition: state.h:63
int i
Definition: reset_after_move_test.cc:51
Definition: agent_trajectory.cc:3
A source block which generates random numbers at a fixed sampling interval, with a zero-order hold be...
Definition: random_source.h:65
double GetNextValue()
Generate the next random value with the given distribution.
Definition: random_source.h:31
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:140
internal::RandomSource< std::uniform_real_distribution< double > > UniformRandomSource
Generates uniformly distributed random numbers in the interval [0,1].
Definition: random_source.h:124
std::vector< double > vector
Definition: translator_test.cc:20
void set_random_seed(Seed seed)
Initializes the random number generator.
Definition: random_source.h:86
int size() const
Returns the number of elements in the only DiscreteValues group.
Definition: discrete_values.h:86
void SetFromVector(const Eigen::Ref< const VectorX< T >> &value) override
Replaces the entire vector with the contents of value.
Definition: basic_vector.h:97
internal::RandomSource< std::normal_distribution< double > > GaussianRandomSource
Generates normally distributed random numbers with mean zero and unit covariance. ...
Definition: random_source.h:132
State for a given random distribution and generator.
Definition: random_source.h:23
Generator::result_type Seed
Definition: random_source.h:25
A superclass template that extends System with some convenience utilities that are not applicable to ...
Definition: leaf_system.h:82
RandomState(Seed seed)
Definition: random_source.h:28
static std::unique_ptr< AbstractValue > Make(const T &value)
Returns an AbstractValue containing the given value.
Definition: value.h:193
static constexpr Seed default_seed
Definition: random_source.h:26
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:153
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:70
Generator::result_type generate_unique_seed()
Definition: random_source.cc:10