repo_id
stringclasses
205 values
file_path
stringlengths
33
141
content
stringlengths
1
307k
__index_level_0__
int64
0
0
/home/johnshepherd/drake/systems/analysis/test_utilities
/home/johnshepherd/drake/systems/analysis/test_utilities/test/spring_mass_system_test.cc
#include "drake/systems/analysis/test_utilities/spring_mass_system.h" #include <memory> #include <Eigen/Dense> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/systems/framework/fixed_input_port_value.h" #include "drake/systems/framework/state.h" #include "drake/systems/framework/subvector.h" #include "drake/systems/framework/system.h" #include "drake/systems/framework/system_output.h" #include "drake/systems/framework/test_utilities/scalar_conversion.h" #include "drake/systems/framework/vector_base.h" using std::make_unique; using std::unique_ptr; namespace drake { namespace systems { namespace { const double kSpring = 300.0; // N/m const double kMass = 2.0; // kg class SpringMassSystemTest : public ::testing::Test { public: void SetUp() override { Initialize(); } void Initialize(bool with_input_force = false) { // Construct the system I/O objects. system_ = std::make_unique<SpringMassSystem<double>>(kSpring, kMass, with_input_force); system_->set_name("test_system"); context_ = system_->CreateDefaultContext(); system_output_ = system_->AllocateOutput(); system_derivatives_ = system_->AllocateTimeDerivatives(); const int nq = system_derivatives_->get_generalized_position().size(); configuration_derivatives_ = std::make_unique<BasicVector<double>>(nq); // Set up some convenience pointers. state_ = dynamic_cast<SpringMassStateVector<double>*>( &context_->get_mutable_continuous_state_vector()); output_ = dynamic_cast<const SpringMassStateVector<double>*>( system_output_->get_vector_data(0)); derivatives_ = dynamic_cast<SpringMassStateVector<double>*>( &system_derivatives_->get_mutable_vector()); } void InitializeState(const double position, const double velocity) { state_->set_position(position); state_->set_velocity(velocity); state_->set_conservative_work(0); } protected: std::unique_ptr<SpringMassSystem<double>> system_; std::unique_ptr<Context<double>> context_; std::unique_ptr<SystemOutput<double>> system_output_; std::unique_ptr<ContinuousState<double>> system_derivatives_; std::unique_ptr<BasicVector<double>> configuration_derivatives_; SpringMassStateVector<double>* state_; const SpringMassStateVector<double>* output_; SpringMassStateVector<double>* derivatives_; private: std::unique_ptr<VectorBase<double>> erased_derivatives_; }; TEST_F(SpringMassSystemTest, Construction) { // Asserts zero inputs for this case. EXPECT_EQ(0, context_->num_input_ports()); EXPECT_EQ("test_system", system_->get_name()); EXPECT_EQ(kSpring, system_->get_spring_constant()); EXPECT_EQ(kMass, system_->get_mass()); EXPECT_FALSE(system_->get_system_is_forced()); } TEST_F(SpringMassSystemTest, DirectFeedthrough) { EXPECT_FALSE(system_->HasAnyDirectFeedthrough()); } TEST_F(SpringMassSystemTest, CloneState) { InitializeState(1.0, 2.0); state_->set_conservative_work(3.0); std::unique_ptr<BasicVector<double>> clone = state_->Clone(); SpringMassStateVector<double>* typed_clone = dynamic_cast<SpringMassStateVector<double>*>(clone.get()); ASSERT_NE(nullptr, typed_clone); EXPECT_EQ(1.0, typed_clone->get_position()); EXPECT_EQ(2.0, typed_clone->get_velocity()); EXPECT_EQ(3.0, typed_clone->get_conservative_work()); } TEST_F(SpringMassSystemTest, CloneOutput) { InitializeState(1.0, 2.0); system_->CalcOutput(*context_, system_output_.get()); std::unique_ptr<BasicVector<double>> clone = output_->Clone(); SpringMassStateVector<double>* typed_clone = dynamic_cast<SpringMassStateVector<double>*>(clone.get()); ASSERT_NE(nullptr, typed_clone); EXPECT_EQ(1.0, typed_clone->get_position()); EXPECT_EQ(2.0, typed_clone->get_velocity()); } // Tests that state is passed through to the output. TEST_F(SpringMassSystemTest, Output) { // Displacement 100cm, vel 250cm/s (.25 is exact in binary). InitializeState(0.1, 0.25); system_->CalcOutput(*context_, system_output_.get()); ASSERT_EQ(1, system_output_->num_ports()); // Check the output through the application-specific interface. EXPECT_NEAR(0.1, output_->get_position(), 1e-14); EXPECT_EQ(0.25, output_->get_velocity()); // Check the output through the VectorBase API. ASSERT_EQ(3, output_->size()); EXPECT_NEAR(0.1, output_->get_value()[0], 1e-14); EXPECT_EQ(0.25, output_->get_value()[1]); } // Tests that second-order structure is exposed in the state. TEST_F(SpringMassSystemTest, SecondOrderStructure) { InitializeState(1.2, 3.4); // Displacement 1.2m, velocity 3.4m/sec. ContinuousState<double>& continuous_state = context_->get_mutable_continuous_state(); ASSERT_EQ(1, continuous_state.get_generalized_position().size()); ASSERT_EQ(1, continuous_state.get_generalized_velocity().size()); ASSERT_EQ(1, continuous_state.get_misc_continuous_state().size()); EXPECT_NEAR(1.2, continuous_state.get_generalized_position().GetAtIndex(0), 1e-8); EXPECT_NEAR(3.4, continuous_state.get_generalized_velocity().GetAtIndex(0), 1e-8); } // Tests that second-order structure can be processed in // MapVelocityToConfigurationDerivative. TEST_F(SpringMassSystemTest, MapVelocityToConfigurationDerivative) { InitializeState(1.2, 3.4); // Displacement 1.2m, velocity 3.4m/sec. ContinuousState<double>& continuous_state = context_->get_mutable_continuous_state(); // Slice just the configuration derivatives out of the derivative // vector. Subvector<double> configuration_derivatives(derivatives_, 0, 1); system_->MapVelocityToQDot( *context_, continuous_state.get_generalized_velocity(), &configuration_derivatives); EXPECT_NEAR(3.4, derivatives_->get_position(), 1e-8); EXPECT_NEAR(3.4, configuration_derivatives.GetAtIndex(0), 1e-8); } TEST_F(SpringMassSystemTest, ForcesPositiveDisplacement) { InitializeState(0.1, 0.1); // Displacement 0.1m, velocity 0.1m/sec. system_->CalcTimeDerivatives(*context_, system_derivatives_.get()); ASSERT_EQ(3, derivatives_->size()); // The derivative of position is velocity. EXPECT_NEAR(0.1, derivatives_->get_position(), 1e-8); // The derivative of velocity is force over mass. EXPECT_NEAR(-kSpring * 0.1 / kMass, derivatives_->get_velocity(), 1e-8); } TEST_F(SpringMassSystemTest, ForcesNegativeDisplacement) { InitializeState(-0.1, 0.2); // Displacement -0.1m, velocity 0.2m/sec. system_->CalcTimeDerivatives(*context_, system_derivatives_.get()); ASSERT_EQ(3, derivatives_->size()); // The derivative of position is velocity. EXPECT_NEAR(0.2, derivatives_->get_position(), 1e-8); // The derivative of velocity is force over mass. EXPECT_NEAR(-kSpring * -0.1 / kMass, derivatives_->get_velocity(), 1e-8); } TEST_F(SpringMassSystemTest, DynamicsWithExternalForce) { // Initializes a spring mass system with an input port for an external force. Initialize(true); EXPECT_TRUE(system_->get_system_is_forced()); EXPECT_FALSE(system_->HasAnyDirectFeedthrough()); // Asserts exactly one input for this case expecting an external force. ASSERT_EQ(1, context_->num_input_ports()); // Sets the input force. const double kExternalForce = 1.0; // Creates a free standing input port not actually connected to the output of // another system but that has its own data. // This is done in order to be able to test this system standalone. system_->get_input_port(0).FixValue(context_.get(), kExternalForce); InitializeState(0.1, 0.1); // Displacement 0.1m, velocity 0.1m/sec. system_->CalcTimeDerivatives(*context_, system_derivatives_.get()); ASSERT_EQ(3, derivatives_->size()); // The derivative of position is velocity. EXPECT_NEAR(0.1, derivatives_->get_position(), Eigen::NumTraits<double>::epsilon()); // The derivative of velocity is force over mass. EXPECT_NEAR((-kSpring * 0.1 + kExternalForce) / kMass, derivatives_->get_velocity(), Eigen::NumTraits<double>::epsilon()); } TEST_F(SpringMassSystemTest, ForceEnergyAndPower) { InitializeState(1, 2); const double m = system_->get_mass(); const double k = system_->get_spring_constant(); const double q0 = 0; // TODO(david-german-tri) should be a parameter. const double q = system_->get_position(*context_); const double v = system_->get_velocity(*context_); const double w_c = system_->get_conservative_work(*context_); const double f = system_->EvalSpringForce(*context_); const double pe = system_->CalcPotentialEnergy(*context_); const double ke = system_->CalcKineticEnergy(*context_); const double power_c = system_->CalcConservativePower(*context_); const double power_nc = system_->CalcNonConservativePower(*context_); EXPECT_EQ(q, 1.0); EXPECT_EQ(v, 2.0); EXPECT_EQ(w_c, 0.0); EXPECT_NEAR(f, -k * (q - q0), 1e-14); EXPECT_NEAR(pe, k * (q - q0) * (q - q0) / 2, 1e-14); EXPECT_NEAR(ke, m * v * v / 2, 1e-14); EXPECT_NEAR(power_c, f * v, 1e-14); EXPECT_EQ(power_nc, 0.0); } // These are helper functions for the Integrate test below. /* Given a System and a Context, calculate the partial derivative matrix D xdot / D x. Here x has only continuous variables; in general we would have x=[xc,xd] in which case we'd be working with xc here. TODO(sherm1) This matrix should be calculated by templatizing the spring-mass System by AutoDiffScalar and by std::complex (for complex step derivatives). The numerical routine here should then be used in a separate test to make sure the autodifferentiated matrices agree with the numerical one. Also, consider switching to central differences here to get more decimal places. */ MatrixX<double> CalcDxdotDx(const System<double>& system, const Context<double>& context) { const double perturb = 1e-7; // roughly sqrt(precision) auto derivs0 = system.AllocateTimeDerivatives(); system.CalcTimeDerivatives(context, derivs0.get()); const int nx = derivs0->size(); const VectorX<double> xdot0 = derivs0->CopyToVector(); MatrixX<double> d_xdot_dx(nx, nx); auto temp_context = context.Clone(); auto& x = temp_context->get_mutable_continuous_state_vector(); // This is a temp that holds one column of the result as a ContinuousState. auto derivs = system.AllocateTimeDerivatives(); for (int i = 0; i < x.size(); ++i) { const double xi = x.GetAtIndex(i); x.SetAtIndex(i, xi + perturb); system.CalcTimeDerivatives(*temp_context, derivs.get()); d_xdot_dx.col(i) = (derivs->CopyToVector() - xdot0) / perturb; x.SetAtIndex(i, xi); // repair Context } return d_xdot_dx; } /* Explicit Euler (unstable): x1 = x0 + h xdot(t0,x0) */ void StepExplicitEuler( double h, const ContinuousState<double>& derivs, // TODO(#2274) Fix NOLINTNEXTLINE(runtime/references). Context<double>& context) { const double t = context.get_time(); // Invalidate all xc-dependent quantities. VectorBase<double>& xc = context.get_mutable_continuous_state_vector(); const auto& dxc = derivs.get_vector(); xc.PlusEqScaled(h, dxc); // xc += h*dxc context.SetTime(t + h); } /* Semi-explicit Euler (neutrally stable): z1 = z0 + h zdot(t0,x0) v1 = v0 + h vdot(t0,x0) q1 = q0 + h qdot(q0,v1) */ void StepSemiExplicitEuler( double h, const System<double>& system, // TODO(#2274) Fix NOLINTNEXTLINE(runtime/references). ContinuousState<double>& derivs, // in/out // TODO(#2274) Fix NOLINTNEXTLINE(runtime/references). Context<double>& context) { const double t = context.get_time(); ContinuousState<double>& xc = context.get_mutable_continuous_state(); // Invalidate z-dependent quantities. VectorBase<double>& xz = xc.get_mutable_misc_continuous_state(); const auto& dxz = derivs.get_misc_continuous_state(); xz.PlusEqScaled(h, dxz); // xz += h*dxz // Invalidate v-dependent quantities. VectorBase<double>& xv = xc.get_mutable_generalized_velocity(); const auto& dxv = derivs.get_generalized_velocity(); xv.PlusEqScaled(h, dxv); // xv += h*dxv context.SetTime(t + h); // Invalidate q-dependent quantities. VectorBase<double>& xq = xc.get_mutable_generalized_position(); auto& dxq = derivs.get_mutable_generalized_position(); system.MapVelocityToQDot(context, xv, &dxq); // qdot = N(q)*v xq.PlusEqScaled(h, dxq); // xq += h*qdot } /* Implicit Euler (unconditionally stable): x1 = x0 + h xdot(t1,x1) Define err(x) = x - (x0 + h xdot(t1,x)) J(x) = D err / D x = 1 - h D xdot / D x Guess: x1 = x0 + h xdot(t0,x0) do: Solve J(x1) dx = err(x1) x1 = x1 - dx while (norm(dx)/norm(x0) > tol) */ void StepImplicitEuler( double h, const System<double>& system, // TODO(#2274) Fix NOLINTNEXTLINE(runtime/references). ContinuousState<double>& derivs, // in/out // TODO(#2274) Fix NOLINTNEXTLINE(runtime/references). Context<double>& context) { const double t = context.get_time(); ContinuousState<double>& xc = context.get_mutable_continuous_state(); // Invalidate all xc-dependent quantities. VectorBase<double>& x1 = xc.get_mutable_vector(); const auto vx0 = x1.CopyToVector(); const auto& dx0 = derivs.get_vector(); x1.PlusEqScaled(h, dx0); // x1 += h*dx0 (initial guess) context.SetTime(t + h); // t=t1 const int nx = static_cast<int>(vx0.size()); const auto I = MatrixX<double>::Identity(nx, nx); // Would normally iterate until convergence of dx norm as shown above. // Here I'm just iterating a fixed number of time that I know is plenty! for (int i = 0; i < 6; ++i) { system.CalcTimeDerivatives(context, &derivs); const auto& dx1 = derivs.get_vector(); const auto vx1 = x1.CopyToVector(); const auto vdx1 = dx1.CopyToVector(); const auto err = vx1 - (vx0 + h * vdx1); const auto DxdotDx = CalcDxdotDx(system, context); const auto J = I - h * DxdotDx; Eigen::PartialPivLU<MatrixX<double>> Jlu(J); VectorX<double> dx = Jlu.solve(err); x1.SetFromVector(vx1 - dx); } } /* Calculate the total energy for this system in the given Context. TODO(sherm1): assuming there is only KE and PE to worry about. */ double CalcEnergy(const SpringMassSystem<double>& system, const Context<double>& context) { return system.CalcPotentialEnergy(context) + system.CalcKineticEnergy(context); } /* This test simulates the spring-mass system simultaneously using three first- order integrators with different stability properties. The system itself is conservative since it contains no actuation or damping. All numerical integrators are approximate, but differing stability properties cause predictably different effects on total system energy: - Explicit Euler: energy should increase - Implicit Euler: energy should decrease - Semi-explicit Euler: energy should remain constant The test evaluates the initial energy and then makes sure it goes in the expected direction for each integration method. The primary goal of this test is to exercise the System 2.0 API by using it for solvers that have different API demands. */ TEST_F(SpringMassSystemTest, Integrate) { const double h = 0.001, kTfinal = 9, kNumIntegrators = 3; // Resource indices for each of the three integrators. enum { kXe = 0, kIe = 1, kSxe = 2 }; std::vector<unique_ptr<Context<double>>> contexts; std::vector<unique_ptr<SystemOutput<double>>> outputs; std::vector<unique_ptr<ContinuousState<double>>> derivs; // Allocate resources. for (int i = 0; i < kNumIntegrators; ++i) { contexts.push_back(system_->CreateDefaultContext()); outputs.push_back(system_->AllocateOutput()); derivs.push_back(system_->AllocateTimeDerivatives()); } // Set initial conditions in each Context. for (auto& context : contexts) { context->SetTime(0); system_->set_position(context.get(), 0.1); // Displacement 0.1m, vel. 0m/s. system_->set_velocity(context.get(), 0.); } // Save the initial energy (same in all contexts). const double initial_energy = CalcEnergy(*system_, *contexts[0]); while (true) { const auto t = contexts[0]->get_time(); /* Evaluate derivatives at the beginning of a step, then generate Outputs (which may depend on derivatives). Uncomment five lines below if you want to get output you can plot. TODO(david-german-tri,sherm1) Should have a way to run similar code in both regression test form and as friendlier examples. */ for (int i = 0; i < kNumIntegrators; ++i) { system_->CalcTimeDerivatives(*contexts[i], derivs[i].get()); system_->CalcOutput(*contexts[i], outputs[i].get()); } // Semi-explicit Euler should keep energy roughly constant every step. EXPECT_NEAR(CalcEnergy(*system_, *contexts[kSxe]), initial_energy, 1e-2); if (t >= kTfinal) break; // Integrate three ways. StepExplicitEuler(h, *derivs[kXe], *contexts[kXe]); StepImplicitEuler(h, *system_, *derivs[kIe], *contexts[kIe]); StepSemiExplicitEuler(h, *system_, *derivs[kSxe], *contexts[kSxe]); } // Now verify that each integrator behaved as expected. EXPECT_GT(CalcEnergy(*system_, *contexts[kXe]), 2 * initial_energy); EXPECT_LT(CalcEnergy(*system_, *contexts[kIe]), initial_energy / 2); EXPECT_NEAR(CalcEnergy(*system_, *contexts[kSxe]), initial_energy, 1e-2); } /* Test that EvalConservativePower() correctly measures the transfer of power from potential energy to kinetic energy. We have to integrate the power to calculate the net work W(t) done by the spring on the mass. If we set W(0)=0, then it should always hold that PE(t) + KE(t) = PE(0) + KE(0) KE(t) = KE(0) + W(t) PE(t) = PE(0) - W(t) This will only be true if the system is integrated with no energy gains or losses from the numerical method, because those are not conservative changes. The semi-explicit Euler method we used above is the only method we can use for this test (unless we run with very small time steps). */ TEST_F(SpringMassSystemTest, IntegrateConservativePower) { const double h = 0.00001, kTfinal = 5; // Resources. unique_ptr<Context<double>> context = system_->CreateDefaultContext(); unique_ptr<ContinuousState<double>> derivs = system_->AllocateTimeDerivatives(); // Set initial conditions.. context->SetTime(0); system_->set_position(context.get(), 0.1); // Displacement 0.1m, vel. 0m/s. system_->set_velocity(context.get(), 0.); system_->set_conservative_work(context.get(), 0.); // W(0)=0 // Save the initial energy. const double pe0 = system_->CalcPotentialEnergy(*context); const double ke0 = system_->CalcKineticEnergy(*context); const double e0 = pe0 + ke0; while (true) { const auto t = context->get_time(); // Evaluate derivatives at the beginning of a step. We don't need outputs. system_->CalcTimeDerivatives(*context, derivs.get()); if (t >= kTfinal) break; const double pe = system_->CalcPotentialEnergy(*context); const double ke = system_->CalcKineticEnergy(*context); const double e = pe + ke; EXPECT_NEAR(e, e0, 1e-3); // Due to a quirk of semi-explicit Euler, this integral was evaluated // using the previous step's q's rather than the ones current now so // there is a larger discrepancy than would be expected from accuracy // alone. const double w = system_->get_conservative_work(*context); EXPECT_NEAR(ke, ke0 + w, 1e-2); EXPECT_NEAR(pe, pe0 - w, 1e-2); // Take a step of size h. StepSemiExplicitEuler(h, *system_, *derivs, *context); } } TEST_F(SpringMassSystemTest, ToAutoDiff) { EXPECT_TRUE(is_autodiffxd_convertible(*system_)); } TEST_F(SpringMassSystemTest, ToSymbolic) { EXPECT_TRUE(is_symbolic_convertible(*system_)); } } // namespace } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/simulator_status_test.cc
#include "drake/systems/analysis/simulator_status.h" #include <gtest/gtest.h> namespace drake { namespace systems { namespace { GTEST_TEST(SimulatorStatusTest, ConstructionAndRetrieval) { const SystemBase* dummy = reinterpret_cast<const SystemBase*>(0x1234); SimulatorStatus status(1.25); // Always constructed with a boundary_time. // Default is that the status reached the boundary time. EXPECT_EQ(status.boundary_time(), 1.25); EXPECT_EQ(status.return_time(), status.boundary_time()); EXPECT_EQ(status.reason(), SimulatorStatus::kReachedBoundaryTime); EXPECT_EQ(status.system(), nullptr); EXPECT_EQ(status.message(), std::string()); status.SetReachedTermination(1., dummy, "Hello there"); EXPECT_EQ(status.boundary_time(), 1.25); EXPECT_EQ(status.return_time(), 1.); EXPECT_EQ(status.reason(), SimulatorStatus::kReachedTerminationCondition); EXPECT_EQ(status.system(), dummy); EXPECT_EQ(status.message(), std::string("Hello there")); } GTEST_TEST(SimulatorStatusTest, CopyConstruction) { const SystemBase* dummy = reinterpret_cast<const SystemBase*>(0x1234); SimulatorStatus status(1.0); status.SetEventHandlerFailed(0.5, dummy, "test message"); SimulatorStatus copy_status(status); EXPECT_TRUE(copy_status.IsIdenticalStatus(status)); } } // namespace } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/simulator_limit_malloc_test.cc
#include <gtest/gtest.h> #include "drake/common/test_utilities/limit_malloc.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/framework/event.h" #include "drake/systems/framework/leaf_system.h" namespace drake { namespace systems { namespace { class EventfulSystem final : public LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(EventfulSystem) EventfulSystem() { // These events were found to cause allocations at AdvanceTo() as // originally implemented. DeclarePeriodicPublishEvent(1.0, 0.5, &EventfulSystem::Update); DeclarePeriodicDiscreteUpdateEvent(1.0, 0.5, &EventfulSystem::Update); DeclarePeriodicUnrestrictedUpdateEvent(1.0, 0.5, &EventfulSystem::Update); DeclarePerStepPublishEvent(&EventfulSystem::Update); DeclarePerStepDiscreteUpdateEvent(&EventfulSystem::Update); DeclarePerStepUnrestrictedUpdateEvent(&EventfulSystem::Update); // These events were not found to allocate at AdvanceTo(); they are // included for completeness. DeclareForcedPublishEvent(&EventfulSystem::Update); DeclareForcedDiscreteUpdateEvent(&EventfulSystem::Update); DeclareForcedUnrestrictedUpdateEvent(&EventfulSystem::Update); // It turns out that declaring an init event can actually *reduce* the // allocation count, by forcing earlier allocations in underlying storage // objects. See #14543 for discussion of this problem. // TODO(rpoyner-tri): expand testing to cover this problem. DeclareInitializationPublishEvent(&EventfulSystem::Update); DeclareInitializationDiscreteUpdateEvent(&EventfulSystem::Update); DeclareInitializationUnrestrictedUpdateEvent(&EventfulSystem::Update); } private: EventStatus Update(const Context<double>&) const { return EventStatus::Succeeded(); } EventStatus Update(const Context<double>&, DiscreteValues<double>*) const { return EventStatus::Succeeded(); } EventStatus Update(const Context<double>&, State<double>*) const { return EventStatus::Succeeded(); } }; // Tests that heap allocations do not occur from Simulator and the systems // framework for systems that do various event updates and do not have // continuous state. // TODO(rpoyner-tri): add testing for witness functions. GTEST_TEST(SimulatorLimitMallocTest, NoHeapAllocsInSimulatorForSystemsWithoutContinuousState) { // Build a Diagram containing the test system so we can test both Diagrams // and LeafSystems at once. DiagramBuilder<double> builder; builder.AddSystem<EventfulSystem>(); auto diagram = builder.Build(); // Create a Simulator and use it to advance time until t=3. Simulator<double> simulator(*diagram); // Actually cause forced-publish events to be issued. simulator.set_publish_every_time_step(true); // Trigger first (and only allowable) heap allocation. simulator.Initialize(); { // As long as there are any allocations allowed here, there are still // defects to fix. The exact number doesn't much matter; it should be set // to the minimum possible at any given revision, to catch regressions. The // goal (see #14543) is for the simulator and framework to support // heap-free simulation after initialization, given careful system // construction. test::LimitMalloc heap_alloc_checker({.max_num_allocations = 0}); simulator.AdvanceTo(1.0); simulator.AdvanceTo(2.0); simulator.AdvanceTo(3.0); simulator.AdvancePendingEvents(); } } } // namespace } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/simulator_config_functions_test.cc
#include "drake/systems/analysis/simulator_config_functions.h" #include <gtest/gtest.h> #include "drake/common/nice_type_name.h" #include "drake/common/test_utilities/expect_no_throw.h" #include "drake/common/yaml/yaml_io.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/leaf_system.h" #include "drake/systems/primitives/constant_vector_source.h" using drake::yaml::LoadYamlString; using drake::yaml::SaveYamlString; namespace drake { namespace systems { namespace { template <typename T> class SimulatorConfigFunctionsTest : public ::testing::Test {}; using MyTypes = ::testing::Types<double, AutoDiffXd>; TYPED_TEST_SUITE(SimulatorConfigFunctionsTest, MyTypes); TYPED_TEST(SimulatorConfigFunctionsTest, ResetIntegratorTest) { using T = TypeParam; ConstantVectorSource<T> source(2); Simulator<T> simulator(source); const void* prior_integrator = &simulator.get_integrator(); IntegratorBase<T>& result = ResetIntegratorFromFlags(&simulator, "runge_kutta2", T(0.001)); EXPECT_NE(&simulator.get_integrator(), prior_integrator); EXPECT_EQ(&simulator.get_integrator(), &result); const std::string result_name_expected = fmt::format( "drake::systems::RungeKutta2Integrator<{}>", NiceTypeName::Get<T>()); EXPECT_EQ(NiceTypeName::Get(result), result_name_expected); } TYPED_TEST(SimulatorConfigFunctionsTest, GetSchemes) { using T = TypeParam; const std::vector<std::string>& schemes = GetIntegrationSchemes(); EXPECT_GE(schemes.size(), 5); // Check that all of the schemes are actually valid. ConstantVectorSource<T> source(2); Simulator<T> simulator(source); for (const auto& one_scheme : schemes) { DRAKE_EXPECT_NO_THROW( ResetIntegratorFromFlags(&simulator, one_scheme, T(0.001))); } } template <typename T> class DummySystem final : public drake::systems::LeafSystem<T> { public: DummySystem() {} }; TYPED_TEST(SimulatorConfigFunctionsTest, CongruenceTest) { // Ensure that a default constructed SimulatorConfig has the same values as a // default constructed Simulator. // N.B. Due to the RoundTripTest, we know that ExtractSimulatorConfig is doing // actual work, not just returning a default constructed SimulatorConfig. using T = TypeParam; const DummySystem<T> dummy; Simulator<T> simulator(dummy); const SimulatorConfig config_defaults; const SimulatorConfig sim_defaults = ExtractSimulatorConfig(simulator); EXPECT_EQ(sim_defaults.integration_scheme, config_defaults.integration_scheme); EXPECT_EQ(sim_defaults.max_step_size, config_defaults.max_step_size); EXPECT_EQ(sim_defaults.accuracy, config_defaults.accuracy); EXPECT_EQ(sim_defaults.use_error_control, config_defaults.use_error_control); EXPECT_EQ(sim_defaults.target_realtime_rate, config_defaults.target_realtime_rate); EXPECT_EQ(sim_defaults.publish_every_time_step, config_defaults.publish_every_time_step); } TYPED_TEST(SimulatorConfigFunctionsTest, RoundTripTest) { using T = TypeParam; const std::string bespoke_str = "integration_scheme: runge_kutta5\n" "max_step_size: 0.003\n" "accuracy: 0.03\n" "use_error_control: true\n" "target_realtime_rate: 3.0\n" "publish_every_time_step: true\n"; // Ensure that the string and the struct have the same fields. const auto bespoke = LoadYamlString<SimulatorConfig>(bespoke_str); // Ensure that a round trip through the archive process does not corrupt data. const std::string readback_str = SaveYamlString(bespoke); EXPECT_EQ(bespoke_str, readback_str); // Ensure that a roundtrip through the Accept and Extract functions does not // corrupt data. const DummySystem<T> dummy; Simulator<T> simulator(dummy); ApplySimulatorConfig(bespoke, &simulator); const SimulatorConfig readback = ExtractSimulatorConfig(simulator); EXPECT_EQ(readback.integration_scheme, bespoke.integration_scheme); EXPECT_EQ(readback.max_step_size, bespoke.max_step_size); EXPECT_EQ(readback.accuracy, bespoke.accuracy); EXPECT_EQ(readback.use_error_control, bespoke.use_error_control); EXPECT_EQ(readback.target_realtime_rate, bespoke.target_realtime_rate); EXPECT_EQ(readback.publish_every_time_step, bespoke.publish_every_time_step); } } // namespace } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/simulator_gflags_main.cc
#include <gflags/gflags.h> #include "drake/common/yaml/yaml_io.h" #include "drake/systems/analysis/simulator_config_functions.h" #include "drake/systems/analysis/simulator_gflags.h" #include "drake/systems/primitives/constant_vector_source.h" namespace drake { namespace systems { template <typename T> void ResetIntegratorFromGflagsTest() { ConstantVectorSource<T> source(2); auto simulator = internal::MakeSimulatorFromGflags(source); internal::ResetIntegratorFromGflags(simulator.get()); const auto simulator_config = ExtractSimulatorConfig(*simulator); drake::log()->info(drake::yaml::SaveYamlString(simulator_config)); } } // namespace systems } // namespace drake int main(int argc, char* argv[]) { gflags::SetUsageMessage("A stub main() program to test simulator_gflags.h"); gflags::ParseCommandLineFlags(&argc, &argv, true); drake::systems::ResetIntegratorFromGflagsTest<double>(); drake::systems::ResetIntegratorFromGflagsTest<drake::AutoDiffXd>(); }
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/radau_integrator_test.cc
#include "drake/systems/analysis/radau_integrator.h" #include <vector> #include <gtest/gtest.h> #include "drake/systems/analysis/implicit_euler_integrator.h" #include "drake/systems/analysis/test_utilities/cubic_scalar_system.h" #include "drake/systems/analysis/test_utilities/implicit_integrator_test.h" #include "drake/systems/analysis/test_utilities/linear_scalar_system.h" #include "drake/systems/analysis/test_utilities/quadratic_scalar_system.h" namespace drake { namespace systems { namespace analysis_test { // Tests accuracy for integrating a scalar cubic system (with the state at time // t corresponding to f(t) ≡ C₃t³ + C₂t² + C₁t + C₀) over // t ∈ [0, 1]. Radau3 is a third order integrator, meaning that it uses the // Taylor Series expansion: // f(t+h) ≈ f(t) + hf'(t) + ½h²f''(t) + ⅙h³f'''(t) + O(h⁴) // The formula above indicates that the approximation error will be zero if // f''''(t) = 0, which is true for the cubic equation. We also test that the // single-stage Radau integrator (i.e., implicit Euler integrator) fails to // integrate this function using a single step. GTEST_TEST(RadauIntegratorTest, CubicSystem) { CubicScalarSystem cubic; std::unique_ptr<Context<double>> context = cubic.CreateDefaultContext(); // Create the integrator using two stages. RadauIntegrator<double, 2> radau3(cubic, context.get()); const double h = 1.0; radau3.set_maximum_step_size(h); radau3.set_fixed_step_mode(true); // Integrate the system radau3.Initialize(); ASSERT_TRUE(radau3.IntegrateWithSingleFixedStepToTime(h)); // Verify the solution. VectorX<double> state = context->get_continuous_state().get_vector().CopyToVector(); EXPECT_NEAR(state[0], cubic.Evaluate(h), std::numeric_limits<double>::epsilon()); // Reset the state. context = cubic.CreateDefaultContext(); // Create an implicit Euler integrator using 1 stage and running in fixed step // mode. const int num_stages = 1; RadauIntegrator<double, num_stages> euler(cubic, context.get()); euler.set_fixed_step_mode(true); euler.set_maximum_step_size(h); // Integrate the system euler.Initialize(); ASSERT_TRUE(euler.IntegrateWithSingleFixedStepToTime(h)); // Verify the integrator failed to produce the solution. state = context->get_continuous_state().get_vector().CopyToVector(); EXPECT_GT(std::abs(state[0] - cubic.Evaluate(h)), 1e9 * std::numeric_limits<double>::epsilon()); } // Tests accuracy for integrating the quadratic system (with the state at time t // corresponding to f(t) ≡ C₂t² + C₁t + C₀, where C₀ is the initial state) over // t ∈ [0, 1]. The error estimate from 2-stage Radau is third-order accurate, // meaning that the approximation error will be zero if f'''(t) = 0, which is // true for the quadratic equation. We check that the error estimate is zero // for this function. // Note: this test differs from [Velocity]ImplicitEulerIntegratorTest:: // QuadraticSystemErrorEstimatorAccuracy in that the error estimation for the // two-stage Radau integrator is third-order accurate, so this test checks to // make sure the error estimate (and error) are zero, while both the implicit // Euler and the velocity-implicit Euler integrators have a second-order- // accurate error estimate, so their tests check to make sure the error // estimate is exact (not necessarily zero). GTEST_TEST(RadauIntegratorTest, QuadraticTest) { QuadraticScalarSystem quadratic; auto quadratic_context = quadratic.CreateDefaultContext(); const double C0 = quadratic.Evaluate(0); quadratic_context->SetTime(0.0); quadratic_context->get_mutable_continuous_state_vector()[0] = C0; // Create the integrator. const int num_stages = 2; RadauIntegrator<double, num_stages> radau(quadratic, quadratic_context.get()); // Ensure that the Radau3 integrator supports error estimation. EXPECT_TRUE(radau.supports_error_estimation()); const double t_final = 1.0; radau.set_maximum_step_size(t_final); radau.set_fixed_step_mode(true); radau.Initialize(); ASSERT_TRUE(radau.IntegrateWithSingleFixedStepToTime(t_final)); // Ensure that Radau, and not BS3, was used by counting the number of // function evaluations. Note that this number is somewhat brittle and might // need to be revised in the future. EXPECT_EQ(radau.get_num_derivative_evaluations(), 8); // Per the description in IntegratorBase::get_error_estimate_order(), this // should return "3", in accordance with the order of the polynomial in the // Big-Oh term; for the single-stage Radau integrator, this value will be // different. ASSERT_EQ(radau.get_error_estimate_order(), 3); const double err_est = radau.get_error_estimate()->get_vector().GetAtIndex(0); // Note the very tight tolerance used, which will likely not hold for // arbitrary values of C0, t_final, or polynomial coefficients. EXPECT_NEAR(err_est, 0.0, 2 * std::numeric_limits<double>::epsilon()); // Verify the solution too. EXPECT_NEAR( quadratic_context->get_continuous_state().get_vector().CopyToVector()[0], quadratic.Evaluate(t_final), std::numeric_limits<double>::epsilon()); // Repeat this test, but using a final time that is below the working minimum // step size (thereby triggering the implicit integrator's alternate, explicit // mode). To retain our existing tolerances, we change the scale factor (S) // for the quadratic system. radau.get_mutable_context()->SetTime(0); const double working_min = radau.get_working_minimum_step_size(); QuadraticScalarSystem scaled_quadratic(4.0/working_min); auto scaled_quadratic_context = scaled_quadratic.CreateDefaultContext(); RadauIntegrator<double> scaled_radau( scaled_quadratic, scaled_quadratic_context.get()); const double updated_t_final = working_min / 2; scaled_radau.set_maximum_step_size(updated_t_final); scaled_radau.set_fixed_step_mode(true); scaled_radau.Initialize(); ASSERT_TRUE(scaled_radau.IntegrateWithSingleFixedStepToTime(updated_t_final)); // Ensure that BS3, and not Radau, was used by counting the number of // function evaluations. EXPECT_EQ(scaled_radau.get_num_derivative_evaluations(), 4); const double updated_err_est = scaled_radau.get_error_estimate()->get_vector()[0]; // Note the very tight tolerance used, which will likely not hold for // arbitrary values of C0, t_final, or polynomial coefficients. EXPECT_NEAR(updated_err_est, 0.0, 2 * std::numeric_limits<double>::epsilon()); // Verify the solution too. EXPECT_NEAR( scaled_quadratic_context->get_continuous_state().get_vector(). CopyToVector()[0], scaled_quadratic.Evaluate(updated_t_final), 10 * std::numeric_limits<double>::epsilon()); } // Tests that Radau1 can successfully integrate the linear system (with the // state at time t corresponding to f(t) ≡ C₁t + C₀, where C₀ is the initial // state) over t ∈ [0, 1], without falling back to Euler+RK2. In // ImplicitIntegratorTest::LinearTest, we also test the accuracy of Radau1 and // Radau3 while integrating the same system. GTEST_TEST(RadauIntegratorTest, LinearRadauTest) { LinearScalarSystem linear; auto linear_context = linear.CreateDefaultContext(); const double C0 = linear.Evaluate(0); linear_context->SetTime(0.0); linear_context->get_mutable_continuous_state_vector()[0] = C0; // Create the integrator. const int num_stages = 1; RadauIntegrator<double, num_stages> radau(linear, linear_context.get()); const double t_final = 1.0; radau.set_maximum_step_size(t_final); radau.set_fixed_step_mode(true); radau.Initialize(); ASSERT_TRUE(radau.IntegrateWithSingleFixedStepToTime(t_final)); // Ensure that Radau, and not Euler+RK2, was used by counting the number of // function evaluations. Note that this number is somewhat brittle and might // need to be revised in the future. EXPECT_EQ(radau.get_num_derivative_evaluations(), 6); // Per the description in IntegratorBase::get_error_estimate_order(), this // should return "2", in accordance with the order of the polynomial in the // Big-Oh term; for the two-stage Radau integrator, this value will be // different. ASSERT_EQ(radau.get_error_estimate_order(), 2); } // Integrate the modified mass-spring-damping system, which exhibits a // discontinuity in the velocity derivative at spring position x = 0, and // compares the results at the final state between implicit Euler and Radau-1. GTEST_TEST(RadauIntegratorTest, Radau1MatchesImplicitEuler) { std::unique_ptr<Context<double>> context_; // The mass of the particle connected by the spring and damper to the world. const double mass = 2.0; // The magnitude of the constant force pushing the particle toward -inf. const double constant_force_mag = 10; // Spring constant for a semi-stiff spring. Corresponds to a frequency of // 35.588 cycles per second without damping, assuming that mass = 2 (using // formula f = sqrt(k/mass)/(2*pi), where k is the spring constant, and f is // the frequency in cycles per second). const double semistiff_spring_k = 1e5; // Construct the discontinuous mass-spring-damper system, using critical // damping. implicit_integrator_test::DiscontinuousSpringMassDamperSystem<double> spring_damper(semistiff_spring_k, std::sqrt(semistiff_spring_k / mass), mass, constant_force_mag); // Create two contexts, one for each integrator. auto context_radau1 = spring_damper.CreateDefaultContext(); auto context_ie = spring_damper.CreateDefaultContext(); // Construct the two integrators. const int num_stages = 1; // Yields implicit Euler. RadauIntegrator<double, num_stages> radau1(spring_damper, context_radau1.get()); ImplicitEulerIntegrator<double> ie(spring_damper, context_ie.get()); // Tell IE to use implicit trapezoid for error estimation to match // Radau1. ie.set_use_implicit_trapezoid_error_estimation(true); // Ensure that both integrators support error estimation. EXPECT_TRUE(radau1.supports_error_estimation()); EXPECT_TRUE(ie.supports_error_estimation()); // Set maximum step sizes that are reasonable for this system. radau1.set_maximum_step_size(1e-2); ie.set_maximum_step_size(1e-2); // Set the same target accuracy for both integrators. radau1.set_target_accuracy(1e-5); ie.set_target_accuracy(1e-5); // Make both integrators re-use Jacobians and iteration matrices, when // possible. radau1.set_reuse(true); ie.set_reuse(true); // Setting the minimum step size speeds the unit test without (in this case) // affecting solution accuracy. radau1.set_requested_minimum_step_size(1e-8); ie.set_requested_minimum_step_size(1e-8); // Set initial position. const double initial_position = 1e-8; spring_damper.set_position(context_radau1.get(), initial_position); spring_damper.set_position(context_ie.get(), initial_position); // Set the initial velocity. const double initial_velocity = 0; spring_damper.set_velocity(context_radau1.get(), initial_velocity); spring_damper.set_velocity(context_ie.get(), initial_velocity); // Initialize both integrators. radau1.Initialize(); ie.Initialize(); // Integrate for 1 second. const double t_final = 1.0; radau1.IntegrateWithMultipleStepsToTime(t_final); ie.IntegrateWithMultipleStepsToTime(t_final); // NOTE: A preliminary investigation indicates that these are not bitwise // identical due to different ordering of arithmetic operations. // Verify the final position and accuracy are identical to machine precision. const double tol = std::numeric_limits<double>::epsilon(); EXPECT_NEAR(context_radau1->get_continuous_state().get_vector().GetAtIndex(0), context_ie->get_continuous_state().get_vector().GetAtIndex(0), tol); EXPECT_NEAR(context_radau1->get_continuous_state().get_vector().GetAtIndex(1), context_ie->get_continuous_state().get_vector().GetAtIndex(1), tol); // NOTE: The preliminary investigation cited above indicates that the // different order of arithmetic operations is responsible for a slight // discrepancy in number of derivative evaluations and Newton-Raphson // iterations, so we don't verify that these stats are identical. // Verify that the remaining statistics are identical. EXPECT_EQ(radau1.get_largest_step_size_taken(), ie.get_largest_step_size_taken()); EXPECT_EQ(radau1.get_num_derivative_evaluations_for_jacobian(), ie.get_num_derivative_evaluations_for_jacobian()); EXPECT_EQ(radau1.get_num_error_estimator_derivative_evaluations(), ie.get_num_error_estimator_derivative_evaluations()); EXPECT_EQ( radau1.get_num_error_estimator_derivative_evaluations_for_jacobian(), ie.get_num_error_estimator_derivative_evaluations_for_jacobian()); EXPECT_EQ(radau1.get_num_error_estimator_iteration_matrix_factorizations(), ie.get_num_error_estimator_iteration_matrix_factorizations()); EXPECT_EQ(radau1.get_num_error_estimator_jacobian_evaluations(), ie.get_num_error_estimator_jacobian_evaluations()); EXPECT_EQ(radau1.get_num_error_estimator_newton_raphson_iterations(), ie.get_num_error_estimator_newton_raphson_iterations()); EXPECT_EQ(radau1.get_num_iteration_matrix_factorizations(), ie.get_num_iteration_matrix_factorizations()); EXPECT_EQ(radau1.get_num_jacobian_evaluations(), ie.get_num_jacobian_evaluations()); EXPECT_EQ(radau1.get_num_step_shrinkages_from_error_control(), ie.get_num_step_shrinkages_from_error_control()); EXPECT_EQ(radau1.get_num_step_shrinkages_from_substep_failures(), ie.get_num_step_shrinkages_from_substep_failures()); EXPECT_EQ(radau1.get_num_steps_taken(), ie.get_num_steps_taken()); EXPECT_EQ(radau1.get_num_substep_failures(), ie.get_num_substep_failures()); // Verify that we've had at least one step shrinkage. EXPECT_GT(radau1.get_num_step_shrinkages_from_substep_failures(), 0); } // Test both 1-stage (1st order) and 2-stage (3rd order) Radau integrators. typedef ::testing::Types<RadauIntegrator<double, 1>, RadauIntegrator<double, 2>> MyTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, ImplicitIntegratorTest, MyTypes); } // namespace analysis_test } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/initial_value_problem_test.cc
#include "drake/systems/analysis/initial_value_problem.h" #include <algorithm> #include <gtest/gtest.h> #include "drake/common/fmt_eigen.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/systems/analysis/integrator_base.h" #include "drake/systems/analysis/runge_kutta2_integrator.h" #include "drake/systems/framework/basic_vector.h" #include "drake/systems/framework/parameters.h" namespace drake { namespace systems { namespace analysis { namespace { // Checks IVP solver usage with multiple integrators. GTEST_TEST(InitialValueProblemTest, SolutionUsingMultipleIntegrators) { // Accuracy upper bound, as not all the integrators used below support // error control. const double kAccuracy = 1e-2; // The initial time t₀, for IVP definition. const double kInitialTime = 0.0; // The initial state 𝐱₀, for IVP definition. const VectorX<double> kInitialState = VectorX<double>::Zero(2); // The default parameters 𝐤₀, for IVP definition. const VectorX<double> kParameters = VectorX<double>::Constant(2, 1.0); // Instantiates a generic IVP for test purposes only, // using a generic ODE d𝐱/dt = -𝐱 + 𝐤, that does not // model (nor attempts to model) any physical process. InitialValueProblem<double> ivp( [](const double& t, const VectorX<double>& x, const VectorX<double>& k) -> VectorX<double> { unused(t); return -x + k; }, kInitialState, kParameters); // Testing against closed form solution of above's IVP, which can be written // as 𝐱(t; 𝐤) = 𝐤 + (𝐱₀ - 𝐤) * e^(-(t - t₀)). const double t0 = kInitialTime; const VectorX<double>& x0 = kInitialState; const VectorX<double>& k1 = kParameters; const double t1 = kInitialTime + 1.0; EXPECT_TRUE(CompareMatrices( ivp.Solve(t0, t1), k1 + (x0 - k1) * std::exp(-(t1 - t0)), kAccuracy)); // Replaces default integrator. const double kMaximumStep = 0.1; const IntegratorBase<double>& default_integrator = ivp.get_integrator(); IntegratorBase<double>* configured_integrator = ivp.reset_integrator<RungeKutta2Integrator<double>>(kMaximumStep); EXPECT_NE(configured_integrator, &default_integrator); EXPECT_EQ(configured_integrator, &ivp.get_integrator()); const double t2 = kInitialTime + 0.3; // Testing against closed form solution of above's IVP, which can be written // as 𝐱(t; 𝐤) = 𝐤 + (𝐱₀ - 𝐤) * e^(-(t - t₀)). EXPECT_TRUE(CompareMatrices( ivp.Solve(t0, t2), k1 + (x0 - k1) * std::exp(-(t2 - t0)), kAccuracy)); } // Parameterized fixture for testing accuracy of IVP solutions. class InitialValueProblemAccuracyTest : public ::testing::TestWithParam<double> { protected: void SetUp() { integration_accuracy_ = GetParam(); } // Expected accuracy for numerical integral // evaluation in the relative tolerance sense. double integration_accuracy_{0.}; }; // Accuracy test of the solution for the momentum 𝐩 of a particle // with mass m travelling through a gas with dynamic viscosity μ, // where d𝐩/dt = -μ * 𝐩/m and 𝐩(t₀; [m, μ]) = 𝐩₀. TEST_P(InitialValueProblemAccuracyTest, ParticleInAGasMomentum) { // The initial time t₀. const double kInitialTime = 0.0; // The initial momentum 𝐩₀ of the particle at time t₀. const VectorX<double> kInitialParticleMomentum = ( VectorX<double>(3) << -3.0, 1.0, 2.0).finished(); const double kLowestGasViscosity = 1.0; const double kHighestGasViscosity = 10.0; const double kGasViscosityStep = 1.0; const double kLowestParticleMass = 1.0; const double kHighestParticleMass = 10.0; const double kParticleMassStep = 1.0; const double kTotalTime = 1.0; const double kTimeStep = 0.1; const double t0 = kInitialTime; const double tf = kTotalTime; const VectorX<double>& p0 = kInitialParticleMomentum; for (double mu = kLowestGasViscosity; mu <= kHighestGasViscosity; mu += kGasViscosityStep) { for (double m = kLowestParticleMass; m <= kHighestParticleMass; m += kParticleMassStep) { const Eigen::Vector2d parameters{mu, m}; // Instantiates the particle momentum IVP. InitialValueProblem<double> particle_momentum_ivp( [](const double& t, const VectorX<double>& p, const VectorX<double>& k) -> VectorX<double> { const double mu_ = k[0]; const double m_ = k[1]; return -mu_ * p / m_; }, kInitialParticleMomentum, parameters); IntegratorBase<double>& inner_integrator = particle_momentum_ivp.get_mutable_integrator(); inner_integrator.set_target_accuracy(integration_accuracy_); const std::unique_ptr<DenseOutput<double>> particle_momentum_approx = particle_momentum_ivp.DenseSolve(t0, tf); for (double t = kInitialTime; t <= kTotalTime; t += kTimeStep) { // Tests are performed against the closed form // solution for the IVP described above, which is // 𝐩(t; [μ, m]) = 𝐩₀ * e^(-μ * (t - t₀) / m). const VectorX<double> solution = p0 * std::exp(-mu * (t - t0) / m); EXPECT_TRUE(CompareMatrices(particle_momentum_ivp.Solve(t0, t), solution, integration_accuracy_)) << fmt::format( "Failure solving d𝐩/dt = -μ * 𝐩/m using 𝐩({}; [μ, m]) = {}" " for t = {}, μ = {} and m = {} to an accuracy of {}", t0, fmt_eigen(p0), t, mu, m, integration_accuracy_); EXPECT_TRUE(CompareMatrices(particle_momentum_approx->Evaluate(t), solution, integration_accuracy_)) << fmt::format( "Failure approximating the solution for d𝐩/dt = -μ * 𝐩/m" " using 𝐩({}; [μ, m]) = {} for t = {}, μ = {} and m = {}" " to an accuracy of {} with solver's continuous extension.", t0, fmt_eigen(p0), t, mu, m, integration_accuracy_); } } } } // Accuracy test of the solution for the velocity 𝐯 of a particle // with mass m travelling through a gas with dynamic viscosity μ // and being pushed by a constant force 𝐅, where // d𝐯/dt = (𝐅 - μ * 𝐯) / m and 𝐯(t₀; [m, μ]) = 𝐯₀. TEST_P(InitialValueProblemAccuracyTest, ParticleInAGasForcedVelocity) { // The initial time t₀. const double kInitialTime = 0.0; // The initial velocity 𝐯₀ of the particle at time t₀. const VectorX<double> kInitialParticleVelocity = VectorX<double>::Unit(3, 0); // The force 𝐅 pushing the particle. const VectorX<double> kPushingForce = VectorX<double>::Unit(3, 1); // The mass m of the particle and the dynamic viscosity μ of the gas. const double kLowestGasViscosity = 1.0; const double kHighestGasViscosity = 10.0; const double kGasViscosityStep = 1.0; const double kLowestParticleMass = 1.0; const double kHighestParticleMass = 10.0; const double kParticleMassStep = 1.0; const double kTotalTime = 1.0; const double kTimeStep = 0.1; const double t0 = kInitialTime; const double tf = kTotalTime; const VectorX<double>& F = kPushingForce; const VectorX<double>& v0 = kInitialParticleVelocity; for (double mu = kLowestGasViscosity; mu <= kHighestGasViscosity; mu += kGasViscosityStep) { for (double m = kLowestParticleMass; m <= kHighestParticleMass; m += kParticleMassStep) { const Eigen::Vector2d parameters{mu, m}; // Instantiates the particle velocity IVP. InitialValueProblem<double> particle_velocity_ivp( [&kPushingForce](const double& t, const VectorX<double>& v, const VectorX<double>& k) -> VectorX<double> { const double mu_ = k[0]; const double m_ = k[1]; const VectorX<double>& F_ = kPushingForce; return (F_ - mu_ * v) / m_; }, kInitialParticleVelocity, parameters); IntegratorBase<double>& inner_integrator = particle_velocity_ivp.get_mutable_integrator(); inner_integrator.set_target_accuracy(integration_accuracy_); const std::unique_ptr<DenseOutput<double>> particle_velocity_approx = particle_velocity_ivp.DenseSolve(t0, tf); for (double t = kInitialTime; t <= kTotalTime; t += kTimeStep) { // Tests are performed against the closed form // solution for the IVP described above, which is // 𝐯(t; [μ, m]) = 𝐯₀ * e^(-μ * (t - t₀) / m) + // 𝐅 / μ * (1 - e^(-μ * (t - t₀) / m)) // with 𝐅 = (0., 1., 0.). const VectorX<double> solution = v0 * std::exp(-mu * (t - t0) / m) + F / mu * (1. - std::exp(-mu * (t - t0) / m)); EXPECT_TRUE(CompareMatrices(particle_velocity_ivp.Solve(t0, t), solution, integration_accuracy_)) << fmt::format( "Failure solving" " d𝐯/dt = (-μ * 𝐯 + 𝐅) / m using 𝐯({}; [μ, m]) = {}" " for t = {}, μ = {}, m = {} and 𝐅 = {}" " to an accuracy of {}", t0, fmt_eigen(v0), t, mu, m, fmt_eigen(F), integration_accuracy_); EXPECT_TRUE(CompareMatrices(particle_velocity_approx->Evaluate(t), solution, integration_accuracy_)) << fmt::format( "Failure approximating the solution for" " d𝐯/dt = (-μ * 𝐯 + 𝐅) / m using 𝐯({}; [μ, m]) = {}" " for t = {}, μ = {}, m = {} and 𝐅 = {}" " to an accuracy of {} with solver's continuous extension.", t0, fmt_eigen(v0), t, mu, m, fmt_eigen(F), integration_accuracy_); } } } } INSTANTIATE_TEST_SUITE_P(IncreasingAccuracyInitialValueProblemTests, InitialValueProblemAccuracyTest, ::testing::Values(1e-1, 1e-2, 1e-3, 1e-4, 1e-5)); } // namespace } // namespace analysis } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/velocity_implicit_euler_integrator_test.cc
#include "drake/systems/analysis/velocity_implicit_euler_integrator.h" #include <gtest/gtest.h> #include "drake/systems/analysis/test_utilities/implicit_integrator_test.h" #include "drake/systems/analysis/test_utilities/quadratic_scalar_system.h" namespace drake { namespace systems { namespace analysis_test { // Tests accuracy for integrating the quadratic system (with the state at time t // corresponding to f(t) ≡ 7t² + 7t + f₀, where f₀ is the initial state) over // t ∈ [0, 1]. Since the error estimate has a Taylor series that is // accurate to O(h²) and since we have no terms beyond this order, // halving the step size should improve the error estimate by a factor of 4. // Furthermore, we test that the error estimate gives the exact error, with // both the correct sign and magnitude. // Note: this test differs from RadauIntegratorTest::QuadraticTest in that // the error estimation for the two-stage Radau integrator is third-order // accurate, so that test checks to make sure the error estimate (and error) // are zero, while this integrator has a second-order-accurate error estimate, // so this test checks to make sure the error estimate is exact (not necessarily // zero). GTEST_TEST(VelocityImplicitEulerIntegratorTest, QuadraticSystemErrorEstimatorAccuracy) { QuadraticScalarSystem quadratic(7); auto quadratic_context = quadratic.CreateDefaultContext(); const double C = quadratic.Evaluate(0); quadratic_context->SetTime(0.0); quadratic_context->get_mutable_continuous_state_vector()[0] = C; VelocityImplicitEulerIntegrator<double> vie(quadratic, quadratic_context.get()); // Ensure that the velocity-implicit Euler integrator supports error // estimation. ASSERT_TRUE(vie.supports_error_estimation()); // Per the description in IntegratorBase::get_error_estimate_order(), this // should return "2", in accordance with the order of the polynomial in the // Big-O term. ASSERT_EQ(vie.get_error_estimate_order(), 2); const double t_final = 1.5; vie.set_maximum_step_size(t_final); vie.set_fixed_step_mode(true); vie.Initialize(); ASSERT_TRUE(vie.IntegrateWithSingleFixedStepToTime(t_final)); const double err_est_h = vie.get_error_estimate()->get_vector().GetAtIndex(0); const double expected_answer = quadratic.Evaluate(t_final); const double actual_answer = quadratic_context->get_continuous_state_vector()[0]; // Verify that the error estimate gets the exact error value. Note the tight // tolerance used. EXPECT_NEAR(err_est_h, actual_answer - expected_answer, 10 * std::numeric_limits<double>::epsilon()); // Now obtain the error estimate corresponding to two half-sized "steps" of // size h/2, to verify the error estimate order. To clarify, this means that // the velocity-implicit Euler integrator would take four small steps and two // large steps here. quadratic_context->SetTime(0.0); quadratic_context->get_mutable_continuous_state_vector()[0] = C; vie.Initialize(); ASSERT_TRUE(vie.IntegrateWithSingleFixedStepToTime(t_final / 2)); ASSERT_TRUE(vie.IntegrateWithSingleFixedStepToTime(t_final)); const double err_est_2h_2 = vie.get_error_estimate()->get_vector().GetAtIndex(0); // Since the error estimate is second order, the estimate from half-steps // should be a quarter the size for a quadratic system. EXPECT_NEAR(err_est_2h_2, 1.0 / 4 * err_est_h, 10 * std::numeric_limits<double>::epsilon()); // Verify the validity of general statistics. ImplicitIntegratorTest< VelocityImplicitEulerIntegrator<double>>::CheckGeneralStatsValidity(&vie); } // Test Velocity-Implicit Euler integrator on common implicit tests. typedef ::testing::Types<VelocityImplicitEulerIntegrator<double>> MyTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, ImplicitIntegratorTest, MyTypes); } // namespace analysis_test } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/simulator_test.cc
#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 // evenly so we should get some step size modification here. GTEST_TEST(SimulatorTest, SpringMass) { const double kSpring = 300.0; // N/m const double kMass = 2.0; // kg // Set the integrator default step size. const double h = 1e-3; // Create the mass spring system and the simulator. analysis_test::MySpringMassSystem<double> spring_mass(kSpring, kMass, 30.); 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 and initialize it. auto& integrator = simulator.reset_integrator<ExplicitEulerIntegrator<double>>(h); integrator.Initialize(); // Set the integrator and initialize the simulator. simulator.Initialize(); // Simulate to one second. simulator.AdvanceTo(1.); EXPECT_GT(simulator.get_num_steps_taken(), 1000); EXPECT_EQ(simulator.get_num_discrete_updates(), 30); // We're calling Publish() every step, and extra steps have to be taken // since the step size doesn't divide evenly into the sample rate. Shouldn't // require more than one extra step per sample though. EXPECT_LE(spring_mass.get_publish_count(), 1030); EXPECT_EQ(spring_mass.get_update_count(), 30); } // This is the example from discrete_systems.h. Let's make sure it works // as advertised there! The discrete system is: // x_{n+1} = x_n + 1 // y_n = 10 x_n // x_0 = 0 // which should produce 0 10 20 30 ... . // // Don't change this unit test without making a corresponding change to the // doxygen example in the systems/discrete_systems.h module. This class should // be as identical to the code there as possible; ideally, just a // copy-and-paste. class ExampleDiscreteSystem : public LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ExampleDiscreteSystem) ExampleDiscreteSystem() { DeclareDiscreteState(1); // Just one state variable, x[0], default=0. // Update to x_{n+1} using a Drake "discrete update" event (occurs // at the beginning of step n+1). DeclarePeriodicDiscreteUpdateEvent(kPeriod, kOffset, &ExampleDiscreteSystem::Update); // Present y_n (=S_n) at the output port. DeclareVectorOutputPort("Sn", 1, &ExampleDiscreteSystem::Output); } static constexpr double kPeriod = 1 / 50.; // Update at 50Hz (h=1/50). static constexpr double kOffset = 0.; // Trigger events at n=0. private: void Update(const systems::Context<double>& context, systems::DiscreteValues<double>* xd) const { const double x_n = context.get_discrete_state()[0]; (*xd)[0] = x_n + 1.; } void Output(const systems::Context<double>& context, systems::BasicVector<double>* result) const { const double x_n = context.get_discrete_state()[0]; const double S_n = 10 * x_n; (*result)[0] = S_n; } }; // Tests the code fragment shown in the systems/discrete_systems.h module. Make // this as copypasta-identical as possible to the code there, and make matching // changes there if you change anything here. GTEST_TEST(SimulatorTest, ExampleDiscreteSystem) { // Build a Diagram containing the Example system and a data logger that // samples the Sn output port exactly at the update times. DiagramBuilder<double> builder; auto example = builder.AddSystem<ExampleDiscreteSystem>(); auto logger = LogVectorOutput(example->GetOutputPort("Sn"), &builder, ExampleDiscreteSystem::kPeriod); auto diagram = builder.Build(); // Create a Simulator and use it to advance time until t=3*h. Simulator<double> simulator(*diagram); simulator.AdvanceTo(3 * ExampleDiscreteSystem::kPeriod); testing::internal::CaptureStdout(); // Not in example. // Print out the contents of the log. const auto& log = logger->FindLog(simulator.get_context()); for (int n = 0; n < log.sample_times().size(); ++n) { const double t = log.sample_times()[n]; std::cout << n << ": " << log.data()(0, n) << " (" << t << ")\n"; } // Not in example (although the expected output is there). std::string output = testing::internal::GetCapturedStdout(); EXPECT_EQ(output, "0: 0 (0)\n" "1: 10 (0.02)\n" "2: 20 (0.04)\n" "3: 30 (0.06)\n"); } // A hybrid discrete-continuous system: // x_{n+1} = sin(1.234*t) // y_n = x_n // With proper initial conditions, this should produce a one-step-delayed // sample of the periodic function, so that y_n = sin(1.234 * (n-1)*h). class SinusoidalDelayHybridSystem : public LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SinusoidalDelayHybridSystem) SinusoidalDelayHybridSystem() { this->DeclarePeriodicDiscreteUpdateEvent( kUpdatePeriod, 0.0, &SinusoidalDelayHybridSystem::Update); this->DeclareDiscreteState(1 /* single state variable */); this->DeclareVectorOutputPort("y", 1, &SinusoidalDelayHybridSystem::CalcOutput); } static constexpr double kSinusoidalFrequency = 1.234; static constexpr double kUpdatePeriod = 0.25; private: void Update(const Context<double>& context, DiscreteValues<double>* x_next) const { const double t = context.get_time(); (*x_next)[0] = std::sin(kSinusoidalFrequency * t); } void CalcOutput(const Context<double>& context, BasicVector<double>* output) const { (*output)[0] = context.get_discrete_state()[0]; // y = x. } }; // Tests that sinusoidal hybrid system that is not periodic in the update period // produces the result from simulating the discrete system: // x_{n+1} = sin(f * n * h) // y_n = x_n // x_0 = sin(f * -1 * h) // where h is the update period and f is the frequency of the sinusoid. // This should be a one-step delayed discrete sampling of the sinusoid. GTEST_TEST(SimulatorTest, SinusoidalHybridSystem) { const double h = SinusoidalDelayHybridSystem::kUpdatePeriod; const double f = SinusoidalDelayHybridSystem::kSinusoidalFrequency; // Build the diagram. DiagramBuilder<double> builder; auto sinusoidal_system = builder.AddSystem<SinusoidalDelayHybridSystem>(); auto logger = builder.AddSystem<VectorLogSink<double>>(1 /* input size */, h); builder.Connect(*sinusoidal_system, *logger); auto diagram = builder.Build(); // Simulator. const double t_final = 10.0; const double initial_value = std::sin(-f * h); // = sin(f*-1*h) Simulator<double> simulator(*diagram); simulator.get_mutable_context().get_mutable_discrete_state()[0] = initial_value; simulator.AdvanceTo(t_final); // Set a very tight tolerance value. const double eps = 1e-14; // Get the output from the signal logger. It will look like this in the // signal logger: // // y value n corresponding time signal logger value (delayed) // ------- --- ------------------ ----------------------------- // y₀ 0 0 sin(-f h) // y₁ 1 t = h sin(0) // y₂ 2 t = 2 h sin(f h) // y₃ 3 t = 3 h sin(f 2 h) // ... const auto& log = logger->FindLog(simulator.get_context()); const VectorX<double> times = log.sample_times(); const MatrixX<double> data = log.data(); ASSERT_EQ(times.size(), std::round(t_final/h) + 1); ASSERT_EQ(data.rows(), 1); for (int n = 0; n < times.size(); ++n) { const double t_n = times[n]; const double y_n = data(0, n); EXPECT_NEAR(t_n, n * h, eps); EXPECT_NEAR(std::sin(f * (n - 1) * h), y_n, eps); } } // A continuous system that outputs unity plus time. class ShiftedTimeOutputter : public LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ShiftedTimeOutputter) ShiftedTimeOutputter() { this->DeclareVectorOutputPort("time", 1, &ShiftedTimeOutputter::OutputTime); } private: void OutputTime( const Context<double>& context, BasicVector<double>* output) const { (*output)[0] = context.get_time() + 1; } }; // A hybrid discrete-continuous system: // x_{n+1} = x_n + u(t) // x_0 = 0 class SimpleHybridSystem : public LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SimpleHybridSystem) explicit SimpleHybridSystem(double offset) { this->DeclarePeriodicDiscreteUpdateEvent(kPeriod, offset, &SimpleHybridSystem::Update); this->DeclareDiscreteState(1 /* single state variable */); this->DeclareVectorInputPort("u", 1); } private: void Update(const Context<double>& context, DiscreteValues<double>* x_next) const { const double u = this->get_input_port(0).Eval(context)[0]; // u(t) double x = context.get_discrete_state()[0]; // x_n (*x_next)[0] = x + u; } const double kPeriod = 1.0; }; // Tests the update sequence for a simple mixed discrete/continuous system // that uses the prescribed updating offset of 0.0. GTEST_TEST(SimulatorTest, SimpleHybridSystemTestOffsetZero) { DiagramBuilder<double> builder; // Connect a system that outputs u(t) = t to the hybrid system // x_{n+1} = x_n + u(t). auto shifted_time_outputter = builder.AddSystem<ShiftedTimeOutputter>(); const double updating_offset_time = 0.0; auto hybrid_system = builder.AddSystem<SimpleHybridSystem>( updating_offset_time); builder.Connect(*shifted_time_outputter, *hybrid_system); auto diagram = builder.Build(); Simulator<double> simulator(*diagram); // Set the initial condition x_0 (the subscript notation reflects the // discrete step number as described in discrete_systems.h). const double initial_condition = 0.0; simulator.get_mutable_context().get_mutable_discrete_state()[0] = initial_condition; // Simulate forward. The first update occurs at t=0, meaning AdvanceTo(1) // updates the discrete state to x⁺(0) (i.e., x_1) before updating time to 1. simulator.AdvanceTo(1.0); // Check that the expected state value was attained. The value should be // x_0 + u(0) since we expect the discrete update to occur at t = 0 when // u(t) = 1. const double u0 = 1; EXPECT_EQ(simulator.get_context().get_discrete_state()[0], initial_condition + u0); // Check that the expected number of updates (one) was performed. EXPECT_EQ(simulator.get_num_discrete_updates(), 1); } // A "Delta function" system that outputs zero except at the instant (the spike // time) when the output is 1. This function of time is continuous otherwise. // We'll verify that the output of this system into a discrete system produces // samples at the expected instant in time. class DeltaFunction : public LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DeltaFunction) explicit DeltaFunction(double spike_time) : spike_time_(spike_time) { this->DeclareVectorOutputPort("spike", 1, &DeltaFunction::Output); } // Change the spike time. Be sure to re-initialize after calling this. void set_spike_time(double spike_time) { spike_time_ = spike_time; } private: void Output( const Context<double>& context, BasicVector<double>* output) const { (*output)[0] = context.get_time() == spike_time_ ? 1. : 0.; } double spike_time_{}; }; // This is a mixed continuous/discrete system: // x_{n+1} = x_n + u(t) // y_n = x_n // x_0 = 0 // By plugging interesting things into the input we can test whether we're // sampling the continuous input at the appropriate times. class DiscreteInputAccumulator : public LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DiscreteInputAccumulator) DiscreteInputAccumulator() { DeclareDiscreteState(1); // Just one state variable, x[0]. DeclareVectorInputPort("u", 1); DeclareInitializationDiscreteUpdateEvent( &DiscreteInputAccumulator::OnInitializeUpdate); DeclarePeriodicPublishEvent( kPeriod, kPublishOffset, &DiscreteInputAccumulator::OnPeriodicPublish); DeclarePeriodicDiscreteUpdateEvent( kPeriod, kPublishOffset, &DiscreteInputAccumulator::OnPeriodicUpdate); } const std::vector<double>& result() const { return result_; } static constexpr double kPeriod = 0.125; static constexpr double kPublishOffset = 0.; private: // Sets initial condition x_0 = 0, and clears the result. EventStatus OnInitializeUpdate(const Context<double>&, DiscreteValues<double>* x_0) const { (*x_0)[0] = 0.0; result_.clear(); return EventStatus::Succeeded(); } // Outputs y_n using a Drake "publish" event (occurs at the end of step n). EventStatus OnPeriodicPublish(const Context<double>& context) const { result_.push_back(get_x(context)); // y_n = x_n return EventStatus::Succeeded(); } // Updates to x_{n+1} (x_np1), using a Drake "discrete update" event (occurs // at the beginning of step n+1). EventStatus OnPeriodicUpdate(const Context<double>& context, DiscreteValues<double>* x_np1) const { const double x_n = get_x(context); const double u = get_input_port(0).Eval(context)[0]; (*x_np1)[0] = x_n + u; // x_{n+1} = x_n + u(t) return EventStatus::Succeeded(); } double get_x(const Context<double>& context) const { return context.get_discrete_state()[0]; } mutable std::vector<double> result_; }; // Build a diagram that takes a DeltaFunction input and then simulates this // mixed discrete/continuous system: // x_{n+1} = x_n + u(t) // y_n = x_n // x_0 = 0 // Let t_s be the chosen "spike time" for the delta function. We expect the // output y_n to be zero for all n unless a sample at k*h occurs exactly at // tₛ for some k. In that case y_n=0, n ≤ k and y_n=1, n > k. Important cases // to check are: t_s=0, t_s=k*h for some k>0, and t_s≠k*h for any k. GTEST_TEST(SimulatorTest, SpikeTest) { DiagramBuilder<double> builder; auto delta = builder.AddSystem<DeltaFunction>(0.); auto hybrid_system = builder.AddSystem<DiscreteInputAccumulator>(); builder.Connect(delta->get_output_port(0), hybrid_system->get_input_port(0)); auto diagram = builder.Build(); Simulator<double> simulator(*diagram); // Test with spike time = 0. delta->set_spike_time(0); simulator.Initialize(); simulator.AdvanceTo(5 * DiscreteInputAccumulator::kPeriod); EXPECT_EQ(hybrid_system->result(), std::vector<double>({0, 1, 1, 1, 1, 1})); // Test with spike time = 3*h. delta->set_spike_time(3 * DiscreteInputAccumulator::kPeriod); simulator.get_mutable_context().SetTime(0.); simulator.Initialize(); simulator.AdvanceTo(5 * DiscreteInputAccumulator::kPeriod); EXPECT_EQ(hybrid_system->result(), std::vector<double>({0, 0, 0, 0, 1, 1})); // Test with spike time not coinciding with a sample time. delta->set_spike_time(2.7 * DiscreteInputAccumulator::kPeriod); simulator.get_mutable_context().SetTime(0.); simulator.Initialize(); simulator.AdvanceTo(5 * DiscreteInputAccumulator::kPeriod); EXPECT_EQ(hybrid_system->result(), std::vector<double>({0, 0, 0, 0, 0, 0})); } // A mock System that requests a single update at a prespecified time. class UnrestrictedUpdater : public LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(UnrestrictedUpdater) explicit UnrestrictedUpdater(double t_upd) : t_upd_(t_upd) {} ~UnrestrictedUpdater() override {} void DoCalcNextUpdateTime(const Context<double>& context, CompositeEventCollection<double>* event_info, double* time) const override { const double inf = std::numeric_limits<double>::infinity(); *time = (context.get_time() < t_upd_) ? t_upd_ : inf; if (unrestricted_update_callback_ != nullptr) { UnrestrictedUpdateEvent<double> event( TriggerType::kPeriodic, [callback = unrestricted_update_callback_]( const System<double>&, const Context<double>& event_context, const UnrestrictedUpdateEvent<double>&, State<double>* event_state) { callback(event_context, event_state); return EventStatus::Succeeded(); }); event.AddToComposite(event_info); } else { UnrestrictedUpdateEvent<double> event(TriggerType::kPeriodic); event.AddToComposite(event_info); } } void DoCalcTimeDerivatives( const Context<double>& context, ContinuousState<double>* derivatives) const override { if (derivatives_callback_ != nullptr) derivatives_callback_(context); } void set_unrestricted_update_callback( std::function<void(const Context<double>&, State<double>*)> callback) { unrestricted_update_callback_ = callback; } void set_derivatives_callback( std::function<void(const Context<double>&)> callback) { derivatives_callback_ = callback; } private: const double t_upd_{0.0}; std::function<void(const Context<double>&, State<double>*)> unrestricted_update_callback_{nullptr}; std::function<void(const Context<double>&)> derivatives_callback_{nullptr}; }; // Tests that the simulator captures an unrestricted update at the exact time // (i.e., without accumulating floating point error). GTEST_TEST(SimulatorTest, ExactUpdateTime) { // Create the UnrestrictedUpdater system. const double t_upd = 1e-10; // Inexact floating point rep. UnrestrictedUpdater unrest_upd(t_upd); Simulator<double> simulator(unrest_upd); // Use default Context. // Set time to an exact floating point representation; we want t_upd to // be much smaller in magnitude than the time, hence the negative time. simulator.get_mutable_context().SetTime(-1.0 / 1024); // Capture the time at which an update is done using a callback function. std::vector<double> updates; unrest_upd.set_unrestricted_update_callback( [&updates](const Context<double>& context, State<double>* state) { updates.push_back(context.get_time()); }); // Simulate forward. simulator.Initialize(); simulator.AdvanceTo(1.); // Check that the update occurs at exactly the desired time. EXPECT_EQ(updates.size(), 1u); EXPECT_EQ(updates.front(), t_upd); } // Tests Simulator for a Diagram system consisting of a tree of systems. // In this case the System is a PidControlledSpringMassSystem which is a // Diagram containing a SpringMassSystem (the plant) and a PidController which // in turn is a Diagram composed of primitives such as Gain and Adder systems. GTEST_TEST(SimulatorTest, ControlledSpringMass) { typedef complex<double> complexd; typedef AutoDiffScalar<Vector1d> SingleVarAutoDiff; // SpringMassSystem parameters. const double kSpring = 300.0; // N/m const double kMass = 2.0; // kg // System's open loop frequency. const double wol = std::sqrt(kSpring / kMass); // Initial conditions. const double x0 = 0.1; const double v0 = 0.0; // Choose some controller constants. const double kp = kSpring; const double ki = 0.0; // System's undamped frequency (when kd = 0). const double w0 = std::sqrt(wol * wol + kp / kMass); // Damping ratio (underdamped). const double zeta = 0.5; const double kd = 2.0 * kMass * w0 * zeta; const double x_target = 0.0; PidControlledSpringMassSystem<double> spring_mass(kSpring, kMass, kp, ki, kd, x_target); Simulator<double> simulator(spring_mass); // Use default Context. // Forces simulator to use fixed-step integration at 1ms (to keep assumptions // below accurate). simulator.get_mutable_integrator().set_fixed_step_mode(true); simulator.get_mutable_integrator().set_maximum_step_size(0.001); // Sets initial condition using the Simulator's internal Context. spring_mass.set_position(&simulator.get_mutable_context(), x0); spring_mass.set_velocity(&simulator.get_mutable_context(), v0); // Takes all the defaults for the simulator. simulator.Initialize(); // Computes analytical solution. // 1) Roots of the characteristic equation. complexd lambda1 = -zeta * w0 + w0 * std::sqrt(complexd(zeta * zeta - 1)); complexd lambda2 = -zeta * w0 - w0 * std::sqrt(complexd(zeta * zeta - 1)); // Roots should be the complex conjugate of each other. #ifdef __APPLE__ // The factor of 20 is needed for OS X builds where the comparison needs a // looser tolerance, see #3636. auto abs_error = 20.0 * NumTraits<double>::epsilon(); #else auto abs_error = NumTraits<double>::epsilon(); #endif EXPECT_NEAR(lambda1.real(), lambda2.real(), abs_error); EXPECT_NEAR(lambda1.imag(), -lambda2.imag(), abs_error); // The damped frequency corresponds to the absolute value of the imaginary // part of any of the roots. double wd = std::abs(lambda1.imag()); // 2) Differential equation's constants of integration. double C1 = x0; double C2 = (zeta * w0 * x0 + v0) / wd; // 3) Computes analytical solution at time final_time. // Velocity is computed using AutoDiffScalar. double final_time = 0.2; double x_final{}, v_final{}; { // At the end of this local scope x_final and v_final are properly // initialized. // Auxiliary AutoDiffScalar variables are confined to this local scope so // that we don't pollute the test's scope with them. SingleVarAutoDiff time(final_time); time.derivatives() << 1.0; auto x = exp(-zeta * w0 * time) * (C1 * cos(wd * time) + C2 * sin(wd * time)); x_final = x.value(); v_final = x.derivatives()[0]; } // Simulates to final_time. simulator.AdvanceTo(final_time); EXPECT_EQ(simulator.get_num_steps_taken(), 200); const auto& context = simulator.get_context(); EXPECT_NEAR(context.get_time(), final_time, 1e-8); // Compares with analytical solution (to numerical integration error). EXPECT_NEAR(spring_mass.get_position(context), x_final, 3.0e-6); EXPECT_NEAR(spring_mass.get_velocity(context), v_final, 1.0e-5); } // A mock hybrid continuous-discrete System with time as its only continuous // variable, discrete updates at 1 kHz, and requests publishes at 400 Hz. Calls // user-configured callbacks in the publish and discrete variable update event // handlers and in EvalTimeDerivatives. This hybrid system will be used to // verify expected state update ordering -- discrete, continuous (i.e., // integration), then publish. class MixedContinuousDiscreteSystem : public LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MixedContinuousDiscreteSystem) MixedContinuousDiscreteSystem() { // Deliberately choose a period that is identical to, and therefore courts // floating-point error with, the default max step size. const double offset = 0.0; DeclarePeriodicDiscreteUpdateEvent( kUpdatePeriod, offset, &MixedContinuousDiscreteSystem::HandleDiscreteVariableUpdates); DeclarePeriodicPublishEvent(kPublishPeriod, 0.0, &MixedContinuousDiscreteSystem::HandlePublish); // We need some continuous state (which will be unused) so that the // continuous state integration will not be bypassed. this->DeclareContinuousState(1); set_name("TestSystem"); } ~MixedContinuousDiscreteSystem() override {} void HandleDiscreteVariableUpdates(const Context<double>& context, DiscreteValues<double>*) const { if (update_callback_ != nullptr) update_callback_(context); } void HandlePublish(const Context<double>& context) const { if (publish_callback_ != nullptr) publish_callback_(context); } void DoCalcTimeDerivatives( const Context<double>& context, ContinuousState<double>* derivatives) const override { if (derivatives_callback_ != nullptr) derivatives_callback_(context); } void set_update_callback( std::function<void(const Context<double>&)> callback) { update_callback_ = callback; } void set_publish_callback( std::function<void(const Context<double>&)> callback) { publish_callback_ = callback; } void set_derivatives_callback( std::function<void(const Context<double>&)> callback) { derivatives_callback_ = callback; } double update_period() const { return kUpdatePeriod; } double publish_period() const { return kPublishPeriod; } private: const double kUpdatePeriod{0.001}; const double kPublishPeriod{0.0025}; std::function<void(const Context<double>&)> update_callback_{nullptr}; std::function<void(const Context<double>&)> publish_callback_{nullptr}; std::function<void(const Context<double>&)> derivatives_callback_{nullptr}; }; // Returns true if the time in the @p context is a multiple of the @p period. bool CheckSampleTime(const Context<double>& context, double period) { const double k = context.get_time() / period; const double int_k = std::round(k); const double kTolerance = 1e-8; return std::abs(k - int_k) < kTolerance; } // Tests that the Simulator invokes the MixedContinuousDiscreteSystem's // update method every 0.001 sec, and its publish method every 0.0025 sec, // without missing any updates. GTEST_TEST(SimulatorTest, DiscreteUpdateAndPublish) { MixedContinuousDiscreteSystem system; int num_disc_updates = 0; system.set_update_callback([&](const Context<double>& context) { ASSERT_TRUE(CheckSampleTime(context, system.update_period())); num_disc_updates++; }); int num_publishes = 0; system.set_publish_callback([&](const Context<double>& context) { ASSERT_TRUE(CheckSampleTime(context, system.publish_period())); num_publishes++; }); Simulator<double> simulator(system); simulator.set_publish_at_initialization(false); simulator.set_publish_every_time_step(false); simulator.AdvanceTo(0.5); // Update occurs at 1000Hz, at the beginning of each step (there is no // discrete event update during initialization nor a final update at the // final time). EXPECT_EQ(500, num_disc_updates); // Publication occurs at 400Hz, at the end of initialization and the end // of each step. EXPECT_EQ(200 + 1, num_publishes); } // Tests that the order of events in a simulator time step is first update // discrete state, then publish, then integrate. GTEST_TEST(SimulatorTest, UpdateThenPublishThenIntegrate) { MixedContinuousDiscreteSystem system; Simulator<double> simulator(system); enum EventType { kPublish = 0, kUpdate = 1, kIntegrate = 2, kTypeCount = 3}; // Record the order in which the MixedContinuousDiscreteSystem is asked to // do publishes, compute discrete updates, or compute derivatives at each // time step. std::map<int, std::vector<EventType>> events; system.set_publish_callback( [&events, &simulator](const Context<double>& context) { events[simulator.get_num_steps_taken()].push_back(kPublish); }); system.set_update_callback( [&events, &simulator](const Context<double>& context) { events[simulator.get_num_steps_taken()].push_back(kUpdate); }); system.set_derivatives_callback( [&events, &simulator](const Context<double>& context) { events[simulator.get_num_steps_taken()].push_back(kIntegrate); }); // Run a simulation with per-step forced-publishing enabled. simulator.set_publish_at_initialization(true); simulator.set_publish_every_time_step(true); simulator.AdvanceTo(0.5); // Verify that at least one of each event type was triggered. bool triggers[kTypeCount] = { false, false, false }; // Check that all of the publish events precede all of the update events // (since "publish on init" was activated), which in turn precede all of the // derivative evaluation events, for each time step in the simulation. for (const auto& log : events) { ASSERT_GE(log.second.size(), 0u); EventType state = log.second[0]; for (const EventType& event : log.second) { triggers[event] = true; ASSERT_TRUE(event >= state); state = event; } } EXPECT_TRUE(triggers[kUpdate]); EXPECT_TRUE(triggers[kPublish]); EXPECT_TRUE(triggers[kIntegrate]); } // A basic sanity check that AutoDiff works. GTEST_TEST(SimulatorTest, AutodiffBasic) { SpringMassSystem<AutoDiffXd> spring_mass(1., 1., 0.); Simulator<AutoDiffXd> simulator(spring_mass); simulator.Initialize(); simulator.AdvanceTo(1); } // Verifies that an integrator will stretch its integration step in the case // that a directed step would end right before an event. GTEST_TEST(SimulatorTest, StretchedStep) { // Setting the update rate to 1.0 will cause the spring mass to update at // 1.0s. analysis_test::MySpringMassSystem<double> spring_mass( 1., 1., 1. /* update rate */); Simulator<double> simulator(spring_mass); // We will direct the integrator to take a single step of t_final, which // will be very near the mass-spring system's update event at 1.0s. 1e-8 // is so small that any reasonable degree of step "stretching" should jump // to 1.0 proper. const double expected_t_final = 1.0; const double directed_t_final = expected_t_final - 1e-8; // Initialize a fixed step integrator and the simulator. simulator.reset_integrator<RungeKutta2Integrator<double>>(directed_t_final); simulator.Initialize(); // Set initial condition using the Simulator's internal Context. simulator.get_mutable_context().SetTime(0); spring_mass.set_position(&simulator.get_mutable_context(), 0.1); spring_mass.set_velocity(&simulator.get_mutable_context(), 0); // Now step. simulator.AdvanceTo(expected_t_final); // Verify that the step size was stretched and that exactly one "step" was // taken to integrate the continuous variables forward. EXPECT_EQ(simulator.get_context().get_time(), expected_t_final); EXPECT_EQ(simulator.get_num_steps_taken(), 1); } // This test specifically tests for correct handling of issue #10443, in which // an event can be missed. GTEST_TEST(SimulatorTest, Issue10443) { // NOTE: This bug arose from a "perfect storm" of conditions- which // occurred due to the interactions of an error controlled integrator, the // maximum step size setting, and the particular publish period used. The // maintainer should assume that every line below is critical to reproducing // those conditions. // Log the output of a simple diagram containing a constant // source and an integrator. DiagramBuilder<double> builder; const double kValue = 2.4; const auto& source = *builder.AddSystem<ConstantVectorSource<double>>(kValue); const int kSize = 1; const auto& integrator = *builder.AddSystem<Integrator<double>>(kSize); builder.Connect(source.get_output_port(), integrator.get_input_port()); // Add a periodic logger. const int kFrequency = 10; // 10 cycles per second. auto& periodic_logger = *builder.AddSystem<VectorLogSink<double>>( kSize, 1.0 / kFrequency); builder.Connect(integrator.get_output_port(), periodic_logger.get_input_port()); // Finish constructing the Diagram. std::unique_ptr<Diagram<double>> diagram = builder.Build(); // Construct the Simulator with an RK3 integrator and settings that reproduce // the behavior. Simulator<double> simulator(*diagram); auto& rk3 = simulator.reset_integrator<RungeKutta3Integrator<double>>(); rk3.set_maximum_step_size(1.0 / kFrequency); rk3.request_initial_step_size_target(1e-4); rk3.set_target_accuracy(1e-4); rk3.set_fixed_step_mode(false); // Simulate. const int kTime = 1; simulator.AdvanceTo(static_cast<double>(kTime)); // Should log exactly once every kPeriod, up to and including // kTime. Eigen::VectorBlock<const VectorX<double>> t_periodic = periodic_logger.FindLog(simulator.get_context()).sample_times(); EXPECT_EQ(t_periodic.size(), kTime * kFrequency + 1); } // Verifies that an integrator will *not* stretch its integration step in the // case that a directed step would be before- but not too close- to an event. GTEST_TEST(SimulatorTest, NoStretchedStep) { // Setting the update rate to 1.0 will cause the spring mass to update at // 1.0s. analysis_test::MySpringMassSystem<double> spring_mass( 1., 1., 1. /* update rate */); Simulator<double> simulator(spring_mass); // We will direct the integrator to take a single step of 0.9, which // will be not so near the mass-spring system's update event at 1.0s. 0.1 // (the difference) is so large that any reasonable approach should avoid // stretching to 1.0 proper. const double event_t_final = 1.0; const double directed_t_final = event_t_final - 0.1; // Initialize a fixed step integrator. simulator.reset_integrator<RungeKutta2Integrator<double>>(directed_t_final); // Set initial condition using the Simulator's internal Context. simulator.get_mutable_context().SetTime(0); spring_mass.set_position(&simulator.get_mutable_context(), 0.1); spring_mass.set_velocity(&simulator.get_mutable_context(), 0); // Now step. simulator.AdvanceTo(event_t_final); // Verify that the step size was not stretched and that exactly two "steps" // were taken to integrate the continuous variables forward. EXPECT_EQ(simulator.get_context().get_time(), event_t_final); EXPECT_EQ(simulator.get_num_steps_taken(), 2); } // Verifies that artificially limiting a step does not change the ideal next // step for error controlled integrators. GTEST_TEST(SimulatorTest, ArtificalLimitingStep) { // Setting the update rate to 1.0 will cause the spring mass to update at // 1.0s. analysis_test::MySpringMassSystem<double> spring_mass( 1., 1., 1. /* update rate */); Simulator<double> simulator(spring_mass); // Set initial condition using the Simulator's internal Context. spring_mass.set_position(&simulator.get_mutable_context(), 1.0); spring_mass.set_velocity(&simulator.get_mutable_context(), 0.1); // Accuracy tolerances are extremely loose. const double accuracy = 1e-1; // Requested step size should start out two orders of magnitude larger than // desired_h (defined below), in order to prime the ideal next step size. const double req_initial_step_size = 1e-2; // Initialize the error controlled integrator and the simulator. simulator.reset_integrator<RungeKutta3Integrator<double>>(); IntegratorBase<double>& integrator = simulator.get_mutable_integrator(); integrator.request_initial_step_size_target(req_initial_step_size); integrator.set_target_accuracy(accuracy); simulator.Initialize(); // Mark the event time. const double event_time = 1.0; // Take a single step with the integrator. const double inf = std::numeric_limits<double>::infinity(); const Context<double>& context = integrator.get_context(); integrator.IntegrateNoFurtherThanTime(inf, context.get_time() + 1.0, context.get_time() + 1.0); // Verify that the integrator has stepped before the event time. EXPECT_LT(context.get_time(), event_time); // Get the ideal next step size and verify that it is not NaN. const double ideal_next_step_size = integrator.get_ideal_next_step_size(); // Set the time to right before an event, which should trigger artificial // limiting. const double desired_h = req_initial_step_size * 1e-2; simulator.get_mutable_context().SetTime(event_time - desired_h); // Step to the event time. integrator.IntegrateNoFurtherThanTime( inf, context.get_time() + desired_h, inf); // Verify that the context is at the event time. EXPECT_EQ(context.get_time(), event_time); // Verify that artificial limiting did not change the ideal next step size. EXPECT_EQ(integrator.get_ideal_next_step_size(), ideal_next_step_size); } // Verifies that an error controlled integrator will stretch its integration // step when it is near an update action and (a) error control is used, (b) // minimum step size exceptions are suppressed, (c) the integration step size // necessary to realize error tolerances is below the minimum step size. GTEST_TEST(SimulatorTest, StretchedStepPerfectStorm) { // Setting the update rate to 1.0 will cause the spring mass to update at // 1.0s. analysis_test::MySpringMassSystem<double> spring_mass( 1., 1., 1. /* update rate */); Simulator<double> simulator(spring_mass); // We will direct the integrator to take a single step of t_final, which // will be very near the mass-spring system's update event at 1.0s. 1e-8 // is so small that any reasonable degree of step "stretching" should jump // to 1.0 proper. const double expected_t_final = 1.0; const double directed_t_final = expected_t_final - 1e-8; // Accuracy tolerances are tight so that the integrator is sure to decrease // the step size. const double accuracy = 1e-8; const double req_min_step_size = directed_t_final; // Initialize the error controlled integrator and the simulator. simulator.reset_integrator<RungeKutta3Integrator<double>>(); IntegratorBase<double>& integrator = simulator.get_mutable_integrator(); integrator.set_requested_minimum_step_size(req_min_step_size); integrator.request_initial_step_size_target(directed_t_final); integrator.set_target_accuracy(accuracy); // Set initial condition using the Simulator's internal Context. simulator.get_mutable_context().SetTime(0); spring_mass.set_position(&simulator.get_mutable_context(), 0.1); spring_mass.set_velocity(&simulator.get_mutable_context(), 0); // Activate exceptions on violating the minimum step size to verify that // error control is a limiting factor. integrator.set_throw_on_minimum_step_size_violation(true); EXPECT_THROW(simulator.AdvanceTo(expected_t_final), std::runtime_error); // Now disable exceptions on violating the minimum step size and step again. // Since we are changing the state between successive AdvanceTo(.) calls, it // is wise to call Initialize() prior to the second call. simulator.get_mutable_context().SetTime(0); spring_mass.set_position(&simulator.get_mutable_context(), 0.1); spring_mass.set_velocity(&simulator.get_mutable_context(), 0); integrator.set_throw_on_minimum_step_size_violation(false); simulator.Initialize(); simulator.AdvanceTo(expected_t_final); // Verify that the step size was stretched and that exactly one "step" was // taken to integrate the continuous variables forward. EXPECT_EQ(simulator.get_context().get_time(), expected_t_final); EXPECT_EQ(simulator.get_num_steps_taken(), 1); } // Tests per step publish, discrete and unrestricted update actions. Each // action handler logs the context time when it's called, and the test compares // the time stamp against the integrator's h. GTEST_TEST(SimulatorTest, PerStepAction) { class PerStepActionTestSystem : public LeafSystem<double> { public: PerStepActionTestSystem() { // We need some continuous state (which will be unused) so that the // continuous state integration will not be bypassed. this->DeclareContinuousState(1); } void AddPerStepPublishEvent() { DeclarePerStepPublishEvent(&PerStepActionTestSystem::HandlePublish); } void AddPerStepDiscreteUpdateEvent() { DeclarePerStepDiscreteUpdateEvent( &PerStepActionTestSystem::HandleDiscrete); } void AddPerStepUnrestrictedUpdateEvent() { DeclarePerStepUnrestrictedUpdateEvent( &PerStepActionTestSystem::HandleUnrestricted); } const std::vector<double>& get_publish_times() const { return publish_times_; } const std::vector<double>& get_discrete_update_times() const { return discrete_update_times_; } const std::vector<double>& get_unrestricted_update_times() const { return unrestricted_update_times_; } private: void DoCalcTimeDerivatives( const Context<double>& context, ContinuousState<double>* derivatives) const override { // Derivative will always be zero, making the system stationary. derivatives->get_mutable_vector().SetAtIndex(0, 0.0); } // TODO(15465) When per-step event declaration sugar allows for callbacks // whose result is "assumed to succeed", change these to void return types. EventStatus HandleDiscrete(const Context<double>& context, DiscreteValues<double>*) const { discrete_update_times_.push_back(context.get_time()); return EventStatus::Succeeded(); } EventStatus HandleUnrestricted(const Context<double>& context, State<double>*) const { unrestricted_update_times_.push_back(context.get_time()); return EventStatus::Succeeded(); } EventStatus HandlePublish(const Context<double>& context) const { publish_times_.push_back(context.get_time()); return EventStatus::Succeeded(); } // A hack to test actions easily. // Note that these should really be part of the Context, and users should // NOT use this as an example code. // // Since Publish only takes a const Context, the only way to log time is // through some side effects. Thus, using a mutable vector can be justified. // // One conceptually correct implementation for discrete_update_times_ is // to pre allocate a big DiscreteState in Context, and store all the time // stamps there. // // unrestricted_update_times_ can be put in the AbstractState in Context // and mutated similarly to this implementation. // // The motivation for keeping them as mutable are for simplicity and // easiness to understand. mutable std::vector<double> publish_times_; mutable std::vector<double> discrete_update_times_; mutable std::vector<double> unrestricted_update_times_; }; PerStepActionTestSystem sys; sys.AddPerStepPublishEvent(); sys.AddPerStepUnrestrictedUpdateEvent(); sys.AddPerStepDiscreteUpdateEvent(); Simulator<double> sim(sys); // Forces simulator to use fixed-step integration. sim.get_mutable_integrator().set_fixed_step_mode(true); sim.get_mutable_integrator().set_maximum_step_size(0.001); // Disables all simulator induced publish events, so that all publish calls // are initiated by sys. sim.set_publish_at_initialization(false); sim.set_publish_every_time_step(false); sim.Initialize(); sim.AdvanceTo(0.1); const double h = sim.get_integrator().get_maximum_step_size(); const int N = static_cast<int>(0.1 / h); // Step size was set to 1ms above; make sure we don't have roundoff trouble. EXPECT_EQ(N, 100); ASSERT_EQ(sim.get_num_steps_taken(), N); auto& publish_times = sys.get_publish_times(); auto& discrete_update_times = sys.get_discrete_update_times(); auto& unrestricted_update_times = sys.get_unrestricted_update_times(); ASSERT_EQ(publish_times.size(), N + 1); // Once at end of Initialize(). ASSERT_EQ(sys.get_discrete_update_times().size(), N); ASSERT_EQ(sys.get_unrestricted_update_times().size(), N); for (int i = 0; i < N; ++i) { // Publish happens at the end of a step (including end of Initialize()); // unrestricted and discrete updates happen at the beginning of a step. EXPECT_NEAR(publish_times[i], i * h, 1e-12); EXPECT_NEAR(discrete_update_times[i], i * h, 1e-12); EXPECT_NEAR(unrestricted_update_times[i], i * h, 1e-12); } // There is a final end-of-step publish, but no final updates. EXPECT_NEAR(publish_times[N], N * h, 1e-12); } // Tests initialization from the simulator. GTEST_TEST(SimulatorTest, Initialization) { class InitializationTestSystem : public LeafSystem<double> { public: InitializationTestSystem() { PublishEvent<double> pub_event( [](const System<double>& system, const Context<double>& callback_context, const PublishEvent<double>& callback_event) { dynamic_cast<const InitializationTestSystem&>(system).InitPublish( callback_context, callback_event); return EventStatus::Succeeded(); }); DeclareInitializationEvent(pub_event); DeclareInitializationDiscreteUpdateEvent( &InitializationTestSystem::InitializationDiscreteUpdateHandler); DeclareInitializationUnrestrictedUpdateEvent( &InitializationTestSystem::InitializationUnrestrictedUpdateHandler); DeclarePeriodicDiscreteUpdateEvent( 0.1, 0.0, &InitializationTestSystem::PeriodicDiscreteUpdateHandler); DeclarePerStepUnrestrictedUpdateEvent( &InitializationTestSystem::PerStepUnrestrictedUpdateHandler); } bool get_pub_init() const { return pub_init_; } bool get_dis_update_init() const { return dis_update_init_; } bool get_unres_update_init() const { return unres_update_init_; } void reset() const { pub_init_ = false; dis_update_init_ = false; unres_update_init_ = false; } private: void InitPublish(const Context<double>& context, const PublishEvent<double>& event) const { EXPECT_EQ(context.get_time(), 0); EXPECT_EQ(event.get_trigger_type(), TriggerType::kInitialization); pub_init_ = true; } EventStatus InitializationDiscreteUpdateHandler( const Context<double>& context, DiscreteValues<double>*) const { EXPECT_EQ(context.get_time(), 0); dis_update_init_ = true; return EventStatus::Succeeded(); } EventStatus PeriodicDiscreteUpdateHandler(const Context<double>&, DiscreteValues<double>*) const { return EventStatus::DidNothing(); } EventStatus InitializationUnrestrictedUpdateHandler( const Context<double>& context, State<double>*) const { EXPECT_EQ(context.get_time(), 0); unres_update_init_ = true; return EventStatus::Succeeded(); } EventStatus PerStepUnrestrictedUpdateHandler(const Context<double>& context, State<double>*) const { return EventStatus::DidNothing(); } mutable bool pub_init_{false}; mutable bool dis_update_init_{false}; mutable bool unres_update_init_{false}; }; InitializationTestSystem sys; Simulator<double> simulator(sys); simulator.AdvanceTo(1); EXPECT_TRUE(sys.get_pub_init()); EXPECT_TRUE(sys.get_dis_update_init()); EXPECT_TRUE(sys.get_unres_update_init()); sys.reset(); simulator.get_mutable_context().SetTime(0); simulator.Initialize({.suppress_initialization_events = true}); simulator.AdvanceTo(1); EXPECT_FALSE(sys.get_pub_init()); EXPECT_FALSE(sys.get_dis_update_init()); EXPECT_FALSE(sys.get_unres_update_init()); } GTEST_TEST(SimulatorTest, OwnedSystemTest) { const double offset = 0.1; Simulator<double> simulator_w_system( std::make_unique<ExampleDiagram>(offset)); // Check that my System reference is still valid. EXPECT_NE( dynamic_cast<const ExampleDiagram*>(&simulator_w_system.get_system()), nullptr); } // This integrator is just explicit Euler with an extra unnecessary derivative // calculation thrown in to test that the derivative counter isn't fooled. class WastefulIntegrator final : public IntegratorBase<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(WastefulIntegrator) ~WastefulIntegrator() override = default; WastefulIntegrator(const System<double>& system, double max_step_size, Context<double>* context = nullptr) : IntegratorBase<double>(system, context) { IntegratorBase<double>::set_maximum_step_size(max_step_size); } bool supports_error_estimation() const final { return false; } int get_error_estimate_order() const final { return 0; } private: bool DoStep(const double& h) final { Context<double>& context = *this->get_mutable_context(); this->EvalTimeDerivatives(context); // Unused, but now up-to-date. // The rest of this is copied from ExplicitEuler. const ContinuousState<double>& xc_deriv = this->EvalTimeDerivatives(context); const VectorBase<double>& xcdot0 = xc_deriv.get_vector(); VectorBase<double>& xc = context.SetTimeAndGetMutableContinuousStateVector( context.get_time() + h); xc.PlusEqScaled(h, xcdot0); return true; } }; // The integrators are supposed to keep count of how many _actual_ derivative // evaluations are performed. Requests to evaluate that just return an // already-cached value don't count. For this test we use the fake "integrator" // above whose only "virtue" is that it makes multiple calls to derivatives // without changing the context so only the first of those should count. GTEST_TEST(SimulatorTest, EvalDerivativesCounter) { SpringMassSystem<double> spring_mass(1., 1., 0.); Simulator<double> simulator(spring_mass); Context<double>& context = simulator.get_mutable_context(); context.DisableCaching(); simulator.reset_integrator<WastefulIntegrator>(0.125); simulator.AdvanceTo(1.); // 8 steps, but 16 evaluations since no caching. EXPECT_EQ(simulator.get_integrator().get_num_steps_taken(), 8); EXPECT_EQ(simulator.get_integrator().get_num_derivative_evaluations(), 16); context.EnableCaching(); simulator.AdvanceTo(2.); // 8 more steps, but only 8 more evaluations. EXPECT_EQ(simulator.get_integrator().get_num_steps_taken(), 16); EXPECT_EQ(simulator.get_integrator().get_num_derivative_evaluations(), 24); } // Verify correct functioning of the monitor() API and runtime monitor // behavior, including correct monitor status reporting from the Simulator. GTEST_TEST(SimulatorTest, MonitorFunctionAndStatusReturn) { SpringMassSystem<double> spring_mass(1., 1., 0.); spring_mass.set_name("my_spring_mass"); Simulator<double> simulator(spring_mass); simulator.reset_integrator<ExplicitEulerIntegrator<double>>(0.125); std::vector<Eigen::VectorXd> states; const auto monitor = [&states](const Context<double>& root_context) { Eigen::VectorXd vector(1 + root_context.num_continuous_states()); vector << root_context.get_time(), root_context.get_continuous_state_vector().CopyToVector(); states.push_back(vector); return EventStatus::Succeeded(); }; simulator.set_monitor(monitor); EXPECT_TRUE(simulator.get_monitor()); SimulatorStatus status = simulator.AdvanceTo(1.); // Initialize + 8 steps. EXPECT_EQ(status.reason(), SimulatorStatus::kReachedBoundaryTime); EXPECT_EQ(simulator.get_num_steps_taken(), 8); EXPECT_EQ(states.size(), 9u); EXPECT_THAT(status.FormatMessage(), ::testing::MatchesRegex( "Simulator successfully reached the boundary time.*1.*")); // Check that some of the timestamps are right. EXPECT_EQ(states[0](0), 0.); EXPECT_EQ(states[1](0), 0.125); EXPECT_EQ(states[8](0), 1.); simulator.clear_monitor(); EXPECT_FALSE(simulator.get_monitor()); simulator.AdvanceTo(2.); EXPECT_EQ(simulator.get_num_steps_taken(), 16); EXPECT_EQ(states.size(), 9u); simulator.set_monitor(monitor); simulator.AdvanceTo(3.); // 8 more steps. EXPECT_EQ(simulator.get_num_steps_taken(), 24); EXPECT_EQ(states.size(), 17u); EXPECT_EQ(states[16](0), 3.); // This monitor should provide a clean termination that is properly // reported through the Simulator's status return. const auto good_monitor = [](const Context<double>& root_context) { const double time = root_context.get_time(); // Don't pass a System to blame for termination. return time < 3.49 ? EventStatus::Succeeded() : EventStatus::ReachedTermination(nullptr, "All done."); }; simulator.set_monitor(good_monitor); status = simulator.AdvanceTo(10.); EXPECT_EQ(status.reason(), SimulatorStatus::kReachedTerminationCondition); // Time should be exactly 3.5 due to our choice of step size. EXPECT_EQ(simulator.get_context().get_time(), 3.5); EXPECT_THAT( status.FormatMessage(), ::testing::MatchesRegex( "Simulator returned early.*3\\.5.*because.*requested termination.*" "with message.*All done\\..*")); // This monitor produces a hard failure that should cause the Simulator // to throw with a helpful message. const auto bad_monitor = [&spring_mass](const Context<double>& root_context) { const double time = root_context.get_time(); // Blame spring_mass for the error. return time < 5.99 ? EventStatus::Succeeded() : EventStatus::Failed(&spring_mass, "Something terrible happened."); }; simulator.set_monitor(bad_monitor); DRAKE_EXPECT_THROWS_MESSAGE( simulator.AdvanceTo(10.), ".*Simulator stopped at time 6.*because.*" "SpringMassSystem.*my_spring_mass.*" "failed with message.*Something terrible happened.*"); } /* A System that has a complete set of simultaneous events (unrestricted, discrete, publish) with both initialization and periodic triggers for the purpose of testing that event status handling is done properly. We also define per-step publish events so we can ensure we're working with the steps we expect. */ class EventStatusTestSystem : public LeafSystem<double> { public: enum class UpdateType { kUnrestricted, kDiscrete, kPublish, }; using Summary = std::tuple<TriggerType, UpdateType, int /* which */>; EventStatusTestSystem() { // Declare pairs (0 and 1) of identically-triggered events so that we have // simultaneous events of each handler type. MakeOneOfEach<0>(); MakeOneOfEach<1>(); DRAKE_DEMAND(event_severities_.size() == 14); } template <TriggerType trigger_type, UpdateType update_type, int which, typename... Args> EventStatus GenericHandler(const Context<double>& context, Args...) const { return MakeStatus(trigger_type, update_type, which, context.get_time()); } void SetSeverity(TriggerType trigger_type, UpdateType update_type, int which, EventStatus::Severity severity) { event_severities_.at(Summary{trigger_type, update_type, which}) = severity; } void SetAllSeverities(EventStatus::Severity severity) { for (auto& [_, map_entry_severity] : event_severities_) { map_entry_severity = severity; } } // Returns the list of events handled by all EventStatusTestSystem instances, // and clears the list back to empty. static std::vector<std::string> take_static_events() { std::vector<std::string> result = events_singleton(); events_singleton().clear(); return result; } private: static std::vector<std::string>& events_singleton() { static never_destroyed<std::vector<std::string>> global( std::vector<std::string>{}); return global.access(); } EventStatus MakeStatus(TriggerType trigger_type, UpdateType update_type, int which, double context_time) const { DRAKE_DEMAND(which == 0 || which == 1); const std::string description = fmt::format( "{} {} event {} at {}", trigger_type == TriggerType::kInitialization ? "initialization" : trigger_type == TriggerType::kPerStep ? "per-step" : trigger_type == TriggerType::kPeriodic ? "periodic" : "???", update_type == UpdateType::kUnrestricted ? "unrestricted update" : update_type == UpdateType::kDiscrete ? "discrete update" : update_type == UpdateType::kPublish ? "publish" : "???", which, context_time); events_singleton().push_back(description); switch (event_severities_.at(Summary{trigger_type, update_type, which})) { case EventStatus::kDidNothing: return EventStatus::DidNothing(); case EventStatus::kSucceeded: return EventStatus::Succeeded(); case EventStatus::kReachedTermination: return EventStatus::ReachedTermination( this, fmt::format("{} terminated", description)); case EventStatus::kFailed: return EventStatus::Failed(this, fmt::format("{} failed", description)); } DRAKE_UNREACHABLE(); } template <int which> void MakeOneOfEach() { DeclareInitializationUnrestrictedUpdateEvent( &EventStatusTestSystem::template GenericHandler< TriggerType::kInitialization, UpdateType::kUnrestricted, which, State<double>*>); DeclareInitializationDiscreteUpdateEvent( &EventStatusTestSystem::template GenericHandler< TriggerType::kInitialization, UpdateType::kDiscrete, which, DiscreteValues<double>*>); DeclareInitializationPublishEvent( &EventStatusTestSystem::template GenericHandler< TriggerType::kInitialization, UpdateType::kPublish, which>); DeclarePerStepPublishEvent(&EventStatusTestSystem::template GenericHandler< TriggerType::kPerStep, UpdateType::kPublish, which>); const double period = 0.5; const double offset = 0.0; DeclarePeriodicUnrestrictedUpdateEvent( period, offset, &EventStatusTestSystem::template GenericHandler< TriggerType::kPeriodic, UpdateType::kUnrestricted, which, State<double>*>); DeclarePeriodicDiscreteUpdateEvent( period, offset, &EventStatusTestSystem::template GenericHandler< TriggerType::kPeriodic, UpdateType::kDiscrete, which, DiscreteValues<double>*>); DeclarePeriodicPublishEvent( period, offset, &EventStatusTestSystem::template GenericHandler< TriggerType::kPeriodic, UpdateType::kPublish, which>); // Set return status to "succeeded" initially. for (auto trigger_type : {TriggerType::kInitialization, TriggerType::kPerStep, TriggerType::kPeriodic}) { for (auto update_type : {UpdateType::kUnrestricted, UpdateType::kDiscrete, UpdateType::kPublish}) { if (trigger_type == TriggerType::kPerStep && update_type != UpdateType::kPublish) { continue; } event_severities_[Summary{trigger_type, update_type, which}] = EventStatus::kSucceeded; } } } // The prescribed return value for each GenericHandler. std::map<Summary, EventStatus::Severity> event_severities_; }; // Verify that the Simulator handles EventStatus from event handlers correctly // (monitor status returns tested above). The Simulator-affecting statuses are // ReachedTermination (which should cause AdvanceTo to stop advancing and // report the reason) and Failure (which should cause an immediate halt to // event processing and throw an exception). In case of simultaneous // ReachedTermination and Failure, the Failure should win. // Simulator::Initialize() and ::AdvanceTo() process events similarly but differ // in details. GTEST_TEST(SimulatorTest, EventStatusReturnHandlingForInitialize) { using UpdateType = EventStatusTestSystem::UpdateType; EventStatusTestSystem system; system.set_name("my_event_system"); Simulator<double> sim(system); const double start_time = 0.125; // Note: not t=0, periodic won't trigger. sim.get_mutable_context().SetTime(start_time); auto reset = [&]() { system.SetAllSeverities(EventStatus::kSucceeded); sim.ResetStatistics(); // Clear the Simulator's counts. }; // Baseline: all events execute and return "succeeded". The Simulator should // count _dispatcher_ calls which cover multiple events. reset(); SimulatorStatus status = sim.Initialize(); const std::string all_events[] = { "initialization unrestricted update event 0 at 0.125", "initialization unrestricted update event 1 at 0.125", "initialization discrete update event 0 at 0.125", "initialization discrete update event 1 at 0.125", "initialization publish event 0 at 0.125", "initialization publish event 1 at 0.125", "per-step publish event 0 at 0.125", "per-step publish event 1 at 0.125"}; EXPECT_THAT(system.take_static_events(), ElementsAreArray(all_events)); EXPECT_EQ(sim.get_num_unrestricted_updates(), 1); EXPECT_EQ(sim.get_num_discrete_updates(), 1); EXPECT_EQ(sim.get_num_publishes(), 1); // initialize & per-step together EXPECT_TRUE(status.succeeded()); EXPECT_EQ(status.reason(), SimulatorStatus::kReachedBoundaryTime); EXPECT_EQ(sim.get_context().get_time(), start_time); // Same test but now everything returns "did nothing" so the Simulator // shouldn't count them. reset(); system.SetAllSeverities(EventStatus::kDidNothing); status = sim.Initialize(); EXPECT_THAT(system.take_static_events(), ElementsAreArray(all_events)); EXPECT_EQ(sim.get_num_unrestricted_updates(), 0); EXPECT_EQ(sim.get_num_discrete_updates(), 0); EXPECT_EQ(sim.get_num_publishes(), 0); EXPECT_TRUE(status.succeeded()); EXPECT_EQ(status.reason(), SimulatorStatus::kReachedBoundaryTime); EXPECT_EQ(sim.get_context().get_time(), start_time); // 2nd unrestricted update reports failure. Discrete and publish events // should not get executed. The dispatch should not be counted since it // failed. reset(); system.SetSeverity(TriggerType::kInitialization, UpdateType::kUnrestricted, 1, EventStatus::kFailed); DRAKE_EXPECT_THROWS_MESSAGE( sim.Initialize(), fmt::format("Simulator stopped.*" "unrestricted update event 1.*failed.*")); EXPECT_THAT( system.take_static_events(), ElementsAre("initialization unrestricted update event 0 at 0.125", "initialization unrestricted update event 1 at 0.125")); EXPECT_EQ(sim.get_num_unrestricted_updates(), 0); EXPECT_EQ(sim.get_num_discrete_updates(), 0); EXPECT_EQ(sim.get_num_publishes(), 0); EXPECT_EQ(sim.get_context().get_time(), start_time); // 2nd unrestricted update reports termination. Discrete events should still // be processed but then we return early without handling end-of-step publish // events. reset(); system.SetSeverity(TriggerType::kInitialization, UpdateType::kUnrestricted, 1, EventStatus::kReachedTermination); status = sim.Initialize(); EXPECT_THAT(system.take_static_events(), ElementsAre("initialization unrestricted update event 0 at 0.125", "initialization unrestricted update event 1 at 0.125", "initialization discrete update event 0 at 0.125", "initialization discrete update event 1 at 0.125")); EXPECT_EQ(sim.get_num_unrestricted_updates(), 1); EXPECT_EQ(sim.get_num_discrete_updates(), 1); EXPECT_EQ(sim.get_num_publishes(), 0); EXPECT_FALSE(status.succeeded()); EXPECT_EQ(status.reason(), SimulatorStatus::kReachedTerminationCondition); EXPECT_EQ(status.system(), &system); EXPECT_THAT(status.FormatMessage(), ::testing::MatchesRegex( fmt::format("Simulator returned early.*" "unrestricted update event 1.*terminated.*"))); EXPECT_EQ(sim.get_context().get_time(), start_time); // 2nd unrestricted update still reports termination, but later the 1st // discrete update fails, which trumps. Should stop executing at that point // and throw. Simulator shouldn't count the failed discrete update. reset(); system.SetSeverity(TriggerType::kInitialization, UpdateType::kUnrestricted, 1, EventStatus::kReachedTermination); system.SetSeverity(TriggerType::kInitialization, UpdateType::kDiscrete, 0, EventStatus::kFailed); DRAKE_EXPECT_THROWS_MESSAGE(sim.Initialize(), fmt::format("Simulator stopped.*" "discrete update event 0.*failed.*")); EXPECT_THAT(system.take_static_events(), ElementsAre("initialization unrestricted update event 0 at 0.125", "initialization unrestricted update event 1 at 0.125", "initialization discrete update event 0 at 0.125")); EXPECT_EQ(sim.get_num_unrestricted_updates(), 1); EXPECT_EQ(sim.get_num_discrete_updates(), 0); EXPECT_EQ(sim.get_num_publishes(), 0); EXPECT_EQ(sim.get_context().get_time(), start_time); // 1st publish event reports termination. All events should still execute // but return status should indicate termination. reset(); system.SetSeverity(TriggerType::kInitialization, UpdateType::kPublish, 0, EventStatus::kReachedTermination); status = sim.Initialize(); EXPECT_THAT(system.take_static_events(), ElementsAreArray(all_events)); EXPECT_EQ(sim.get_num_unrestricted_updates(), 1); EXPECT_EQ(sim.get_num_discrete_updates(), 1); EXPECT_EQ(sim.get_num_publishes(), 1); EXPECT_FALSE(status.succeeded()); EXPECT_EQ(status.reason(), SimulatorStatus::kReachedTerminationCondition); EXPECT_EQ(status.system(), &system); EXPECT_THAT(status.FormatMessage(), ::testing::MatchesRegex(fmt::format( "Simulator returned early.*" "publish event 0.*terminated.*"))); EXPECT_EQ(sim.get_context().get_time(), start_time); // 1st publish event reports failure. All events should still execute but an // error should be thrown. reset(); system.SetSeverity(TriggerType::kInitialization, UpdateType::kPublish, 0, EventStatus::kFailed); DRAKE_EXPECT_THROWS_MESSAGE(sim.Initialize(), fmt::format("Simulator stopped.*" "publish event 0.*failed.*")); EXPECT_THAT(system.take_static_events(), ElementsAreArray(all_events)); EXPECT_EQ(sim.get_num_unrestricted_updates(), 1); EXPECT_EQ(sim.get_num_discrete_updates(), 1); EXPECT_EQ(sim.get_num_publishes(), 0); // Shouldn't count failed dispatch. EXPECT_EQ(sim.get_context().get_time(), start_time); // Both publish events fail. All events should still execute but an error // should be thrown reporting the _first_ publish event's failure. reset(); system.SetSeverity(TriggerType::kInitialization, UpdateType::kPublish, 0, EventStatus::kFailed); system.SetSeverity(TriggerType::kInitialization, UpdateType::kPublish, 1, EventStatus::kFailed); DRAKE_EXPECT_THROWS_MESSAGE(sim.Initialize(), fmt::format("Simulator stopped.*" "publish event 0.*failed.*")); EXPECT_THAT(system.take_static_events(), ElementsAreArray(all_events)); EXPECT_EQ(sim.get_num_unrestricted_updates(), 1); EXPECT_EQ(sim.get_num_discrete_updates(), 1); EXPECT_EQ(sim.get_num_publishes(), 0); // Shouldn't count failed dispatch. EXPECT_EQ(sim.get_context().get_time(), start_time); } GTEST_TEST(SimulatorTest, EventStatusReturnHandlingForAdvanceTo) { using UpdateType = EventStatusTestSystem::UpdateType; EventStatusTestSystem system; system.set_name("my_event_system"); Simulator<double> sim(system); sim.reset_integrator<RungeKutta2Integrator<double>>(0.5); // Fixed step size. // We're starting at t=0.125 and advancing to t=0.75 with a step size of // h=0.5. If there were no events, the two steps taken would have been: // t=.125 (h=.5) t=.625 (h=.125) t=.75 // But with periodic events occurring at t=0.5, the steps will be: // t=.125 (h=.375) t=.5 (h=.25) t=.75 // Note that the per-step publishes will occur with each step regardless of // the step size. const double start_time = 0.125; const double early_return_time = 0.5; // Periodic events trigger here. const double boundary_time = 0.75; auto reset = [&]() { sim.get_mutable_context().SetTime(start_time); system.SetAllSeverities(EventStatus::kSucceeded); sim.Initialize(); system.take_static_events(); // Clear the System's event log. sim.ResetStatistics(); // Clear the Simulator's counts. }; // Baseline: advance to 0.75 with no notable status returns. Should take two // steps, executing the per-step publishes twice and each of the periodic // events once. reset(); SimulatorStatus status = sim.AdvanceTo(boundary_time); const std::string all_events[] = { "per-step publish event 0 at 0.5", "per-step publish event 1 at 0.5", "periodic publish event 0 at 0.5", "periodic publish event 1 at 0.5", "periodic unrestricted update event 0 at 0.5", "periodic unrestricted update event 1 at 0.5", "periodic discrete update event 0 at 0.5", "periodic discrete update event 1 at 0.5", "per-step publish event 0 at 0.75", "per-step publish event 1 at 0.75"}; EXPECT_THAT(system.take_static_events(), ElementsAreArray(all_events)); EXPECT_EQ(sim.get_num_unrestricted_updates(), 1); EXPECT_EQ(sim.get_num_discrete_updates(), 1); EXPECT_EQ(sim.get_num_publishes(), 2); // step+periodic dispatched together EXPECT_TRUE(status.succeeded()); EXPECT_EQ(sim.get_context().get_time(), boundary_time); EXPECT_EQ(sim.get_num_steps_taken(), 2); // Same, but everyone reports "did nothing" so the Simulator should not count // those dispatches. reset(); system.SetAllSeverities(EventStatus::kDidNothing); status = sim.AdvanceTo(boundary_time); EXPECT_THAT(system.take_static_events(), ElementsAreArray(all_events)); EXPECT_EQ(sim.get_num_unrestricted_updates(), 0); EXPECT_EQ(sim.get_num_discrete_updates(), 0); EXPECT_EQ(sim.get_num_publishes(), 0); EXPECT_TRUE(status.succeeded()); EXPECT_EQ(sim.get_context().get_time(), boundary_time); EXPECT_EQ(sim.get_num_steps_taken(), 2); // When we attempt to advance to t=0.75 we'll trigger events at t=0.5. Publish // events are handled at the _end_ of the step that reached 0.5; unrestricted // and discrete events are handled at the _start_ of the next step. // 2nd unrestricted update fails (at start of 2nd step). Should stop executing // at that point (t=0.5) and throw. Discrete updates and final publishes // should _not_ be handled. Simulator should not count the unrestricted // update since it failed. Per-step and periodic publishes occur at the end // of the first step (also t=0.5). reset(); system.SetSeverity(TriggerType::kPeriodic, UpdateType::kUnrestricted, 1, EventStatus::kFailed); DRAKE_EXPECT_THROWS_MESSAGE( status = sim.AdvanceTo(boundary_time), fmt::format("Simulator stopped.*" "periodic unrestricted update event 1.*failed.*")); EXPECT_THAT(system.take_static_events(), ElementsAre("per-step publish event 0 at 0.5", "per-step publish event 1 at 0.5", "periodic publish event 0 at 0.5", "periodic publish event 1 at 0.5", "periodic unrestricted update event 0 at 0.5", "periodic unrestricted update event 1 at 0.5")); EXPECT_EQ(sim.get_num_unrestricted_updates(), 0); EXPECT_EQ(sim.get_num_discrete_updates(), 0); EXPECT_EQ(sim.get_num_publishes(), 1); // the one at 0.5 (end of 1st step) // The periodic publish occurring at the end of the step that reaches 0.5 // reports termination. That should not stop both per-step and periodic // publishes from being handled then and allows the periodic updates to be // scheduled, though not handled. reset(); system.SetSeverity(TriggerType::kPeriodic, UpdateType::kPublish, 0, EventStatus::kReachedTermination); status = sim.AdvanceTo(boundary_time); EXPECT_THAT(system.take_static_events(), ElementsAre("per-step publish event 0 at 0.5", "per-step publish event 1 at 0.5", "periodic publish event 0 at 0.5", "periodic publish event 1 at 0.5")); EXPECT_EQ(sim.get_num_unrestricted_updates(), 0); EXPECT_EQ(sim.get_num_discrete_updates(), 0); EXPECT_EQ(sim.get_num_publishes(), 1); // dispatched together EXPECT_FALSE(status.succeeded()); EXPECT_EQ(status.reason(), SimulatorStatus::kReachedTerminationCondition); EXPECT_EQ(status.return_time(), 0.5); EXPECT_EQ(status.system(), &system); EXPECT_THAT(status.FormatMessage(), ::testing::MatchesRegex( fmt::format("Simulator returned early.*" "periodic publish event 0.*terminated.*"))); EXPECT_EQ(sim.get_context().get_time(), early_return_time); EXPECT_EQ(sim.get_num_steps_taken(), 1); // Handle the periodic events we left dangling. This counts as a final // zero-length step so will bump the step count and trigger per-step events. status = sim.AdvancePendingEvents(); EXPECT_THAT(system.take_static_events(), ElementsAre("periodic unrestricted update event 0 at 0.5", "periodic unrestricted update event 1 at 0.5", "periodic discrete update event 0 at 0.5", "periodic discrete update event 1 at 0.5", "per-step publish event 0 at 0.5", "per-step publish event 1 at 0.5")); EXPECT_EQ(sim.get_num_unrestricted_updates(), 1); EXPECT_EQ(sim.get_num_discrete_updates(), 1); EXPECT_EQ(sim.get_num_publishes(), 2); EXPECT_EQ(sim.get_num_steps_taken(), 2); // 2nd unrestricted event reports termination at 0.5 (_start_ of 2nd step). // Periodic and per-step publish events will trigger at end of 1st step, but // not at end of 2nd step since that will be cut short. However, both the // discrete update events should still trigger at start of 2nd since the // termination return doesn't halt execution of simultaneous updates. reset(); system.SetSeverity(TriggerType::kPeriodic, UpdateType::kUnrestricted, 1, EventStatus::kReachedTermination); status = sim.AdvanceTo(boundary_time); EXPECT_THAT(system.take_static_events(), ElementsAre("per-step publish event 0 at 0.5", "per-step publish event 1 at 0.5", "periodic publish event 0 at 0.5", "periodic publish event 1 at 0.5", "periodic unrestricted update event 0 at 0.5", "periodic unrestricted update event 1 at 0.5", "periodic discrete update event 0 at 0.5", "periodic discrete update event 1 at 0.5")); EXPECT_EQ(sim.get_num_unrestricted_updates(), 1); EXPECT_EQ(sim.get_num_discrete_updates(), 1); EXPECT_EQ(sim.get_num_publishes(), 1); EXPECT_FALSE(status.succeeded()); EXPECT_EQ(status.reason(), SimulatorStatus::kReachedTerminationCondition); EXPECT_EQ(status.system(), &system); EXPECT_THAT(status.FormatMessage(), ::testing::MatchesRegex(fmt::format( "Simulator returned early.*" "periodic unrestricted update event 1.*terminated.*"))); EXPECT_EQ(sim.get_context().get_time(), early_return_time); EXPECT_EQ(sim.get_num_steps_taken(), 1); // 2nd unrestricted update still reports termination, but later the 1st // discrete update fails, which trumps. Should stop executing at that point // (t=0.5) and throw. 2nd discrete update and final publishes should _not_ be // handled. Simulator should not count the discrete update since it failed. // Per-step and periodic publishes occur at the end of the first step (at // t=0.5). reset(); system.SetSeverity(TriggerType::kPeriodic, UpdateType::kUnrestricted, 1, EventStatus::kReachedTermination); system.SetSeverity(TriggerType::kPeriodic, UpdateType::kDiscrete, 0, EventStatus::kFailed); DRAKE_EXPECT_THROWS_MESSAGE( status = sim.AdvanceTo(boundary_time), fmt::format("Simulator stopped.*" "periodic discrete update event 0.*failed.*")); EXPECT_THAT(system.take_static_events(), ElementsAre("per-step publish event 0 at 0.5", "per-step publish event 1 at 0.5", "periodic publish event 0 at 0.5", "periodic publish event 1 at 0.5", "periodic unrestricted update event 0 at 0.5", "periodic unrestricted update event 1 at 0.5", "periodic discrete update event 0 at 0.5")); EXPECT_EQ(sim.get_num_unrestricted_updates(), 1); EXPECT_EQ(sim.get_num_discrete_updates(), 0); EXPECT_EQ(sim.get_num_publishes(), 1); // the one at 0.5 (end of 1st step) // First publish event fails. The second one should still be handled, then // AdvanceTo() should throw reporting the failure. That's at the end of the // first step (that ended at 0.5s) so we won't get to the unrestricted and // discrete updates that would have occurred at the start of the 2nd step. reset(); system.SetSeverity(TriggerType::kPeriodic, UpdateType::kPublish, 0, EventStatus::kFailed); DRAKE_EXPECT_THROWS_MESSAGE( status = sim.AdvanceTo(boundary_time), fmt::format("Simulator stopped.*" "periodic publish event 0.*failed.*")); EXPECT_THAT(system.take_static_events(), ElementsAre("per-step publish event 0 at 0.5", "per-step publish event 1 at 0.5", "periodic publish event 0 at 0.5", "periodic publish event 1 at 0.5")); EXPECT_EQ(sim.get_num_unrestricted_updates(), 0); EXPECT_EQ(sim.get_num_discrete_updates(), 0); EXPECT_EQ(sim.get_num_publishes(), 0); // Shouldn't count failed dispatch. // Same, but now both publishes failed. We should still report the failure of // the first one that failed, i.e., publish0. Note that per-step and periodic // publish handlers are all invoked (at end of 1st step) but we don't go any // futher because of the failure (so none of the updates that would have // occurred at the beginning of the next step occur). reset(); system.SetSeverity(TriggerType::kPeriodic, UpdateType::kPublish, 0, EventStatus::kFailed); system.SetSeverity(TriggerType::kPeriodic, UpdateType::kPublish, 1, EventStatus::kFailed); DRAKE_EXPECT_THROWS_MESSAGE( status = sim.AdvanceTo(boundary_time), fmt::format("Simulator stopped.*" "periodic publish event 0.*failed.*")); EXPECT_THAT(system.take_static_events(), ElementsAre("per-step publish event 0 at 0.5", "per-step publish event 1 at 0.5", "periodic publish event 0 at 0.5", "periodic publish event 1 at 0.5")); EXPECT_EQ(sim.get_num_unrestricted_updates(), 0); EXPECT_EQ(sim.get_num_discrete_updates(), 0); EXPECT_EQ(sim.get_num_publishes(), 0); // Shouldn't count failed dispatch. } // Simulator::Initialize() called at time t temporarily moves time back to // t̅ = t-δ prior to calling CalcNextUpdateTime() so that timed events scheduled // for time t will trigger. (t̅ is the next floating point value below t.) // This causes trouble for DoCalcNextUpdateTime() overloads that want an // event "right now", since those return contact.get_time(), which in this // case will be t̅ when it should have been t. When a Diagram runs through // all its subsystems looking for the "next" update time, it keeps only the // ones that occur at the earliest of all times reported, and forgets any // later ones (since obviously those are not "next"). Without special handling, // the "right now" events at t̅ would prevent other time t events from being // seen. (This was not done originally, see Drake issue #13296.) // // The case here creates a two-subsystem Diagram in which one of the subsystems // specifies a "right now" update time while the other has an event that occurs // at a specified time t. We'll verify that they play well together under // various circumstances that can occur during Simulator::Initialize(). GTEST_TEST(SimulatorTest, MissedPublishEventIssue13296) { // This models systems like LcmSubscriberSystem that want to generate // an event as soon as possible after an external message arrives. Here we // just set a flag to indicate that a "message" is waiting and generate an // event whenever that flag is set. class RightNowEventSystem : public LeafSystem<double> { public: int publish_count() const { return publish_counter_; } void reset_count() { publish_counter_ = 0; } void set_message_is_waiting(bool message_is_waiting) { message_is_waiting_ = message_is_waiting; } private: void DoCalcNextUpdateTime(const Context<double>& context, CompositeEventCollection<double>* event_info, double* next_update_time) const final { const double inf = std::numeric_limits<double>::infinity(); *next_update_time = message_is_waiting_ ? context.get_time() : inf; PublishEvent<double> event( [](const System<double>& system, const Context<double>& callback_context, const PublishEvent<double>& callback_event) { dynamic_cast<const RightNowEventSystem&>(system).MyPublishHandler( callback_context, callback_event); return EventStatus::Succeeded(); }); event.AddToComposite(TriggerType::kTimed, event_info); } void MyPublishHandler(const Context<double>& context, const PublishEvent<double>&) const { ++publish_counter_; } bool message_is_waiting_{false}; mutable int publish_counter_{0}; }; // Just an ordinary system that has a periodic event with period 0.25. It // should play nicely with simultaneous events from the // RightNowEventSystem above. class PeriodicEventSystem : public LeafSystem<double> { public: PeriodicEventSystem() { this->DeclarePeriodicPublishEvent(0.25, 0., &PeriodicEventSystem::MakeItCount); } int publish_count() const { return publish_counter_; } void reset_count() { publish_counter_ = 0; } private: void MakeItCount(const Context<double>&) const { ++publish_counter_; } mutable int publish_counter_{0}; }; DiagramBuilder<double> builder; auto right_now_system = builder.AddSystem<RightNowEventSystem>(); auto periodic_system = builder.AddSystem<PeriodicEventSystem>(); Simulator<double> simulator(builder.Build()); // Verify that CalcNextUpdateTime() returns "true time" rather than // current time when time is perturbed but we return "right now". // Note that the times are chosen to trigger only the "right now" event. const double true_time = .125; right_now_system->set_message_is_waiting(true); // Activate event. simulator.get_mutable_context().SetTime(true_time); auto events = simulator.get_system().AllocateCompositeEventCollection(); double next_update_time = simulator.get_system().CalcNextUpdateTime (simulator.get_context(), events.get()); EXPECT_EQ(simulator.get_context().get_time(), true_time); EXPECT_EQ(next_update_time, true_time); // Normal behavior. // Tweak the time. (Simulator::Initialize() does this more carefully.) const double perturbed_time = true_time - 1e-14; ASSERT_NE(perturbed_time, true_time); // Watch for precision loss. simulator.get_mutable_context().PerturbTime(perturbed_time, true_time); next_update_time = simulator.get_system().CalcNextUpdateTime (simulator.get_context(), events.get()); EXPECT_EQ(simulator.get_context().get_time(), perturbed_time); EXPECT_EQ(next_update_time, true_time); // Return true time, not current. // With no "message" waiting, the "right now" event won't trigger. At // the offset time 0, we should get just the periodic event. This has always // worked properly. right_now_system->set_message_is_waiting(false); // Deactivate event. simulator.get_mutable_context().SetTime(0.); simulator.Initialize(); EXPECT_EQ(right_now_system->publish_count(), 0); EXPECT_EQ(periodic_system->publish_count(), 1); periodic_system->reset_count(); // With a message waiting, the "right now" event should trigger, // but the periodic event won't issue until its offset time (0) is reached. // Although this wasn't reported in #13296, it did not work correctly before // the fix in PR #13438. right_now_system->set_message_is_waiting(true); simulator.get_mutable_context().SetTime(-1.); simulator.Initialize(); EXPECT_EQ(right_now_system->publish_count(), 1); EXPECT_EQ(periodic_system->publish_count(), 0); right_now_system->reset_count(); // With a message present and t=0 both should trigger. This is the case // that failed in #13296: the "right now" event would come back at the // perturbed time (slightly before zero), hiding the periodic event, and // its handler would not get called either since that isn't the current time. right_now_system->set_message_is_waiting(true); simulator.get_mutable_context().SetTime(0.); simulator.Initialize(); EXPECT_EQ(right_now_system->publish_count(), 1); EXPECT_EQ(periodic_system->publish_count(), 1); } } // namespace } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/instantaneous_realtime_rate_calculator_test.cc
#include "drake/systems/analysis/instantaneous_realtime_rate_calculator.h" #include <gtest/gtest.h> namespace drake { namespace systems { namespace { using internal::InstantaneousRealtimeRateCalculator; class MockTimer final : public Timer { public: void Start() final {} double Tick() final { return 0.1; } }; // Tests that the InstantaneousRealtimeRateCalculator calculates the correct // results including startup and rewinding time. GTEST_TEST(InstantaneousRealtimeRateCalculatorTest, BasicTest) { InstantaneousRealtimeRateCalculator calculator{}; calculator.InjectMockTimer(std::make_unique<MockTimer>()); // First (seed) call returns nullopt. EXPECT_FALSE(calculator.UpdateAndRecalculate(0.0).has_value()); // Next calls return correct value. EXPECT_DOUBLE_EQ(calculator.UpdateAndRecalculate(0.1).value(), 1.0); EXPECT_DOUBLE_EQ(calculator.UpdateAndRecalculate(0.2).value(), 1.0); EXPECT_DOUBLE_EQ(calculator.UpdateAndRecalculate(0.4).value(), 2.0); // Reset time and observe another nullopt result. EXPECT_FALSE(calculator.UpdateAndRecalculate(0.0).has_value()); EXPECT_DOUBLE_EQ(calculator.UpdateAndRecalculate(0.1).value(), 1.0); // Calling UpdateAndRecalcuate() again with the same sim time will // return 0.0 realtime rate. EXPECT_DOUBLE_EQ(calculator.UpdateAndRecalculate(0.1).value(), 0.0); // InstantaneousRealtimeRateCalculator should reset properly on call // to Reset(). calculator.Reset(); // First call to UpdateAndRecalculate() after Reset() returns nullopt // and calculation resumes on the next call. EXPECT_FALSE(calculator.UpdateAndRecalculate(0.2).has_value()); EXPECT_DOUBLE_EQ(calculator.UpdateAndRecalculate(0.3).value(), 1.0); } } // namespace } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/semi_explicit_euler_integrator_test.cc
#include "drake/systems/analysis/semi_explicit_euler_integrator.h" #include <cmath> #include <gtest/gtest.h> #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/analysis/explicit_euler_integrator.h" #include "drake/systems/analysis/test_utilities/my_spring_mass_system.h" namespace drake { namespace systems { namespace { // Tests context-related operations, including determining whether or not // system can be integrated without a context (it can't). GTEST_TEST(IntegratorTest, ContextAccess) { // Create the mass spring system. SpringMassSystem<double> spring_mass(1., 1., 0.); // Setup the integration step size. const double h = 1e-3; // Create a context. auto context = spring_mass.CreateDefaultContext(); // Create the integrator. SemiExplicitEulerIntegrator<double> integrator( spring_mass, h, context.get()); // Use default Context. integrator.get_mutable_context()->SetTime(3.); EXPECT_EQ(integrator.get_context().get_time(), 3.); EXPECT_EQ(context->get_time(), 3.); integrator.reset_context(nullptr); EXPECT_THROW(integrator.Initialize(), std::logic_error); const double target_time = context->get_time() + h; EXPECT_THROW(integrator.IntegrateNoFurtherThanTime( target_time, target_time, target_time), std::logic_error); } // Verifies error estimation is unsupported. GTEST_TEST(IntegratorTest, AccuracyEstAndErrorControl) { // Spring-mass system is necessary only to setup the problem. SpringMassSystem<double> spring_mass(1., 1., 0.); const double h = 1e-3; auto context = spring_mass.CreateDefaultContext(); SemiExplicitEulerIntegrator<double> integrator( spring_mass, h, context.get()); EXPECT_EQ(integrator.get_error_estimate_order(), 0); EXPECT_EQ(integrator.supports_error_estimation(), false); EXPECT_THROW(integrator.set_target_accuracy(1e-1), std::logic_error); EXPECT_THROW(integrator.request_initial_step_size_target(h), std::logic_error); } // Tests accuracy when generalized velocity is not the time derivative of // generalized configuration (using a rigid body). GTEST_TEST(IntegratorTest, RigidBody) { // Instantiate a multibody plant consisting of a single rigid body. multibody::MultibodyPlant<double> plant(0.0); const double radius = 0.05; // m const double mass = 0.1; // kg multibody::SpatialInertia<double> M_BBcm = multibody::SpatialInertia<double>::SolidSphereWithMass(mass, radius); plant.AddRigidBody("Ball", M_BBcm); plant.Finalize(); // Set free_body to have zero translation, zero rotation, and zero velocity. auto context = plant.CreateDefaultContext(); plant.SetDefaultState(*context, &context->get_mutable_state()); // Update the velocity. VectorX<double> generalized_velocities(plant.num_velocities()); generalized_velocities << 1, 2, 3, 4, 5, 6; // Set the linear and angular velocity. plant.SetVelocities(context.get(), generalized_velocities); // Integrate for one second of virtual time using explicit Euler integrator. const double small_h = 1e-4; ExplicitEulerIntegrator<double> ee(plant, small_h, context.get()); ee.Initialize(); const double t_final = 1.0; do { ee.IntegrateNoFurtherThanTime(t_final, t_final, t_final); } while (context->get_time() < t_final); // Get the final state. VectorX<double> x_final_ee = context->get_continuous_state_vector(). CopyToVector(); // Re-integrate with semi-explicit Euler. context->SetTime(0.); plant.SetDefaultState(*context, &context->get_mutable_state()); plant.SetVelocities(context.get(), generalized_velocities); SemiExplicitEulerIntegrator<double> see(plant, small_h, context.get()); see.Initialize(); // Integrate for one second. do { see.IntegrateNoFurtherThanTime(t_final, t_final, t_final); } while (context->get_time() < t_final); // Verify that the final states are "close". VectorX<double> x_final_see = context->get_continuous_state_vector(). CopyToVector(); const double tol = 5e-3; for (int i=0; i< x_final_see.size(); ++i) EXPECT_NEAR(x_final_ee[i], x_final_see[i], tol); } // Try a purely continuous system with no sampling. // d^2x/dt^2 = -kx/m // solution to this ODE: x(t) = c1*cos(omega*t) + c2*sin(omega*t) // where omega = sqrt(k/m) // x'(t) = -c1*sin(omega*t)*omega + c2*cos(omega*t)*omega // for t = 0, x(0) = c1, x'(0) = c2*omega GTEST_TEST(IntegratorTest, SpringMassStep) { const double kSpring = 300.0; // N/m const double kMass = 2.0; // kg // Create the spring-mass system. SpringMassSystem<double> spring_mass(kSpring, kMass, 0.); // Create a context. auto context = spring_mass.CreateDefaultContext(); // Setup the integration size and infinity. const double h = 1e-6; const double inf = std::numeric_limits<double>::infinity(); // Create the integrator. SemiExplicitEulerIntegrator<double> integrator( spring_mass, h, context.get()); // Use default Context. // Setup the initial position and initial velocity. const double kInitialPosition = 0.1; const double kInitialVelocity = 0.01; const double kOmega = std::sqrt(kSpring / kMass); // Set initial condition. spring_mass.set_position(context.get(), kInitialPosition); // Take all the defaults. integrator.Initialize(); // Setup c1 and c2 for ODE constants. const double c1 = kInitialPosition; const double c2 = kInitialVelocity / kOmega; // Integrate for 1 second. const double kTFinal = 1.0; double t; for (t = 0.0; std::abs(t - kTFinal) > h; t += h) integrator.IntegrateNoFurtherThanTime(inf, inf, kTFinal); EXPECT_NEAR(context->get_time(), t, h); // Should be exact. // Get the final position. const double x_final = context->get_continuous_state().get_vector().GetAtIndex(0); // Check the solution. EXPECT_NEAR(c1 * std::cos(kOmega * t) + c2 * std::sin(kOmega * t), x_final, 5e-3); // Verify that integrator statistics are valid EXPECT_GT(integrator.get_previous_integration_step_size(), 0.0); EXPECT_GT(integrator.get_largest_step_size_taken(), 0.0); EXPECT_GT(integrator.get_num_steps_taken(), 0); EXPECT_EQ(integrator.get_error_estimate(), nullptr); EXPECT_GT(integrator.get_num_derivative_evaluations(), 0); } } // namespace } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/bogacki_shampine3_integrator_test.cc
#include "drake/systems/analysis/bogacki_shampine3_integrator.h" #include <cmath> #include <gtest/gtest.h> #include "drake/common/eigen_types.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/math/rotation_matrix.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/analysis/runge_kutta2_integrator.h" #include "drake/systems/analysis/test_utilities/cubic_scalar_system.h" #include "drake/systems/analysis/test_utilities/explicit_error_controlled_integrator_test.h" #include "drake/systems/analysis/test_utilities/generic_integrator_test.h" #include "drake/systems/analysis/test_utilities/my_spring_mass_system.h" #include "drake/systems/analysis/test_utilities/quadratic_scalar_system.h" namespace drake { namespace systems { namespace analysis_test { typedef ::testing::Types<BogackiShampine3Integrator<double>> Types; // NOLINTNEXTLINE(whitespace/line_length) INSTANTIATE_TYPED_TEST_SUITE_P(My, ExplicitErrorControlledIntegratorTest, Types); INSTANTIATE_TYPED_TEST_SUITE_P(My, PleidesTest, Types); INSTANTIATE_TYPED_TEST_SUITE_P(My, GenericIntegratorTest, Types); // Tests accuracy for integrating the cubic system (with the state at time t // corresponding to f(t) ≡ t³ + t² + 12t + C) over t ∈ [0, 1]. BS3 is a third // order integrator, meaning that it uses the Taylor Series expansion: // f(t+h) ≈ f(t) + hf'(t) + ½h²f''(t) + ⅙h³f'''(t) + O(h⁴) // The formula above indicates that the approximation error will be zero if // f''''(t) = 0, which is true for the cubic equation. GTEST_TEST(BS3IntegratorErrorEstimatorTest, CubicTest) { CubicScalarSystem cubic; auto cubic_context = cubic.CreateDefaultContext(); const double C = cubic.Evaluate(0); cubic_context->SetTime(0.0); cubic_context->get_mutable_continuous_state_vector()[0] = C; BogackiShampine3Integrator<double> bs3(cubic, cubic_context.get()); const double t_final = 1.0; bs3.set_maximum_step_size(t_final); bs3.set_fixed_step_mode(true); bs3.Initialize(); ASSERT_TRUE(bs3.IntegrateWithSingleFixedStepToTime(t_final)); // Check for near-exact 3rd-order results. The measure of accuracy is a // tolerance that scales with expected answer at t_final. const double expected_answer = cubic.Evaluate(t_final); const double allowable_3rd_order_error = expected_answer * std::numeric_limits<double>::epsilon(); const double actual_answer = cubic_context->get_continuous_state_vector()[0]; EXPECT_NEAR(actual_answer, expected_answer, allowable_3rd_order_error); // This integrator calculates error by subtracting a 2nd-order integration // result from a 3rd-order integration result. Since the 2nd-order integrator // has a Taylor series that is accurate to O(h³) and since we have no terms // beyond order h³, halving the step size should improve the error estimate // by a factor of 2³ = 8. We verify this. // First obtain the error estimate using a single step of h. const double err_est_h = bs3.get_error_estimate()->get_vector().GetAtIndex(0); // Now obtain the error estimate using two half steps of h/2. cubic_context->SetTime(0.0); cubic_context->get_mutable_continuous_state_vector()[0] = C; bs3.Initialize(); ASSERT_TRUE(bs3.IntegrateWithSingleFixedStepToTime(t_final / 2)); ASSERT_TRUE(bs3.IntegrateWithSingleFixedStepToTime(t_final)); const double err_est_2h_2 = bs3.get_error_estimate()->get_vector().GetAtIndex(0); EXPECT_NEAR(err_est_2h_2, 1.0 / 8 * err_est_h, 10 * std::numeric_limits<double>::epsilon()); } // Tests accuracy for integrating the quadratic system (with the state at time t // corresponding to f(t) ≡ 4t² + 4t + C, where C is the initial state) over // t ∈ [0, 1]. The error estimate from BS3 is second order accurate, meaning // that the approximation error will be zero if f'''(t) = 0, which is true for // the quadratic equation. We check that the error estimate is perfect for this // function. GTEST_TEST(BS3IntegratorErrorEstimatorTest, QuadraticTest) { QuadraticScalarSystem quadratic; auto quadratic_context = quadratic.CreateDefaultContext(); const double C = quadratic.Evaluate(0); quadratic_context->SetTime(0.0); quadratic_context->get_mutable_continuous_state_vector()[0] = C; BogackiShampine3Integrator<double> bs3(quadratic, quadratic_context.get()); const double t_final = 1.0; bs3.set_maximum_step_size(t_final); bs3.set_fixed_step_mode(true); bs3.Initialize(); ASSERT_TRUE(bs3.IntegrateWithSingleFixedStepToTime(t_final)); // Per the description in IntegratorBase::get_error_estimate_order(), this // should return "3", in accordance with the order of the polynomial in the // Big-Oh term. ASSERT_EQ(bs3.get_error_estimate_order(), 3); const double err_est = bs3.get_error_estimate()->get_vector().GetAtIndex(0); // Note the very tight tolerance used, which will likely not hold for // arbitrary values of C, t_final, or polynomial coefficients. EXPECT_NEAR(err_est, 0.0, 2 * std::numeric_limits<double>::epsilon()); } } // namespace analysis_test } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/hermitian_dense_output_test.cc
#include "drake/systems/analysis/hermitian_dense_output.h" #include <gtest/gtest.h> #include "drake/common/eigen_types.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_no_throw.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/trajectories/piecewise_polynomial.h" namespace drake { namespace systems { namespace analysis { namespace { template <typename T> class HermitianDenseOutputTest : public ::testing::Test { protected: const double kInvalidTime{-1.0}; const double kInitialTime{0.0}; const double kMidTime{0.5}; const double kFinalTime{1.0}; const double kTimeStep{0.1}; const MatrixX<double> kInitialState{ (MatrixX<double>(3, 1) << 0., 0., 0.).finished()}; const MatrixX<double> kMidState{ (MatrixX<double>(3, 1) << 0.5, 5., 50.).finished()}; const MatrixX<double> kFinalState{ (MatrixX<double>(3, 1) << 1., 10., 100.).finished()}; const MatrixX<double> kFinalStateWithFewerDimensions{ (MatrixX<double>(2, 1) << 1., 10.).finished()}; const MatrixX<double> kFinalStateWithMoreDimensions{ (MatrixX<double>(4, 1) << 1., 10., 100., 1000.).finished()}; const MatrixX<double> kFinalStateNotAVector{ (MatrixX<double>(2, 2) << 1., 10., 100., 1000.).finished()}; const MatrixX<double> kInitialStateDerivative{ (MatrixX<double>(3, 1) << 0., 1., 0.).finished()}; const MatrixX<double> kMidStateDerivative{ (MatrixX<double>(3, 1) << 0.5, 0.5, 0.5).finished()}; const MatrixX<double> kFinalStateDerivative{ (MatrixX<double>(3, 1) << 1., 0., 1.).finished()}; const MatrixX<double> kFinalStateDerivativeWithFewerDimensions{ (MatrixX<double>(2, 1) << 1., 0.).finished()}; const MatrixX<double> kFinalStateDerivativeWithMoreDimensions{ (MatrixX<double>(4, 1) << 1., 0., 1., 0.).finished()}; const MatrixX<double> kFinalStateDerivativeNotAVector{ (MatrixX<double>(2, 2) << 0., 1., 0., 1.).finished()}; const int kValidElementIndex{0}; const int kInvalidElementIndex{10}; const std::string kEmptyOutputErrorMessage{ ".*[Dd]ense output.*empty.*"}; const std::string kZeroLengthStepErrorMessage{ ".*step has zero length.*"}; const std::string kCannotRollbackErrorMessage{ "No updates to rollback."}; const std::string kCannotConsolidateErrorMessage{ "No updates to consolidate."}; const std::string kInvalidElementIndexErrorMessage{ ".*out of.*dense output.*range.*"}; const std::string kInvalidTimeErrorMessage{ ".*[Tt]ime.*out of.*dense output.*domain.*"}; const std::string kTimeMismatchErrorMessage{ ".*start time.*end time.*differ.*"}; const std::string kStateMismatchErrorMessage{ ".*start state.*end state.*differ.*"}; const std::string kStateDerivativeMismatchErrorMessage{ ".*start state derivative.*end state derivative.*differ.*"}; const std::string kStepBackwardsErrorMessage{ ".*cannot be extended backwards.*"}; const std::string kDimensionMismatchErrorMessage{ ".*dimensions do not match.*"}; const std::string kNotAVectorErrorMessage{".*not a column matrix.*"}; }; // HermitianDenseOutput types to test. typedef ::testing::Types<double, AutoDiffXd> OutputTypes; TYPED_TEST_SUITE(HermitianDenseOutputTest, OutputTypes); // Checks that HermitianDenseOutput consistency is ensured. TYPED_TEST(HermitianDenseOutputTest, OutputConsistency) { // Instantiates dense output. HermitianDenseOutput<TypeParam> dense_output; // Verifies that the dense output is empty and API behavior // is consistent with that fact. ASSERT_TRUE(dense_output.is_empty()); DRAKE_EXPECT_THROWS_MESSAGE( dense_output.Evaluate(this->kInitialTime), this->kEmptyOutputErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE(dense_output.EvaluateNth( this->kInitialTime, this->kValidElementIndex), this->kEmptyOutputErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE(dense_output.start_time(), this->kEmptyOutputErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE(dense_output.end_time(), this->kEmptyOutputErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE(dense_output.size(), this->kEmptyOutputErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE(dense_output.Rollback(), this->kCannotRollbackErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE(dense_output.Consolidate(), this->kCannotConsolidateErrorMessage); // Verifies that trying to update the dense output with // a zero length step fails. typename HermitianDenseOutput<TypeParam>::IntegrationStep first_step( this->kInitialTime, this->kInitialState, this->kInitialStateDerivative); DRAKE_EXPECT_THROWS_MESSAGE(dense_output.Update(first_step), this->kZeroLengthStepErrorMessage); // Verifies that trying to update the dense output with // a valid step succeeds. first_step.Extend(this->kMidTime, this->kMidState, this->kMidStateDerivative); dense_output.Update(first_step); // Verifies that an update does not imply a consolidation and thus // the dense output remains empty. ASSERT_TRUE(dense_output.is_empty()); DRAKE_EXPECT_THROWS_MESSAGE(dense_output.Evaluate(this->kMidTime), this->kEmptyOutputErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE( dense_output.EvaluateNth(this->kMidTime, this->kValidElementIndex), this->kEmptyOutputErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE(dense_output.start_time(), this->kEmptyOutputErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE(dense_output.end_time(), this->kEmptyOutputErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE(dense_output.size(), this->kEmptyOutputErrorMessage); // Consolidates all previous updates. dense_output.Consolidate(); // Verifies that it is not possible to roll back updates after consolidation. DRAKE_EXPECT_THROWS_MESSAGE(dense_output.Rollback(), this->kCannotRollbackErrorMessage); // Verifies that it is not possible to consolidate again. DRAKE_EXPECT_THROWS_MESSAGE(dense_output.Consolidate(), this->kCannotConsolidateErrorMessage); // Verifies that the dense output is not empty and that it // reflects the data provided on updates. ASSERT_FALSE(dense_output.is_empty()); EXPECT_EQ(dense_output.start_time(), first_step.start_time()); EXPECT_EQ(dense_output.end_time(), first_step.end_time()); EXPECT_EQ(dense_output.size(), first_step.size()); DRAKE_EXPECT_NO_THROW(dense_output.Evaluate(this->kMidTime)); DRAKE_EXPECT_NO_THROW(dense_output.EvaluateNth( this->kMidTime, this->kValidElementIndex)); // Verifies that invalid evaluation arguments generate errors. DRAKE_EXPECT_THROWS_MESSAGE( dense_output.EvaluateNth(this->kMidTime, this->kInvalidElementIndex), this->kInvalidElementIndexErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE( dense_output.EvaluateNth(this->kInvalidTime, this->kValidElementIndex), this->kInvalidTimeErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE( dense_output.Evaluate(this->kInvalidTime), this->kInvalidTimeErrorMessage); // Verifies that step updates that would disrupt the output continuity // fail. typename HermitianDenseOutput<TypeParam>::IntegrationStep second_step( (this->kFinalTime + this->kMidTime) / 2., this->kMidState, this->kMidStateDerivative); second_step.Extend(this->kFinalTime, this->kFinalState, this->kFinalStateDerivative); DRAKE_EXPECT_THROWS_MESSAGE( dense_output.Update(second_step), this->kTimeMismatchErrorMessage); typename HermitianDenseOutput<TypeParam>::IntegrationStep third_step( this->kMidTime, this->kMidState * 2., this->kMidStateDerivative); third_step.Extend(this->kFinalTime, this->kFinalState, this->kFinalStateDerivative); DRAKE_EXPECT_THROWS_MESSAGE( dense_output.Update(third_step), this->kStateMismatchErrorMessage); typename HermitianDenseOutput<TypeParam>::IntegrationStep fourth_step( this->kMidTime, this->kMidState, this->kMidStateDerivative * 2.); fourth_step.Extend(this->kFinalTime, this->kFinalState, this->kFinalStateDerivative); DRAKE_EXPECT_THROWS_MESSAGE( dense_output.Update(fourth_step), this->kStateDerivativeMismatchErrorMessage); } // Checks that HermitianDenseOutput::Step consistency is ensured. TYPED_TEST(HermitianDenseOutputTest, StepsConsistency) { // Verifies that zero length steps are properly constructed. typename HermitianDenseOutput<TypeParam>::IntegrationStep step( this->kInitialTime, this->kInitialState, this->kInitialStateDerivative); ASSERT_EQ(step.get_times().size(), 1); EXPECT_EQ(step.start_time(), this->kInitialTime); EXPECT_EQ(step.end_time(), this->kInitialTime); EXPECT_EQ(step.size(), this->kInitialState.rows()); ASSERT_EQ(step.get_states().size(), 1); EXPECT_TRUE(CompareMatrices(step.get_states().front(), this->kInitialState)); ASSERT_EQ(step.get_state_derivatives().size(), 1); EXPECT_TRUE(CompareMatrices(step.get_state_derivatives().front(), this->kInitialStateDerivative)); // Verifies that any attempt to break step consistency fails. DRAKE_EXPECT_THROWS_MESSAGE( step.Extend(this->kInvalidTime, this->kFinalState, this->kFinalStateDerivative), this->kStepBackwardsErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE( step.Extend(this->kFinalTime, this->kFinalStateWithFewerDimensions, this->kFinalStateDerivative), this->kDimensionMismatchErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE( step.Extend(this->kFinalTime, this->kFinalStateWithMoreDimensions, this->kFinalStateDerivative), this->kDimensionMismatchErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE( step.Extend(this->kFinalTime, this->kFinalStateNotAVector, this->kFinalStateDerivative), this->kNotAVectorErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE( step.Extend(this->kFinalTime, this->kFinalState, this->kFinalStateDerivativeWithFewerDimensions), this->kDimensionMismatchErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE( step.Extend(this->kFinalTime, this->kFinalState, this->kFinalStateDerivativeWithMoreDimensions), this->kDimensionMismatchErrorMessage); DRAKE_EXPECT_THROWS_MESSAGE( step.Extend(this->kFinalTime, this->kFinalState, this->kFinalStateDerivativeNotAVector), this->kNotAVectorErrorMessage); // Extends the step with appropriate values. step.Extend(this->kFinalTime, this->kFinalState, this->kFinalStateDerivative); // Verifies that the step was properly extended. EXPECT_EQ(step.get_times().size(), 2); EXPECT_EQ(step.start_time(), this->kInitialTime); EXPECT_EQ(step.end_time(), this->kFinalTime); EXPECT_EQ(step.size(), this->kInitialState.rows()); EXPECT_EQ(step.get_states().size(), 2); EXPECT_TRUE(CompareMatrices(step.get_states().back(), this->kFinalState)); EXPECT_EQ(step.get_state_derivatives().size(), 2); EXPECT_TRUE(CompareMatrices(step.get_state_derivatives().back(), this->kFinalStateDerivative)); } // Checks that HermitianDenseOutput properly supports stepwise // construction. TYPED_TEST(HermitianDenseOutputTest, CorrectConstruction) { // Instantiates dense output. HermitianDenseOutput<TypeParam> dense_output; // Updates output for the first time. typename HermitianDenseOutput<TypeParam>::IntegrationStep first_step( this->kInitialTime, this->kInitialState, this->kInitialStateDerivative); first_step.Extend(this->kMidTime, this->kMidState, this->kMidStateDerivative); dense_output.Update(first_step); // Updates output a second time. typename HermitianDenseOutput<TypeParam>::IntegrationStep second_step( this->kMidTime, this->kMidState, this->kMidStateDerivative); second_step.Extend(this->kFinalTime, this->kFinalState, this->kFinalStateDerivative); dense_output.Update(second_step); // Rolls back the last update. dense_output.Rollback(); // `second_step` // Consolidates existing updates. dense_output.Consolidate(); // only `first_step` // Verifies that the dense output only reflects the first step. EXPECT_FALSE(dense_output.is_empty()); EXPECT_EQ(dense_output.start_time(), first_step.start_time()); EXPECT_EQ(dense_output.end_time(), first_step.end_time()); EXPECT_EQ(dense_output.size(), first_step.size()); EXPECT_TRUE(CompareMatrices(dense_output.Evaluate(this->kInitialTime), first_step.get_states().front())); EXPECT_TRUE(CompareMatrices(dense_output.Evaluate(this->kMidTime), first_step.get_states().back())); } // Checks that HermitianDenseOutput properly implements and evaluates // an Hermite interpolator. TYPED_TEST(HermitianDenseOutputTest, CorrectEvaluation) { // Creates an Hermite cubic spline with times, states and state // derivatives. const std::vector<double> spline_times{ this->kInitialTime, this->kMidTime, this->kFinalTime}; const std::vector<MatrixX<double>> spline_states{ this->kInitialState, this->kMidState, this->kFinalState}; const std::vector<MatrixX<double>> spline_state_derivatives{ this->kInitialStateDerivative, this->kMidStateDerivative, this->kFinalStateDerivative}; const trajectories::PiecewisePolynomial<double> hermite_spline = trajectories::PiecewisePolynomial<double>::CubicHermite( spline_times, spline_states, spline_state_derivatives); // Instantiates dense output. HermitianDenseOutput<TypeParam> dense_output; // Updates output for the first time. typename HermitianDenseOutput<TypeParam>::IntegrationStep first_step( this->kInitialTime, this->kInitialState, this->kInitialStateDerivative); first_step.Extend(this->kMidTime, this->kMidState, this->kMidStateDerivative); dense_output.Update(first_step); // Updates output a second time. typename HermitianDenseOutput<TypeParam>::IntegrationStep second_step( this->kMidTime, this->kMidState, this->kMidStateDerivative); second_step.Extend(this->kFinalTime, this->kFinalState, this->kFinalStateDerivative); dense_output.Update(second_step); // Consolidates all previous updates. dense_output.Consolidate(); // Verifies that dense output and Hermite spline match. const double kAccuracy{1e-12}; EXPECT_FALSE(dense_output.is_empty()); for (TypeParam t = this->kInitialTime; t <= this->kFinalTime; t += this->kTimeStep) { const MatrixX<double> matrix_value = hermite_spline.value(ExtractDoubleOrThrow(t)); const VectorX<TypeParam> vector_value = matrix_value.col(0).template cast<TypeParam>(); EXPECT_TRUE(CompareMatrices(dense_output.Evaluate(t), vector_value, kAccuracy)); } } // Construct a HermitianDenseOutput<T> from PiecewisePolynomial<U>. template <typename T> void TestScalarType() { const Vector3<T> breaks(0.0, 1.0, 2.0); const RowVector3<T> samples(6.0, 5.0, 4.0); const auto foh = trajectories::PiecewisePolynomial<T>::FirstOrderHold(breaks, samples); const HermitianDenseOutput<T> hdo(foh); EXPECT_EQ(ExtractDoubleOrThrow(hdo.start_time()), ExtractDoubleOrThrow(breaks(0))); EXPECT_EQ(ExtractDoubleOrThrow(hdo.end_time()), ExtractDoubleOrThrow(breaks(2))); for (const T& time : {T(0.1), T(0.4), T(1.6)}) { EXPECT_NEAR(ExtractDoubleOrThrow(hdo.Evaluate(time)(0)), ExtractDoubleOrThrow(foh.value(time)(0)), 1e-14); } } GTEST_TEST(HermitianDenseOutputTest, ConstructFromPiecewisePolynomialTest) { TestScalarType<double>(); TestScalarType<AutoDiffXd>(); TestScalarType<symbolic::Expression>(); } } // namespace } // namespace analysis } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/scalar_initial_value_problem_test.cc
#include "drake/systems/analysis/scalar_initial_value_problem.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/unused.h" #include "drake/systems/analysis/integrator_base.h" #include "drake/systems/analysis/runge_kutta2_integrator.h" namespace drake { namespace systems { namespace analysis { namespace { // Checks scalar IVP solver usage with multiple integrators. GTEST_TEST(ScalarInitialValueProblemTest, UsingMultipleIntegrators) { // Accuracy upper bound, as not all the integrators used below support // error control. const double kAccuracy = 1e-2; // The initial time t₀, for IVP definition. const double kInitialTime = 0.0; // The initial state x₀, for IVP definition. const double kInitialState = 0.0; // The default parameters 𝐤₀, for IVP definition. const VectorX<double> kParameters = VectorX<double>::Constant(1, 1.0); // Instantiates a generic IVP for test purposes only, // using a generic ODE dx/dt = -x + k₁, that does not // model (nor attempts to model) any physical process. ScalarInitialValueProblem<double> ivp( [](const double& t, const double& x, const VectorX<double>& k) -> double { unused(t); return -x + k[0]; }, kInitialState, kParameters); // Testing against closed form solution of above's scalar IVP, which // can be written as x(t; [k₁]) = k₁ + (x₀ - k₁) * e^(-(t - t₀)). const double t0 = kInitialTime; const double x0 = kInitialState; const VectorX<double>& k1 = kParameters; const double t1 = kInitialTime + 1.0; EXPECT_NEAR(ivp.Solve(t0, t1), k1[0] + (x0 - k1[0]) * std::exp(-(t1 - t0)), kAccuracy); // Replaces default integrator. const double kMaximumStep = 0.1; const IntegratorBase<double>& default_integrator = ivp.get_integrator(); IntegratorBase<double>* configured_integrator = ivp.reset_integrator<RungeKutta2Integrator<double>>(kMaximumStep); EXPECT_NE(configured_integrator, &default_integrator); EXPECT_EQ(configured_integrator, &ivp.get_integrator()); // Specifies a different parameter vector, but leaves both // initial time and state as defaults. const Eigen::Vector2d k2{1, 5.0}; ScalarInitialValueProblem<double> ivp2( [](const double& t, const double& x, const VectorX<double>& k) -> double { unused(t); return -x + k[0]; }, kInitialState, k2); const double t2 = kInitialTime + 0.3; // Testing against closed form solution of above's scalar IVP, // which can be written as x(t; [k₁]) = k₁ + (x₀ - k₁) * e^(-(t - t₀)). EXPECT_NEAR(ivp2.Solve(t0, t2), k2[0] + (x0 - k2[0]) * std::exp(-(t2 - t0)), kAccuracy); } // Parameterized fixture for testing accuracy of scalar IVP solutions. class ScalarInitialValueProblemAccuracyTest : public ::testing::TestWithParam<double> { protected: void SetUp() { integration_accuracy_ = GetParam(); } // Expected accuracy for numerical integral // evaluation in the relative tolerance sense. double integration_accuracy_{0.}; }; // Accuracy test of the solution for the stored charge Q in an RC // series circuit excited by a sinusoidal voltage source E(t), // where dQ/dt = (E(t) - Q / Cs) / Rs and Q(t₀; [Rs, Cs]) = Q₀. TEST_P(ScalarInitialValueProblemAccuracyTest, StoredCharge) { // The initial time t₀. const double kInitialTime = 0.0; // The initial stored charge Q₀ at time t₀. const double kInitialStoredCharge = 0.0; // The resistance Rs of the resistor and the capacitance Cs // of the capacitor. const double kLowestResistance = 1.0; const double kHighestResistance = 10.0; const double kResistanceStep = 1.0; const double kLowestCapacitance = 1.0; const double kHighestCapacitance = 10.0; const double kCapacitanceStep = 1.0; const double kTotalTime = 1.0; const double kTimeStep = 0.1; const double Q0 = kInitialStoredCharge; const double t0 = kInitialTime; const double tf = kTotalTime; for (double Rs = kLowestResistance; Rs <= kHighestResistance ; Rs += kResistanceStep) { for (double Cs = kLowestCapacitance; Cs <= kHighestCapacitance ; Cs += kCapacitanceStep) { const Eigen::Vector2d parameters{Rs, Cs}; // Instantiates the stored charge scalar IVP. ScalarInitialValueProblem<double> stored_charge_ivp( [](const double& t, const double& q, const VectorX<double>& k) -> double { const double Rs_ = k[0]; const double Cs_ = k[1]; return (std::sin(t) - q / Cs_) / Rs_; }, kInitialStoredCharge, parameters); IntegratorBase<double>& inner_integrator = stored_charge_ivp.get_mutable_integrator(); inner_integrator.set_target_accuracy(integration_accuracy_); const std::unique_ptr<ScalarDenseOutput<double>> stored_charge_approx = stored_charge_ivp.DenseSolve(t0, tf); const double tau = Rs * Cs; const double tau_sq = tau * tau; for (double t = kInitialTime; t <= kTotalTime; t += kTimeStep) { // Tests are performed against the closed form // solution for the scalar IVP described above, which is // Q(t; [Rs, Cs]) = 1/Rs * (τ²/ (1 + τ²) * e^(-t / τ) + // τ / √(1 + τ²) * sin(t - arctan(τ))) // where τ = Rs * Cs for Q(t₀ = 0; [Rs, Cs]) = Q₀ = 0. const double solution = ( tau_sq / (1. + tau_sq) * std::exp(-t / tau) + tau / std::sqrt(1. + tau_sq) * std::sin(t - std::atan(tau))) / Rs; EXPECT_NEAR(stored_charge_ivp.Solve(t0, t), solution, integration_accuracy_) << "Failure solving dQ/dt = (sin(t) - Q / Cs) / Rs using Q(t₀ = " << t0 << "; [Rs, Cs]) = " << Q0 << " for t = " << t << ", Rs = " << Rs << " and Cs = " << Cs << " to an accuracy of " << integration_accuracy_; EXPECT_NEAR(stored_charge_approx->EvaluateScalar(t), solution, integration_accuracy_) << "Failure approximating the solution for" << " dQ/dt = (sin(t) - Q / Cs) / Rs using Q(t₀ = " << t0 << "; [Rs, Cs]) = " << Q0 << " for t = " << t << ", Rs = " << Rs << " and Cs = " << Cs << " to an accuracy of " << integration_accuracy_ << " with solver's continuous extension."; } } } } // Accuracy test of the solution for population growth N, described // by dN/dt = r * N and N(t₀; r) = N₀. TEST_P(ScalarInitialValueProblemAccuracyTest, PopulationGrowth) { // The initial time t₀. const double kInitialTime = 0.0; // The initial population N₀ at time t₀. const double kInitialPopulation = 10.0; // The Malthusian parameter r that shapes the growth of the // population. const double kLowestMalthusParam = 0.1; const double kHighestMalthusParam = 1.0; const double kMalthusParamStep = 0.1; const double kTotalTime = 1.0; const double kTimeStep = 0.1; const double N0 = kInitialPopulation; const double t0 = kInitialTime; const double tf = kTotalTime; for (double r = kLowestMalthusParam; r <= kHighestMalthusParam; r += kMalthusParamStep) { ScalarInitialValueProblem<double> population_growth_ivp( [](const double& t, const double& n, const VectorX<double>& k) -> double { unused(t); return k[0] * n; }, kInitialPopulation, Vector1<double>{r}); IntegratorBase<double>& inner_integrator = population_growth_ivp.get_mutable_integrator(); inner_integrator.set_target_accuracy(integration_accuracy_); const std::unique_ptr<ScalarDenseOutput<double>> population_growth_approx = population_growth_ivp.DenseSolve(t0, tf); for (double t = kInitialTime; t <= kTotalTime; t += kTimeStep) { // Tests are performed against the closed form // solution for the IVP described above, which is // N(t; r) = N₀ * e^(r * t). const double solution = N0 * std::exp(r * t); EXPECT_NEAR(population_growth_ivp.Solve(t0, t), solution, integration_accuracy_) << "Failure solving dN/dt = r * N using N(t₀ = " << t0 << "; r) = " << N0 << " for t = " << t << " and r = " << r << " to an accuracy of " << integration_accuracy_; EXPECT_NEAR(population_growth_approx->EvaluateScalar(t), solution, integration_accuracy_) << "Failure approximating the solution for dN/dt = r * N" << " using N(t₀ = " << t0 << "; r) = " << N0 << " for t = " << t << " and r = " << r << " to an accuracy of " << integration_accuracy_ << " with solver's continuous extension."; } } } INSTANTIATE_TEST_SUITE_P( IncreasingAccuracyScalarInitialValueProblemTests, ScalarInitialValueProblemAccuracyTest, ::testing::Values(1e-1, 1e-2, 1e-3, 1e-4, 1e-5)); } // namespace } // namespace analysis } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/implicit_integrator_test.cc
#include "drake/systems/analysis/implicit_integrator.h" #include <gtest/gtest.h> #include "drake/systems/analysis/test_utilities/spring_mass_system.h" using Eigen::VectorXd; namespace drake { namespace systems { namespace { // Dummy implicit integrator for testing protected methods of // ImplicitIntegrator class. class DummyImplicitIntegrator final : public ImplicitIntegrator<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DummyImplicitIntegrator) DummyImplicitIntegrator(const System<double>& system, Context<double>* context) : ImplicitIntegrator(system, context) {} bool supports_error_estimation() const override { return false; } int get_error_estimate_order() const override { return 0; } using ImplicitIntegrator<double>::IsUpdateZero; // Returns whether DoResetCachedMatrices() has been called. bool get_has_reset_cached_matrices() { return has_reset_cached_matrices_; } private: // There is no stepping so no stats should accumulate. int64_t do_get_num_newton_raphson_iterations() const final { return 0; } int64_t do_get_num_error_estimator_derivative_evaluations() const final { return 0; } int64_t do_get_num_error_estimator_jacobian_evaluations() const final { return 0; } int64_t do_get_num_error_estimator_derivative_evaluations_for_jacobian() const final { return 0; } int64_t do_get_num_error_estimator_newton_raphson_iterations() const final { return 0; } int64_t do_get_num_error_estimator_iteration_matrix_factorizations() const final { return 0; } void DoResetCachedJacobianRelatedMatrices() final { has_reset_cached_matrices_ = true; } bool DoImplicitIntegratorStep(const double& h) override { throw std::logic_error("Dummy integrator not meant to be stepped."); } bool has_reset_cached_matrices_{false}; }; GTEST_TEST(ImplicitIntegratorTest, IsUpdateZero) { const double mass = 1.0; const double spring_k = 1.0; SpringMassSystem<double> dummy_system(spring_k, mass, false /* unforced */); std::unique_ptr<Context<double>> context = dummy_system.CreateDefaultContext(); DummyImplicitIntegrator dummy_integrator(dummy_system, context.get()); // Machine epsilon is used in the tests below. The tolerance used to check // whether a dimension of the update is zero in IsUpdateZero() will be // 10 * eps. eps will also be used to construct the test below. const double eps = std::numeric_limits<double>::epsilon(); // Test the case where the value of interest is unity and the update is near // machine epsilon. The other state and update are set to zero so that these // would *not* cause the update to be treated as *non*-zero. VectorXd xc(2), dxc(2); xc << 1.0, 0.0; dxc << eps * 5, 0.0; EXPECT_TRUE(dummy_integrator.IsUpdateZero(xc, dxc, eps * 10)); // Test the case where the value of interest is large and the update is still // large, but not large enough relative to the value of interest. xc << 1e10, 0.0; dxc << eps * 1e6, 0.0; EXPECT_TRUE(dummy_integrator.IsUpdateZero(xc, dxc, eps * 10)); // Test the case where we have two values of interest, one large and the // other small with both updates "significant". xc << 1e10, 1.0; dxc << 1e0, eps * 1e6; EXPECT_FALSE(dummy_integrator.IsUpdateZero(xc, dxc, eps * 10)); // Verify that a reasonable tolerance is used when a negative or zero // tolerance is used. xc << 1.0, 0.0; dxc << eps, 0.0; EXPECT_TRUE(dummy_integrator.IsUpdateZero(xc, dxc, -1.0)); EXPECT_TRUE(dummy_integrator.IsUpdateZero(xc, dxc, 0.0)); dxc << 0.1, 0.0; EXPECT_FALSE(dummy_integrator.IsUpdateZero(xc, dxc, -1.0)); EXPECT_FALSE(dummy_integrator.IsUpdateZero(xc, dxc, 0.0)); } // This test verifies that if we change the Jacobian computation scheme from // the default scheme (kForwardDifference), then ImplicitIntegrator calls // DoResetCachedMatrices() to reset any cached matrices. GTEST_TEST(ImplicitIntegratorTest, SetComputationSchemeResetsCachedMatrices) { const double mass = 1.0; const double spring_k = 1.0; SpringMassSystem<double> dummy_system(spring_k, mass, false /* unforced */); std::unique_ptr<Context<double>> context = dummy_system.CreateDefaultContext(); DummyImplicitIntegrator dummy_integrator(dummy_system, context.get()); // The default scheme should be kForwardDifference. EXPECT_EQ(dummy_integrator.get_jacobian_computation_scheme(), ImplicitIntegrator<double> ::JacobianComputationScheme::kForwardDifference); // Verify that DoResetCachedMatrices() has not been called yet. EXPECT_FALSE(dummy_integrator.get_has_reset_cached_matrices()); // Set the scheme to something other than kForwardDifference. dummy_integrator.set_jacobian_computation_scheme( ImplicitIntegrator<double>::JacobianComputationScheme::kAutomatic); // Verify that DoResetCachedMatrices() has been called. EXPECT_TRUE(dummy_integrator.get_has_reset_cached_matrices()); // Verify that the scheme has been properly changed. EXPECT_EQ(dummy_integrator.get_jacobian_computation_scheme(), ImplicitIntegrator<double> ::JacobianComputationScheme::kAutomatic); } } // namespace } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/batch_eval_test.cc
#include "drake/systems/analysis/batch_eval.h" #include <cmath> #include <thread> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/systems/primitives/linear_system.h" #include "drake/systems/primitives/symbolic_vector_system.h" namespace drake { namespace systems { namespace analysis { namespace { using symbolic::Expression; using symbolic::Variable; using systems::LinearSystem; GTEST_TEST(BatchEvalUniquePeriodicDiscreteUpdate, BasicTest) { Eigen::Matrix2d A, B; // clang-format off A << 1, 2, 3, 4; B << 5, 6, 7, 8; // clang-format on const Eigen::MatrixXd C(0, 2), D(0, 2); const double time_step = 0.1; LinearSystem<double> system(A, B, C, D, time_step); auto context = system.CreateDefaultContext(); Parallelism parallelize = Parallelism::Max(); const Eigen::RowVector3d times{0, 1, 2}; Eigen::MatrixXd x0(2, 3); Eigen::MatrixXd inputs(2, 3); // clang-format off x0 << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6; inputs << -0.12, -0.34, 0.45, 0.32, 0.14, -0.65; // clang-format on const Eigen::MatrixXd x1_expected = A * x0 + B * inputs; const Eigen::MatrixXd x2_expected = A * x1_expected + B * inputs; int num_time_steps = 1; InputPortIndex input_port_index = system.get_input_port().get_index(); const Eigen::MatrixXd x1 = BatchEvalUniquePeriodicDiscreteUpdate<double>( system, *context, times, x0, inputs, num_time_steps, input_port_index, parallelize); EXPECT_TRUE(CompareMatrices(x1, x1_expected, 1e-14)); const Eigen::RowVector3d times1 = (times.array() + time_step).matrix(); const Eigen::MatrixXd x2 = BatchEvalUniquePeriodicDiscreteUpdate<double>( system, *context, times1, x1, inputs, num_time_steps, input_port_index, parallelize); EXPECT_TRUE(CompareMatrices(x2, x2_expected, 1e-14)); // Compare the results from doing 2 steps one at a time vs two steps via // num_time_steps = 2. EXPECT_TRUE(CompareMatrices( x2_expected, BatchEvalUniquePeriodicDiscreteUpdate<double>( system, *context, times, x0, inputs, 2 /* num_time_steps */, input_port_index, parallelize), 1e-14)); } // Confirm that time-varying dynamics are handled correctly (with multiple time // steps, etc.) GTEST_TEST(BatchEvalUniquePeriodicDiscreteUpdate, TimeVaryingTest) { const Variable t("t"); const Vector1<Variable> x{Variable("x")}; const double time_period = 0.12; // Make a simple time-varying system // x[n+1] = x[n] + t const auto system = SymbolicVectorSystemBuilder() .time(t) .state(x) .dynamics(Vector1<Expression>{x[0] + t}) .time_period(time_period) .Build(); auto context = system->CreateDefaultContext(); const Eigen::RowVector3d times{0, 1, 2}; Eigen::MatrixXd x0(1, 3); x0 << 0.1, 0.2, 0.3; // No inputs are needed here, since there is no input port. Eigen::MatrixXd inputs(0, 3); int num_time_steps = 2; // x1 = x0 + t0 // x2 = x0 + t0 + (t0 + time_step) = x0 + 2*t0 + time_step const Eigen::MatrixXd x2 = BatchEvalUniquePeriodicDiscreteUpdate<double>( *system, *context, times, x0, inputs, num_time_steps); Eigen::MatrixXd x2_expected = x0 + 2 * times + Eigen::RowVector3d::Constant(time_period); EXPECT_TRUE(CompareMatrices(x2, x2_expected, 1e-14)); } GTEST_TEST(BatchEvalTimeDerivatives, BasicTest) { Eigen::Matrix2d A, B; // clang-format off A << 1, 2, 3, 4; B << 5, 6, 7, 8; // clang-format on const Eigen::MatrixXd C(0, 2), D(0, 2); LinearSystem<double> system(A, B, C, D); auto context = system.CreateDefaultContext(); Parallelism parallelize = Parallelism::Max(); const Eigen::RowVector3d times{0, 1, 2}; Eigen::MatrixXd states(2, 3); Eigen::MatrixXd inputs(2, 3); // clang-format off states << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6; inputs << -0.12, -0.34, 0.45, 0.32, 0.14, -0.65; // clang-format on InputPortIndex input_port_index = system.get_input_port().get_index(); const Eigen::MatrixXd xdot = BatchEvalTimeDerivatives<double>( system, *context, times, states, inputs, input_port_index, parallelize); const Eigen::MatrixXd xdot_expected = A * states + B * inputs; EXPECT_TRUE(CompareMatrices(xdot, xdot_expected, 1e-14)); } } // namespace } // namespace analysis } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/simulator_print_stats_test.cc
#include "drake/systems/analysis/simulator_print_stats.h" #include <gtest/gtest.h> #include "drake/systems/primitives/constant_vector_source.h" namespace drake { namespace systems { template <typename T> class SimulatorPrintStatsTest : public::testing::Test {}; using MyTypes = ::testing::Types<double, AutoDiffXd>; TYPED_TEST_SUITE(SimulatorPrintStatsTest, MyTypes); TYPED_TEST(SimulatorPrintStatsTest, Test) { using T = TypeParam; // A no-crash test. Calling PrintSimulatorStatistics should not throw an // error. ConstantVectorSource<T> source(2); Simulator<T> simulator(source); simulator.AdvanceTo(2); PrintSimulatorStatistics(simulator); } } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/simulator_gflags_test.py
import os import subprocess import unittest from python import runfiles class TestSimulatorGflags(unittest.TestCase): def setUp(self): manifest = runfiles.Create() self.dut = manifest.Rlocation( "drake/systems/analysis/simulator_gflags_main") def test(self): result = subprocess.run([ self.dut, "--simulator_integration_scheme=implicit_euler", "--simulator_max_time_step=0.01", "--simulator_accuracy=1E-3", "--simulator_use_error_control=true", "--simulator_target_realtime_rate=1.", "--simulator_publish_every_time_step=true" ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8") self.assertIn("integration_scheme: implicit_euler", result.stdout)
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/monte_carlo_test.cc
#include "drake/systems/analysis/monte_carlo.h" #include <cmath> #include <thread> #include <gtest/gtest.h> #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/framework/vector_system.h" #include "drake/systems/primitives/constant_vector_source.h" #include "drake/systems/primitives/pass_through.h" #include "drake/systems/primitives/random_source.h" namespace drake { namespace systems { namespace analysis { namespace { // Checks that RandomSimulation repeatedly produces the same output sample // when given the same RandomGenerator, but produces different output samples // when given different generators. void CheckConsistentReplay(const SimulatorFactory& make_simulator, const ScalarSystemFunction& output, double final_time) { RandomGenerator generator; // Run a simulation with a snapshot of the generator saved. const RandomGenerator generator_snapshot(generator); const double random_output = RandomSimulation(make_simulator, output, final_time, &generator); // Run a few more random simulators to mix-up the state. Make sure they // give different outputs. for (int i = 0; i < 5; i++) { EXPECT_NE(RandomSimulation(make_simulator, output, final_time, &generator), random_output); } // Reset the generator to our snapshot and confirm that we got our // original result: generator = generator_snapshot; EXPECT_EQ(RandomSimulation(make_simulator, output, final_time, &generator), random_output); } double GetScalarOutput(const System<double>& system, const Context<double>& context) { return system.get_output_port(0) .Eval<BasicVector<double>>(context) .GetAtIndex(0); } // Check that we get the expected deterministic result if our // SimulatorFactory is deterministic. GTEST_TEST(RandomSimulationTest, DeterministicSimulator) { RandomGenerator generator; const double final_time = 0.1; const double value = 1.432; const SimulatorFactory make_simulator = [value](RandomGenerator*) { auto system = std::make_unique<ConstantVectorSource<double>>(value); return std::make_unique<Simulator<double>>(std::move(system)); }; EXPECT_EQ(RandomSimulation(make_simulator, &GetScalarOutput, final_time, &generator), value); } // Ensure that RandomSimulation provides deterministic results when // the "randomness" is in the SimulatorFactory. GTEST_TEST(RandomSimulationTest, WithRandomSimulator) { // Factory for a simple system output value is different in each simulator // (but constant over the duration of each simulation). const SimulatorFactory make_simulator = [](RandomGenerator* generator) { std::normal_distribution<> distribution; auto system = std::make_unique<ConstantVectorSource<double>>( distribution(*generator)); return std::make_unique<Simulator<double>>(std::move(system)); }; const double final_time = 0.1; CheckConsistentReplay(make_simulator, &GetScalarOutput, final_time); } // Simple system that outputs constant scalar, where this scalar is stored in // the discrete state of the system. The scalar value is randomized in // SetRandomState(). class RandomContextSystem : public VectorSystem<double> { public: RandomContextSystem() : VectorSystem(0, 1) { this->DeclareDiscreteState(1); } private: void SetRandomState(const Context<double>& context, State<double>* state, RandomGenerator* generator) const override { std::normal_distribution<> distribution; state->get_mutable_discrete_state(0).SetAtIndex(0, distribution(*generator)); } void DoCalcVectorOutput( const Context<double>& context, const Eigen::VectorBlock<const VectorX<double>>& input, const Eigen::VectorBlock<const VectorX<double>>& state, Eigen::VectorBlock<VectorX<double>>* output) const override { *output = state; } }; // Ensure that RandomSimulation provides correct/deterministic results when // the "randomness" is in the SetRandomContext. GTEST_TEST(RandomSimulationTest, WithRandomContext) { // Factory for a simple system output value is different in each simulator // (but constant over the duration of each simulation). const SimulatorFactory make_simulator = [](RandomGenerator*) { auto system = std::make_unique<RandomContextSystem>(); return std::make_unique<Simulator<double>>(std::move(system)); }; const double final_time = 0.1; CheckConsistentReplay(make_simulator, &GetScalarOutput, final_time); } // Ensure that RandomSimulation provides correct/deterministic results when // the "randomness" comes from random input ports. (Also provides coverage // for using a DiagramBuilder in a SimulatorFactory). GTEST_TEST(RandomSimulationTest, WithRandomInputs) { const SimulatorFactory make_simulator = [](RandomGenerator*) { DiagramBuilder<double> builder; const int kNumOutputs = 1; const double sampling_interval = 0.1; auto random_source = builder.AddSystem<RandomSource<double>>( RandomDistribution::kUniform, kNumOutputs, sampling_interval); auto pass_through = builder.template AddSystem<PassThrough>(kNumOutputs); builder.Connect(random_source->get_output_port(0), pass_through->get_input_port()); builder.ExportOutput(pass_through->get_output_port(), "random"); auto diagram = builder.Build(); return std::make_unique<Simulator<double>>(std::move(diagram)); }; const double final_time = 0.1; CheckConsistentReplay(make_simulator, &GetScalarOutput, final_time); } GTEST_TEST(MonteCarloSimulationTest, BasicTest) { const SimulatorFactory make_simulator = [](RandomGenerator* generator) { auto system = std::make_unique<RandomContextSystem>(); return std::make_unique<Simulator<double>>(std::move(system)); }; const double final_time = 0.1; const int num_samples = 100; const RandomGenerator prototype_generator; RandomGenerator serial_generator(prototype_generator); RandomGenerator parallel_generator(prototype_generator); const auto serial_results = MonteCarloSimulation( make_simulator, &GetScalarOutput, final_time, num_samples, &serial_generator, Parallelism::None()); const auto parallel_results = MonteCarloSimulation( make_simulator, &GetScalarOutput, final_time, num_samples, &parallel_generator, Parallelism::Max()); EXPECT_EQ(serial_results.size(), num_samples); EXPECT_EQ(parallel_results.size(), num_samples); // Check that the results were all different. We only check the serial results // since we check later that serial and parallel results are identical. std::unordered_set<double> serial_outputs; for (const auto& serial_result : serial_results) { serial_outputs.emplace(serial_result.output); } EXPECT_EQ(serial_outputs.size(), serial_results.size()); // Confirm that serial and parallel MonteCarloSimulation produce the same // results, and that they are both reproducible. for (int sample = 0; sample < num_samples; ++sample) { const auto& serial_result = serial_results.at(sample); const auto& parallel_result = parallel_results.at(sample); EXPECT_EQ(serial_result.output, parallel_result.output); RandomGenerator serial_reproduction_generator( serial_result.generator_snapshot); RandomGenerator parallel_reproduction_generator( parallel_result.generator_snapshot); EXPECT_EQ(RandomSimulation(make_simulator, &GetScalarOutput, final_time, &serial_reproduction_generator), serial_result.output); EXPECT_EQ(RandomSimulation(make_simulator, &GetScalarOutput, final_time, &parallel_reproduction_generator), parallel_result.output); } } // Simple system that outputs constant scalar, where this scalar is stored in // the discrete state of the system. The scalar value is randomized in // SetRandomState(). If the state value (cast to int) is odd, DoCalcVectorOutput // throws. class ThrowingRandomContextSystem : public VectorSystem<double> { public: ThrowingRandomContextSystem() : VectorSystem(0, 1) { this->DeclareDiscreteState(1); } private: void SetRandomState(const Context<double>& context, State<double>* state, RandomGenerator* generator) const override { std::normal_distribution<> distribution; state->get_mutable_discrete_state(0).SetAtIndex(0, distribution(*generator)); } void DoCalcVectorOutput( const Context<double>& context, const Eigen::VectorBlock<const VectorX<double>>& input, const Eigen::VectorBlock<const VectorX<double>>& state, Eigen::VectorBlock<VectorX<double>>* output) const override { if ((static_cast<int>(state(0)) % 2) != 0) { throw std::runtime_error("State value is odd"); } else { *output = state; } } }; GTEST_TEST(MonteCarloSimulationExceptionTest, BasicTest) { const SimulatorFactory make_simulator = [](RandomGenerator* generator) { auto system = std::make_unique<ThrowingRandomContextSystem>(); return std::make_unique<Simulator<double>>(std::move(system)); }; const double final_time = 0.1; const int num_samples = 10; const RandomGenerator prototype_generator; RandomGenerator serial_generator(prototype_generator); RandomGenerator parallel_generator(prototype_generator); EXPECT_THROW(MonteCarloSimulation( make_simulator, &GetScalarOutput, final_time, num_samples, &serial_generator, Parallelism::None()), std::exception); EXPECT_THROW(MonteCarloSimulation( make_simulator, &GetScalarOutput, final_time, num_samples, &parallel_generator, Parallelism::Max()), std::exception); } } // namespace } // namespace analysis } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/region_of_attraction_test.cc
#include "drake/systems/analysis/region_of_attraction.h" #include <cmath> #include <gtest/gtest.h> #include "drake/solvers/csdp_solver.h" #include "drake/solvers/mosek_solver.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/primitives/constant_vector_source.h" #include "drake/systems/primitives/symbolic_vector_system.h" namespace drake { namespace systems { namespace analysis { namespace { using std::pow; using symbolic::Expression; using symbolic::Polynomial; using symbolic::Variable; using symbolic::Variables; // Verifies the region of attraction of the origin, x ∈ [-1, 1]. This is // taken from the example in http://underactuated.mit.edu/lyapunov.html . GTEST_TEST(RegionOfAttractionTest, CubicPolynomialTest) { Variable x("x"); const auto system = SymbolicVectorSystemBuilder().state(x).dynamics(-x + pow(x, 3)).Build(); const auto context = system->CreateDefaultContext(); const Expression V = RegionOfAttraction(*system, *context); // V does not use my original variable (unless I pass it in through the // options, but I want to test this case). x = *V.GetVariables().begin(); const Polynomial V_expected{x * x}; EXPECT_TRUE(Polynomial(V).CoefficientsAlmostEqual(V_expected, 1e-6)); // Solve again using the implicit form. RegionOfAttractionOptions options; options.use_implicit_dynamics = true; const Expression V2 = RegionOfAttraction(*system, *context, options); EXPECT_TRUE(Polynomial(V).CoefficientsAlmostEqual(V_expected, 1e-6)); } // Cubic again, but shifted to a non-zero equilibrium. GTEST_TEST(RegionOfAttractionTest, ShiftedCubicPolynomialTest) { Variable x("x"); const double x0 = 2; const auto system = SymbolicVectorSystemBuilder() .state(x) .dynamics(-(x - x0) + pow(x - x0, 3)) .Build(); auto context = system->CreateDefaultContext(); context->SetContinuousState(Vector1d(x0)); const Expression V = RegionOfAttraction(*system, *context); // V does not use my original Variable. x = *V.GetVariables().begin(); const Polynomial V_expected{(x - x0) * (x - x0)}; EXPECT_TRUE(Polynomial(V).CoefficientsAlmostEqual(V_expected, 1e-6)); } // A multivariate polynomial with a non-trivial but known floating-point // solution for the optimal level-set of the candidate Lyapunov function. // From section 7.3 of: // Structured Semidefinite Programs and Semialgebraic Geometry Methods // in Robustness and Optimization. Pablo Parrilo, California Institute of // Technology, Pasadena, CA, May 2000. GTEST_TEST(RegionOfAttractionTest, ParriloExample) { const Variable x("x"); const Variable y("y"); const auto system = SymbolicVectorSystemBuilder() .state({x, y}) .dynamics({-x + y, 0.1 * x - 2 * y - x * x - 0.1 * x * x * x}) .Build(); const auto context = system->CreateDefaultContext(); RegionOfAttractionOptions options; options.lyapunov_candidate = x * x + y * y; options.state_variables = Vector2<symbolic::Variable>(x, y); const Expression V = RegionOfAttraction(*system, *context, options); EXPECT_TRUE(V.GetVariables().IsSubsetOf(Variables({x, y}))); // Level-set reported in the thesis: const double gamma = std::pow(2.66673, 2); const Polynomial V_expected{(x * x + y * y) / gamma}; EXPECT_TRUE(Polynomial(V).CoefficientsAlmostEqual(V_expected, 1e-5)); // Run it again with the lyapunov candidate scaled by a large number to // test the "BalanceQuadraticForms" call (this scaling is the smallest // multiple of 10 that caused Mosek to fail without balancing). if (solvers::MosekSolver::is_available()) { options.lyapunov_candidate *= 1e8; const Expression scaled_V = RegionOfAttraction(*system, *context, options); EXPECT_TRUE(Polynomial(scaled_V).CoefficientsAlmostEqual(V_expected, 1e-6)); } } // The cubic polynomial again, but this time with V=x^4. Tests the case // where the Hessian of Vdot is negative definite at the origin. GTEST_TEST(RegionOfAttractionTest, IndefiniteHessian) { Variable x("x"); const auto system = SymbolicVectorSystemBuilder().state(x).dynamics(-x + pow(x, 3)).Build(); const auto context = system->CreateDefaultContext(); RegionOfAttractionOptions options; options.lyapunov_candidate = 3 * pow(x, 4); options.state_variables = Vector1<Variable>(x); const Expression V = RegionOfAttraction(*system, *context, options); const Polynomial V_expected{pow(x, 4)}; EXPECT_TRUE(Polynomial(V).CoefficientsAlmostEqual(V_expected, 1e-6)); } // Another example from the underactuated lyapunov chapter. U(x) is a // polynomial potential function, and xdot = (U-1)dUdx, which should have // U==1 as the true boundary of the RoA. GTEST_TEST(RegionOfAttractionTest, NonConvexROA) { const Vector2<Variable> x{Variable("x"), Variable("y")}; Eigen::Matrix2d A1, A2; A1 << 1, 2, 3, 4; A2 << -1, 2, -3, 4; // mirror about the y-axis const Expression U{((A1 * x).dot(A1 * x)) * ((A2 * x).dot(A2 * x))}; const RowVector2<Expression> dUdx = U.Jacobian(x); const auto system = SymbolicVectorSystemBuilder() .state(x) .dynamics((U - 1) * dUdx.transpose()) .Build(); const auto context = system->CreateDefaultContext(); RegionOfAttractionOptions options; options.lyapunov_candidate = (x.transpose() * x)(0); options.state_variables = x; // Force the use of CSDP for solving; Mosek and Clarabel are known to fail for // this test, see #12876. We also need a tighter tolerance to pass on macOS. options.solver_id = solvers::CsdpSolver::id(); options.solver_options.emplace().SetOption(solvers::CsdpSolver::id(), "objtol", 1e-9); const Expression V = RegionOfAttraction(*system, *context, options); // Leverage the quadratic form of V to find the boundary point on the // positive x axis. symbolic::Environment env{{x(0), 1}, {x(1), 0}}; const double rho = 1. / V.Evaluate(env); env[x(0)] = std::sqrt(rho); // Confirm that it is on the boundary of V. EXPECT_NEAR(V.Evaluate(env), 1.0, 1e-12); // As an inner approximation of the ROA, It should be inside the boundary // of U(x) <= 1 (but this time with the tolerance of the SDP solver). EXPECT_LE(U.Evaluate(env), 1.0 + 1e-6); } // The CubicPolynomialTest again, but this time with an input port that must be // fixed to zero for the computation to succeed. GTEST_TEST(RegionOfAttractionTest, FixedInput) { Variable x("x"); Variable u("u"); const auto system = SymbolicVectorSystemBuilder() .state(x) .input(u) .dynamics(u - x + pow(x, 3)) .Build(); auto context = system->CreateDefaultContext(); system->get_input_port().FixValue(context.get(), Vector1d::Zero()); const Expression V = RegionOfAttraction(*system, *context); // V does not use my original variable (unless I pass it in through the // options, but I want to test this case). x = *V.GetVariables().begin(); const Polynomial V_expected{x * x}; EXPECT_TRUE(Polynomial(V).CoefficientsAlmostEqual(V_expected, 1e-6)); } // A copy of CubicPolynomicalTest but with the analyzed system embedded into a // diagram with a constant vector source. This confirms that one can apply // RegionOfAttraction to a subsystem. GTEST_TEST(RegionOfAttractionTest, SubSystem) { DiagramBuilder<double> builder; Variable x("x"); Variable y{"y"}; const auto& system = *builder.AddSystem(SymbolicVectorSystemBuilder() .state(x) .dynamics(-x + pow(x, 3) + y) .input(y) .Build()); const auto& value_system = *builder.AddSystem<ConstantVectorSource<double>>(0); builder.Connect(value_system, system); auto diagram = builder.Build(); auto diagram_context = diagram->CreateDefaultContext(); const auto& system_context = diagram->GetMutableSubsystemContext(system, diagram_context.get()); const Expression V = RegionOfAttraction(system, system_context); // V does not use my original variable (unless I pass it in through the // options, but I want to test this case). x = *V.GetVariables().begin(); const Polynomial V_expected{x * x}; EXPECT_TRUE(Polynomial(V).CoefficientsAlmostEqual(V_expected, 1e-6)); } // ẋ = (−x+x³)/(1+x²) has a stable fixed point at the origin with a region of // attraction x ∈ (−1, 1). template <typename T> class RationalPolynomialSystem final : public LeafSystem<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(RationalPolynomialSystem); RationalPolynomialSystem() : LeafSystem<T>(SystemTypeTag<RationalPolynomialSystem>{}) { this->DeclareContinuousState(1); } // Scalar-converting copy constructor. See @ref system_scalar_conversion. template <typename U> explicit RationalPolynomialSystem(const RationalPolynomialSystem<U>& other) : RationalPolynomialSystem() {} private: void DoCalcTimeDerivatives( const systems::Context<T>& context, systems::ContinuousState<T>* derivatives) const override { T x = context.get_continuous_state_vector()[0]; (*derivatives)[0] = (-x + pow(x, 3)) / (1.0 + pow(x, 2)); } void DoCalcImplicitTimeDerivativesResidual( const systems::Context<T>& context, const systems::ContinuousState<T>& proposed_derivatives, EigenPtr<VectorX<T>> residual) const override { T x = context.get_continuous_state_vector()[0]; T xdot = proposed_derivatives[0]; (*residual)[0] = (1.0 + pow(x, 2)) * xdot + x - pow(x, 3); } }; // The region of attraction should be certified with V=x²<1. GTEST_TEST(RegionOfAttractionTest, ImplicitDynamics) { RationalPolynomialSystem<double> system; const auto context = system.CreateDefaultContext(); RegionOfAttractionOptions options; options.use_implicit_dynamics = true; const Expression V = RegionOfAttraction(system, *context, options); Variable x = *V.GetVariables().begin(); const Polynomial V_expected{x * x}; EXPECT_TRUE(Polynomial(V).CoefficientsAlmostEqual(V_expected, 1e-6)); } } // namespace } // namespace analysis } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/simulator_python_internal_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/systems/analysis/simulator.h" #include "drake/systems/analysis/simulator_python_internal.h" /* clang-format on */ #include <gtest/gtest.h> #include "drake/systems/primitives/constant_vector_source.h" namespace drake { namespace systems { namespace internal { namespace { // The python_monitor will increment this mutable, global counter. int global_counter = 0; GTEST_TEST(SimulatorPythonInternalTest, BasicTest) { ConstantVectorSource<double> source(1.0); Simulator<double> simulator(source); // Add a monitor. Initializing or advancing should update the counter. global_counter = 0; auto python_monitor = []() { ++global_counter; }; SimulatorPythonInternal<double>::set_python_monitor(&simulator, python_monitor); simulator.Initialize(); EXPECT_EQ(global_counter, 1); simulator.AdvanceTo(0.2); EXPECT_EQ(global_counter, 2); simulator.AdvanceTo(0.3); EXPECT_EQ(global_counter, 3); // Clearing the monitor means no more counter updates. SimulatorPythonInternal<double>::set_python_monitor(&simulator, nullptr); simulator.Initialize(); simulator.AdvanceTo(0.4); EXPECT_EQ(global_counter, 3); } } // namespace } // namespace internal } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/antiderivative_function_test.cc
#include "drake/systems/analysis/antiderivative_function.h" #include <gtest/gtest.h> #include "drake/common/eigen_types.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/systems/analysis/integrator_base.h" #include "drake/systems/analysis/runge_kutta2_integrator.h" namespace drake { namespace systems { namespace analysis { namespace { // Checks antiderivative function usage with multiple integrators. GTEST_TEST(AntiderivativeFunctionTest, UsingMultipleIntegrators) { // Accuracy upper bound, as not all the integrators used below support // error control. const double kAccuracy = 1e-2; // The lower integration bound v, for function definition. const double kDefaultLowerIntegrationBound = 0.0; // The default parameters 𝐤, for function definition. const VectorX<double> kDefaultParameters = VectorX<double>::Constant(2, 1.0); // Defines an antiderivative function for f(x; 𝐤) = k₁ * x + k₂. AntiderivativeFunction<double> antiderivative_function( [](const double& x, const VectorX<double>& k) -> double { return k[0] * x + k[1]; }, kDefaultParameters); // Testing against closed form solution of above's integral, which // can be written as F(u; 𝐤) = k₀/2 * u^2 + k₁ * u for the specified // integration lower bound. const double u1 = kDefaultLowerIntegrationBound + 10.0; const VectorX<double>& k1 = kDefaultParameters; EXPECT_NEAR( antiderivative_function.Evaluate(kDefaultLowerIntegrationBound, u1), k1[0] / 2 * std::pow(u1, 2.0) + k1[1] * u1, kAccuracy); // Replaces default integrator. const double kMaximumStep = 0.1; const IntegratorBase<double>& default_integrator = antiderivative_function.get_integrator(); using RK2 = RungeKutta2Integrator<double>; IntegratorBase<double>* configured_integrator = antiderivative_function.reset_integrator<RK2>(kMaximumStep); EXPECT_NE(configured_integrator, &default_integrator); EXPECT_EQ(configured_integrator, &antiderivative_function.get_integrator()); const double u2 = kDefaultLowerIntegrationBound + 15.0; // Testing against closed form solution of above's integral, which // can be written as F(u; 𝐤) = k₀/2 * u^2 + k₁ * u for the specified // integration lower bound. EXPECT_NEAR( antiderivative_function.Evaluate(kDefaultLowerIntegrationBound, u2), k1[0] / 2 * std::pow(u2, 2.0) + k1[1] * u2, kAccuracy); } class AntiderivativeFunctionAccuracyTest : public ::testing::TestWithParam<double> { protected: void SetUp() { integration_accuracy_ = GetParam(); } // Expected accuracy for numerical integral // evaluation in the relative tolerance sense. double integration_accuracy_{0.}; }; // Accuracy test for the numerical integration of ∫₀ᵘ xⁿ dx, // parameterized in its order n. TEST_P(AntiderivativeFunctionAccuracyTest, NthPowerMonomialTestCase) { // The order n of the monomial. const VectorX<double> kDefaultParameters = VectorX<double>::Constant(1, 0.0); const int kLowestOrder = 0; const int kHighestOrder = 3; const double kArgIntervalLBound = 0.0; const double kArgIntervalUBound = 10.0; const double kArgStep = 1.0; for (int n = kLowestOrder; n <= kHighestOrder; ++n) { AntiderivativeFunction<double> antiderivative_function( [](const double& x, const VectorX<double>& k) -> double { return std::pow(x, k[0]); }, Vector1<double>{n}); IntegratorBase<double>& inner_integrator = antiderivative_function.get_mutable_integrator(); inner_integrator.set_target_accuracy(integration_accuracy_); const std::unique_ptr<ScalarDenseOutput<double>> antiderivative_function_approx = antiderivative_function.MakeDenseEvalFunction( kArgIntervalLBound, kArgIntervalUBound); for (double u = kArgIntervalLBound; u <= kArgIntervalUBound; u += kArgStep) { // Tests are performed against the closed form solution of // the definite integral, which is (n + 1)⁻¹ uⁿ⁺¹. const double solution = std::pow(u, n + 1.) / (n + 1.); EXPECT_NEAR( antiderivative_function.Evaluate(kArgIntervalLBound, u), solution, integration_accuracy_) << "Failure integrating ∫₀ᵘ xⁿ dx for u = " << u << " and n = " << n << " to an accuracy of " << integration_accuracy_; EXPECT_NEAR( antiderivative_function_approx->EvaluateScalar(u), solution, integration_accuracy_) << "Failure approximating ∫₀ᵘ xⁿ dx for u = " << u << " and n = " << n << " to an accuracy of " << integration_accuracy_ << " with solver's continuous extension."; } } } // Accuracy test for the numerical integration of ∫₀ᵘ tanh(a⋅x) dx, // parameterized in its factor a. TEST_P(AntiderivativeFunctionAccuracyTest, HyperbolicTangentTestCase) { // The factor a in the tangent. const VectorX<double> kDefaultParameters = VectorX<double>::Constant(1, 0.0); const double kParamIntervalLBound = -4.5; const double kParamIntervalUBound = 4.5; const double kParamStep = 1.0; const double kArgIntervalLBound = 0.0; const double kArgIntervalUBound = 10.0; const double kArgStep = 1.0; for (double a = kParamIntervalLBound; a <= kParamIntervalUBound; a += kParamStep) { AntiderivativeFunction<double> antiderivative_function( [](const double& x, const VectorX<double>& k) -> double { return std::tanh(k[0] * x); }, Vector1<double>{a}); IntegratorBase<double>& inner_integrator = antiderivative_function.get_mutable_integrator(); inner_integrator.set_target_accuracy(integration_accuracy_); const std::unique_ptr<ScalarDenseOutput<double>> antiderivative_function_approx = antiderivative_function.MakeDenseEvalFunction( kArgIntervalLBound, kArgIntervalUBound); for (double u = kArgIntervalLBound; u <= kArgIntervalUBound; u += kArgStep) { // Tests are performed against the closed form solution of // the definite integral, which is a⁻¹ ln(cosh(a ⋅ u)). const double solution = std::log(std::cosh(a * u)) / a; EXPECT_NEAR(antiderivative_function.Evaluate(kArgIntervalLBound, u), solution, integration_accuracy_) << "Failure integrating ∫₀ᵘ tanh(a⋅x) dx for" << " u = " << u << " and a = " << a << " to an accuracy of " << integration_accuracy_; EXPECT_NEAR(antiderivative_function_approx->EvaluateScalar(u), solution, integration_accuracy_) << "Failure approximating ∫₀ᵘ tanh(a⋅x) dx for" << " u = " << u << " and a = " << a << " to an accuracy of " << integration_accuracy_ << " with solver's continuous extension."; } } } // Accuracy test for the numerical integration of ∫₀ᵘ [(x + a)⋅(x + b)]⁻¹ dx, // parameterized in its denominator roots (or function poles) a and b. TEST_P(AntiderivativeFunctionAccuracyTest, SecondOrderRationalFunctionTestCase) { // The denominator roots a and b. const VectorX<double> kDefaultParameters = VectorX<double>::Zero(2); const double k1stPoleIntervalLBound = 20.0; const double k1stPoleIntervalUBound = 25.0; const double k1stPoleStep = 1.0; const double k2ndPoleIntervalLBound = 30.0; const double k2ndPoleIntervalUBound = 35.0; const double k2ndPoleStep = 1.0; const double kArgIntervalLBound = 0.0; const double kArgIntervalUBound = 10.0; const double kArgStep = 1.0; for (double a = k1stPoleIntervalLBound; a <= k1stPoleIntervalUBound; a += k1stPoleStep) { for (double b = k2ndPoleIntervalLBound; b <= k2ndPoleIntervalUBound; b += k2ndPoleStep) { AntiderivativeFunction<double> antiderivative_function( [](const double& x, const VectorX<double>& k) -> double { const double a_ = k[0]; const double b_ = k[1]; return 1. / ((x + a_) * (x + b_)); }, Eigen::Vector2d{a, b}); IntegratorBase<double>& inner_integrator = antiderivative_function.get_mutable_integrator(); inner_integrator.set_target_accuracy(GetParam()); const std::unique_ptr<ScalarDenseOutput<double>> antiderivative_function_approx = antiderivative_function.MakeDenseEvalFunction( kArgIntervalLBound, kArgIntervalUBound); for (double u = kArgIntervalLBound; u <= kArgIntervalUBound; u += kArgStep) { // Tests are performed against the closed form solution of the definite // integral, which is (b - a)⁻¹ ln [(b / a) ⋅ (u + a) / (u + b)]. const double solution = std::log((b / a) * ((u + a) / (u + b))) / (b - a); EXPECT_NEAR(antiderivative_function.Evaluate(kArgIntervalLBound, u), solution, integration_accuracy_) << "Failure integrating ∫₀ᵘ [(x + a)⋅(x + b)]⁻¹ dx for" << " u = " << u << ", a = " << a << "and b = " << b << " to an accuracy of " << integration_accuracy_; EXPECT_NEAR(antiderivative_function_approx->EvaluateScalar(u), solution, integration_accuracy_) << "Failure approximating ∫₀ᵘ [(x + a)⋅(x + b)]⁻¹ dx for" << " u = " << u << ", a = " << a << "and b = " << b << " to an accuracy of " << integration_accuracy_ << " with solver's continuous extension."; } } } } // Accuracy test for the numerical integration of ∫₀ᵘ x eⁿˣ dx, // parameterized in its exponent factor n. TEST_P(AntiderivativeFunctionAccuracyTest, ExponentialFunctionTestCase) { // The exponent factor n. const VectorX<double> kDefaultParameters = VectorX<double>::Zero(1); const double kParamIntervalLBound = -4.5; const double kParamIntervalUBound = 4.5; const double kParamStep = 1.0; const double kArgIntervalLBound = 0.0; const double kArgIntervalUBound = 1.0; const double kArgStep = 0.1; for (double n = kParamIntervalLBound; n <= kParamIntervalUBound; n += kParamStep) { AntiderivativeFunction<double> antiderivative_function( [](const double& x, const VectorX<double>& k) -> double { return x * std::exp(k[0] * x); }, Vector1<double>{n}); IntegratorBase<double>& inner_integrator = antiderivative_function.get_mutable_integrator(); inner_integrator.set_target_accuracy(integration_accuracy_); const std::unique_ptr<ScalarDenseOutput<double>> antiderivative_function_approx = antiderivative_function.MakeDenseEvalFunction( kArgIntervalLBound, kArgIntervalUBound); for (double u = kArgIntervalLBound; u <= kArgIntervalUBound; u += kArgStep) { // Tests are performed against the closed form solution of the definite // integral, which is (u / n - 1 / n²) ⋅ e^(n ⋅ u) + 1 / n². const double solution = (u / n - 1. / (n * n)) * std::exp(n * u) + 1. / (n * n); EXPECT_NEAR( antiderivative_function.Evaluate(kArgIntervalLBound, u), solution, integration_accuracy_) << "Failure integrating ∫₀ᵘ x eⁿˣ dx for" << " u = " << u << " and n = " << n << " to an accuracy of " << integration_accuracy_; EXPECT_NEAR(antiderivative_function_approx->EvaluateScalar(u), solution, integration_accuracy_) << "Failure approximating ∫₀ᵘ x eⁿˣ dx for" << " u = " << u << " and n = " << n << " to an accuracy of " << integration_accuracy_ << " with solver's continuous extension."; } } } // Accuracy test for the numerical integration of ∫₀ᵘ x⋅sin(a⋅x) dx, // parameterized in its factor a. TEST_P(AntiderivativeFunctionAccuracyTest, TrigonometricFunctionTestCase) { // The factor a in the sine. const VectorX<double> kDefaultParameters = VectorX<double>::Zero(1); const double kParamIntervalLBound = -4.5; const double kParamIntervalUBound = 4.5; const double kParamStep = 1.0; const double kArgIntervalLBound = 0.0; const double kArgIntervalUBound = 10.0; const double kArgStep = 1.0; for (double a = kParamIntervalLBound; a <= kParamIntervalUBound; a += kParamStep) { AntiderivativeFunction<double> antiderivative_function( [](const double& x, const VectorX<double>& k) -> double { return x * std::sin(k[0] * x); }, Vector1<double>{a}); IntegratorBase<double>& inner_integrator = antiderivative_function.get_mutable_integrator(); inner_integrator.set_target_accuracy(integration_accuracy_); const std::unique_ptr<ScalarDenseOutput<double>> antiderivative_function_approx = antiderivative_function.MakeDenseEvalFunction( kArgIntervalLBound, kArgIntervalUBound); for (double u = kArgIntervalLBound; u <= kArgIntervalUBound; u += kArgStep) { // Tests are performed against the closed form solution of the definite // integral, which is -u ⋅ cos(a ⋅ u) / a + sin(a ⋅ u) / a². const double solution = -u * std::cos(a * u) / a + std::sin(a * u) / (a * a); EXPECT_NEAR(antiderivative_function.Evaluate(kArgIntervalLBound, u), solution, integration_accuracy_) << "Failure integrating ∫₀ᵘ x⋅sin(a⋅x) dx for" << " u = " << u << " and a = " << a << " to an accuracy of " << integration_accuracy_; EXPECT_NEAR(antiderivative_function_approx->EvaluateScalar(u), solution, integration_accuracy_) << "Failure approximating ∫₀ᵘ x⋅sin(a⋅x) dx for" << " u = " << u << " and a = " << a << " to an accuracy of " << integration_accuracy_ << "with solver's continuous extension.";; } } } INSTANTIATE_TEST_SUITE_P(IncreasingAccuracyAntiderivativeFunctionTests, AntiderivativeFunctionAccuracyTest, ::testing::Values(1e-1, 1e-2, 1e-3, 1e-4)); } // namespace } // namespace analysis } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/integrator_base_test.cc
#include "drake/systems/analysis/integrator_base.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/systems/analysis/test_utilities/spring_mass_system.h" namespace drake { namespace systems { namespace { // A class for testing protected integration functions. template <typename T> class DummyIntegrator : public IntegratorBase<T> { DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DummyIntegrator) public: DummyIntegrator(const System<T>& system, Context<T>* context) : IntegratorBase<T>(system, context) {} // Necessary implementations of pure virtual methods. bool supports_error_estimation() const override { return true; } int get_error_estimate_order() const override { return 1; } std::pair<bool, T> CalcAdjustedStepSize(const T& err, const T& step_taken, bool* at_minimum_step_size) const { return IntegratorBase<T>::CalcAdjustedStepSize(err, step_taken, at_minimum_step_size); } // Promote CalcStateChangeNorm() to public. using IntegratorBase<T>::CalcStateChangeNorm; private: // We want the Step function to fail whenever the step size is greater than // or equal to unity (see FixedStepFailureIndicatesSubstepFailure). bool DoStep(const T& step_size) override { Context<T>* context = this->get_mutable_context(); context->SetTime(context->get_time() + step_size); return (step_size < 1.0); } }; // Tests that IntegratorBase::IntegrateNoFurtherThanTime(.) records a substep // failure when running in fixed step mode and stepping fails. GTEST_TEST(IntegratorBaseTest, FixedStepFailureIndicatesSubstepFailure) { // Use the spring-mass system because we need some system (and this one will // do as well as any other). SpringMassSystem<double> spring_mass(10.0, 1.0, false); std::unique_ptr<Context<double>> context = spring_mass.CreateDefaultContext(); DummyIntegrator<double> integrator(spring_mass, context.get()); // Set the integrator to fixed step mode. integrator.set_fixed_step_mode(true); // Verify the statistics are clear before integrating. EXPECT_EQ(integrator.get_num_step_shrinkages_from_substep_failures(), 0); EXPECT_EQ(integrator.get_num_substep_failures(), 0); // Call the integration function. const double arbitrary_time = 1.0; integrator.Initialize(); integrator.IntegrateNoFurtherThanTime(arbitrary_time, arbitrary_time, arbitrary_time); // Verify the step statistics have been updated. We expect DoStep() to be // called just twice. EXPECT_EQ(integrator.get_num_step_shrinkages_from_substep_failures(), 1); EXPECT_EQ(integrator.get_num_substep_failures(), 1); } // Tests that CalcAdjustedStepSize() shrinks the step size when encountering // NaN and Inf. GTEST_TEST(IntegratorBaseTest, CalcAdjustedStepSizeShrinksOnNaNAndInf) { // We expect the shrinkage to be *at least* a factor of two. const double kShrink = 0.5; // Various "errors" that will be passed into CalcAdjustedStepSize. const double zero_error = 0.0; const double nan_error = std::numeric_limits<double>::quiet_NaN(); const double inf_error = std::numeric_limits<double>::infinity(); // Arbitrary step size taken. const double step_taken = 1.0; // The two possible values that the at_minimum_step_size input/output // parameter can take on entry. bool at_minimum_step_size_true_on_entry = true; bool at_minimum_step_size_false_on_entry = false; // Use the spring-mass system (system and context will be unused for this // test). SpringMassSystem<double> spring_mass(10.0, 1.0, false); std::unique_ptr<Context<double>> context = spring_mass.CreateDefaultContext(); DummyIntegrator<double> integrator(spring_mass, context.get()); // Verify that there is no shrinkage for zero error. std::pair<bool, double> result; result = integrator.CalcAdjustedStepSize(zero_error, step_taken, &at_minimum_step_size_true_on_entry); EXPECT_EQ(result.first, true); EXPECT_GE(result.second, step_taken); result = integrator.CalcAdjustedStepSize( zero_error, step_taken, &at_minimum_step_size_false_on_entry); EXPECT_EQ(result.first, true); EXPECT_GE(result.second, step_taken); // Neither should be at the minimum step size. EXPECT_EQ(at_minimum_step_size_true_on_entry, false); EXPECT_EQ(at_minimum_step_size_false_on_entry, false); // Reset the minimum step size Booleans. at_minimum_step_size_true_on_entry = true; at_minimum_step_size_false_on_entry = false; // Verify shrinkage for NaN error. result = integrator.CalcAdjustedStepSize(nan_error, step_taken, &at_minimum_step_size_true_on_entry); EXPECT_EQ(result.first, false); EXPECT_LT(result.second, kShrink * step_taken); result = integrator.CalcAdjustedStepSize( nan_error, step_taken, &at_minimum_step_size_false_on_entry); EXPECT_EQ(result.first, false); EXPECT_LT(result.second, kShrink * step_taken); // Minimum step size should be unchanged. EXPECT_EQ(at_minimum_step_size_true_on_entry, true); EXPECT_EQ(at_minimum_step_size_false_on_entry, false); // Verify shrinkage for Inf error. result = integrator.CalcAdjustedStepSize(inf_error, step_taken, &at_minimum_step_size_true_on_entry); EXPECT_EQ(result.first, false); EXPECT_LT(result.second, kShrink * step_taken); result = integrator.CalcAdjustedStepSize( inf_error, step_taken, &at_minimum_step_size_false_on_entry); EXPECT_EQ(result.first, false); EXPECT_LT(result.second, kShrink * step_taken); // Minimum step size should be unchanged. EXPECT_EQ(at_minimum_step_size_true_on_entry, true); EXPECT_EQ(at_minimum_step_size_false_on_entry, false); } // Tests that CalcStateChangeNorm() propagates NaNs in state. GTEST_TEST(IntegratorBaseTest, DoubleStateChangeNormPropagatesNaN) { // We need a system with q, v, and z variables. Constants and absence of // forcing are arbitrary (irrelevant for this test). SpringMassSystem<double> spring_mass(10.0, 1.0, false); std::unique_ptr<Context<double>> context = spring_mass.CreateDefaultContext(); DummyIntegrator<double> integrator(spring_mass, context.get()); integrator.Initialize(); // Set q = v = z = 0 and verify that the state change norm is zero. ASSERT_EQ(context->get_continuous_state().size(), 3); context->get_mutable_continuous_state()[0] = 0; context->get_mutable_continuous_state()[1] = 0; context->get_mutable_continuous_state()[2] = 0; EXPECT_EQ(integrator.CalcStateChangeNorm(context->get_continuous_state()), 0); // Set q to NaN, and v = z = 0 and verify that NaN is returned from // CalcStateChangeNorm(). using std::isnan; context->get_mutable_continuous_state()[0] = std::numeric_limits<double>::quiet_NaN(); context->get_mutable_continuous_state()[1] = 0; context->get_mutable_continuous_state()[2] = 0; EXPECT_TRUE( isnan(integrator.CalcStateChangeNorm(context->get_continuous_state()))); // Set v to NaN, and q = z = 0 and verify that NaN is returned from // CalcStateChangeNorm(). context->get_mutable_continuous_state()[0] = 0; context->get_mutable_continuous_state()[1] = std::numeric_limits<double>::quiet_NaN(); context->get_mutable_continuous_state()[2] = 0; EXPECT_TRUE( isnan(integrator.CalcStateChangeNorm(context->get_continuous_state()))); // Set v to NaN, and q = z = 0 and verify that NaN is returned from // CalcStateChangeNorm(). context->get_mutable_continuous_state()[0] = 0; context->get_mutable_continuous_state()[1] = 0; context->get_mutable_continuous_state()[2] = std::numeric_limits<double>::quiet_NaN(); EXPECT_TRUE( isnan(integrator.CalcStateChangeNorm(context->get_continuous_state()))); } // Tests that CalcStateChangeNorm() propagates NaNs in state. GTEST_TEST(IntegratorBaseTest, AutoDiffXdStateChangeNormPropagatesNaN) { // We need a system with q, v, and z variables. Constants and absence of // forcing are arbitrary (irrelevant for this test). SpringMassSystem<AutoDiffXd> spring_mass(10.0, 1.0, false); std::unique_ptr<Context<AutoDiffXd>> context = spring_mass.CreateDefaultContext(); DummyIntegrator<AutoDiffXd> integrator(spring_mass, context.get()); integrator.Initialize(); // Set q = v = z = 0 and verify that the state change norm is zero. ASSERT_EQ(context->get_continuous_state().size(), 3); context->get_mutable_continuous_state()[0] = 0; context->get_mutable_continuous_state()[1] = 0; context->get_mutable_continuous_state()[2] = 0; EXPECT_EQ(integrator.CalcStateChangeNorm(context->get_continuous_state()), 0); // Set q to NaN, and v = z = 0 and verify that NaN is returned from // CalcStateChangeNorm(). using std::isnan; context->get_mutable_continuous_state()[0] = std::numeric_limits<double>::quiet_NaN(); context->get_mutable_continuous_state()[1] = 0; context->get_mutable_continuous_state()[2] = 0; EXPECT_TRUE( isnan(integrator.CalcStateChangeNorm(context->get_continuous_state()))); // Set v to NaN, and q = z = 0 and verify that NaN is returned from // CalcStateChangeNorm(). context->get_mutable_continuous_state()[0] = 0; context->get_mutable_continuous_state()[1] = std::numeric_limits<double>::quiet_NaN(); context->get_mutable_continuous_state()[2] = 0; EXPECT_TRUE( isnan(integrator.CalcStateChangeNorm(context->get_continuous_state()))); // Set v to NaN, and q = z = 0 and verify that NaN is returned from // CalcStateChangeNorm(). context->get_mutable_continuous_state()[0] = 0; context->get_mutable_continuous_state()[1] = 0; context->get_mutable_continuous_state()[2] = std::numeric_limits<double>::quiet_NaN(); EXPECT_TRUE( isnan(integrator.CalcStateChangeNorm(context->get_continuous_state()))); } // Check that dense integration handles repeated evaluations, as seen in the // witness isolation use case in Simulator. GTEST_TEST(IntegratorBaseTest, DenseOutputTest) { SpringMassSystem<double> spring_mass(10.0, 1.0, false); std::unique_ptr<Context<double>> context = spring_mass.CreateDefaultContext(); DummyIntegrator<double> integrator(spring_mass, context.get()); integrator.set_fixed_step_mode(true); integrator.Initialize(); EXPECT_EQ(integrator.get_dense_output(), nullptr); integrator.StartDenseIntegration(); const trajectories::PiecewisePolynomial<double>* dense_output = integrator.get_dense_output(); EXPECT_EQ(dense_output->get_number_of_segments(), 0); EXPECT_TRUE(integrator.IntegrateWithSingleFixedStepToTime(0.1)); EXPECT_EQ(dense_output->get_number_of_segments(), 1); EXPECT_TRUE(integrator.IntegrateWithSingleFixedStepToTime(0.2)); EXPECT_EQ(dense_output->get_number_of_segments(), 2); // Now repeat a step, and make sure that I replace rather than append the new // segment. context->SetTime(0.1); EXPECT_TRUE(integrator.IntegrateWithSingleFixedStepToTime(0.15)); EXPECT_EQ(dense_output->get_number_of_segments(), 2); EXPECT_EQ(dense_output->start_time(), 0.0); EXPECT_EQ(dense_output->end_time(), 0.15); context->SetTime(0.2); DRAKE_EXPECT_THROWS_MESSAGE( static_cast<void>(integrator.IntegrateWithSingleFixedStepToTime(0.3)), ".*ConcatenateInTime.*time_offset.*"); } } // namespace } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/runge_kutta3_integrator_test.cc
#include "drake/systems/analysis/runge_kutta3_integrator.h" #include <cmath> #include <gtest/gtest.h> #include "drake/common/eigen_types.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/math/rotation_matrix.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/analysis/runge_kutta2_integrator.h" #include "drake/systems/analysis/test_utilities/cubic_scalar_system.h" #include "drake/systems/analysis/test_utilities/explicit_error_controlled_integrator_test.h" #include "drake/systems/analysis/test_utilities/generic_integrator_test.h" #include "drake/systems/analysis/test_utilities/my_spring_mass_system.h" #include "drake/systems/analysis/test_utilities/quadratic_scalar_system.h" namespace drake { namespace systems { namespace analysis_test { typedef ::testing::Types<RungeKutta3Integrator<double>> Types; // NOLINTNEXTLINE(whitespace/line_length) INSTANTIATE_TYPED_TEST_SUITE_P(My, ExplicitErrorControlledIntegratorTest, Types); INSTANTIATE_TYPED_TEST_SUITE_P(My, PleidesTest, Types); INSTANTIATE_TYPED_TEST_SUITE_P(My, GenericIntegratorTest, Types); // Tests accuracy for integrating the cubic system (with the state at time t // corresponding to f(t) ≡ t³ + t² + 12t + C) over t ∈ [0, 1]. RK3 is a third // order integrator, meaning that it uses the Taylor Series expansion: // f(t+h) ≈ f(t) + hf'(t) + ½h²f''(t) + ⅙h³f'''(t) + O(h⁴) // The formula above indicates that the approximation error will be zero if // f''''(t) = 0, which is true for the cubic equation. GTEST_TEST(RK3IntegratorErrorEstimatorTest, CubicTest) { CubicScalarSystem cubic; auto cubic_context = cubic.CreateDefaultContext(); const double C = cubic.Evaluate(0); cubic_context->SetTime(0.0); cubic_context->get_mutable_continuous_state_vector()[0] = C; RungeKutta3Integrator<double> rk3(cubic, cubic_context.get()); const double t_final = 1.0; rk3.set_maximum_step_size(t_final); rk3.set_fixed_step_mode(true); rk3.Initialize(); ASSERT_TRUE(rk3.IntegrateWithSingleFixedStepToTime(t_final)); // Check for near-exact 3rd-order results. The measure of accuracy is a // tolerance that scales with expected answer at t_final. const double expected_answer = t_final * (t_final * (t_final + 1) + 12) + C; const double allowable_3rd_order_error = expected_answer * std::numeric_limits<double>::epsilon(); const double actual_answer = cubic_context->get_continuous_state_vector()[0]; EXPECT_NEAR(actual_answer, expected_answer, allowable_3rd_order_error); // This integrator calculates error by subtracting a 2nd-order integration // result from a 3rd-order integration result. Since the 2nd-order integrator // has a Taylor series that is accurate to O(h³) and since we have no terms // beyond order h³, halving the step size should improve the error estimate // by a factor of 2³ = 8. We verify this. // First obtain the error estimate using a single step of h. const double err_est_h = rk3.get_error_estimate()->get_vector().GetAtIndex(0); // Now obtain the error estimate using two half steps of h/2. cubic_context->SetTime(0.0); cubic_context->get_mutable_continuous_state_vector()[0] = C; rk3.Initialize(); ASSERT_TRUE(rk3.IntegrateWithSingleFixedStepToTime(t_final/2)); ASSERT_TRUE(rk3.IntegrateWithSingleFixedStepToTime(t_final)); const double err_est_2h_2 = rk3.get_error_estimate()->get_vector().GetAtIndex(0); EXPECT_NEAR(err_est_2h_2, 1.0 / 8 * err_est_h, 25 * std::numeric_limits<double>::epsilon()); } // Tests accuracy for integrating the quadratic system (with the state at time t // corresponding to f(t) ≡ 4t² + 4t + C, where C is the initial state) over // t ∈ [0, 1]. The error estimator from RK3 is // second order, meaning that it uses the Taylor Series expansion: // f(t+h) ≈ f(t) + hf'(t) + ½h²f''(t) + O(h³) // This formula indicates that the approximation error will be zero if // f'''(t) = 0, which is true for the quadratic equation. We check that the // error estimator gives a perfect error estimate for this function. GTEST_TEST(RK3IntegratorErrorEstimatorTest, QuadraticTest) { QuadraticScalarSystem quadratic; auto quadratic_context = quadratic.CreateDefaultContext(); const double C = quadratic.Evaluate(0); quadratic_context->SetTime(0.0); quadratic_context->get_mutable_continuous_state_vector()[0] = C; RungeKutta3Integrator<double> rk3(quadratic, quadratic_context.get()); const double t_final = 1.0; rk3.set_maximum_step_size(t_final); rk3.set_fixed_step_mode(true); rk3.Initialize(); ASSERT_TRUE(rk3.IntegrateWithSingleFixedStepToTime(t_final)); const double err_est = rk3.get_error_estimate()->get_vector().GetAtIndex(0); // Note the very tight tolerance used, which will likely not hold for // arbitrary values of C, t_final, or polynomial coefficients. EXPECT_NEAR(err_est, 0.0, 2 * std::numeric_limits<double>::epsilon()); } } // namespace analysis_test } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/implicit_euler_integrator_test.cc
#include "drake/systems/analysis/implicit_euler_integrator.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/unused.h" #include "drake/systems/analysis/test_utilities/implicit_integrator_test.h" #include "drake/systems/analysis/test_utilities/quadratic_scalar_system.h" namespace drake { namespace systems { namespace analysis_test { // Tests accuracy for integrating the quadratic system (with the state at time t // corresponding to f(t) ≡ 7t² + 7t + f₀, where f₀ is the initial state) over // t ∈ [0, 1]. Since the error estimate has a Taylor series that is // accurate to O(h²) and since we have no terms beyond this order, // halving the step size should improve the error estimate by a factor of 4. // Furthermore, we test that the error estimate gives the exact error, with // both the correct sign and magnitude. // Note: this test differs from RadauIntegratorTest::QuadraticTest in that // the error estimation for the two-stage Radau integrator is third-order // accurate, so that test checks to make sure the error estimate (and error) // are zero, while this integrator has a second-order-accurate error estimate, // so this test checks to make sure the error estimate is exact (not necessarily // zero). GTEST_TEST(ImplicitEulerIntegratorTest, QuadraticSystemErrorEstimatorAccuracy) { QuadraticScalarSystem quadratic(7); auto quadratic_context = quadratic.CreateDefaultContext(); const double C = quadratic.Evaluate(0); quadratic_context->SetTime(0.0); quadratic_context->get_mutable_continuous_state_vector()[0] = C; ImplicitEulerIntegrator<double> ie(quadratic, quadratic_context.get()); // Ensure that the implicit Euler integrator supports error estimation. ASSERT_TRUE(ie.supports_error_estimation()); // Per the description in IntegratorBase::get_error_estimate_order(), this // should return "2", in accordance with the order of the polynomial in the // Big-O term. ASSERT_EQ(ie.get_error_estimate_order(), 2); const double t_final = 1.5; ie.set_maximum_step_size(t_final); ie.set_fixed_step_mode(true); ie.Initialize(); ASSERT_TRUE(ie.IntegrateWithSingleFixedStepToTime(t_final)); const double err_est_h = ie.get_error_estimate()->get_vector().GetAtIndex(0); const double expected_answer = quadratic.Evaluate(t_final); const double actual_answer = quadratic_context->get_continuous_state_vector()[0]; // Verify that the error estimate gets the exact error value. Note the tight // tolerance used. EXPECT_NEAR(err_est_h, actual_answer - expected_answer, 10 * std::numeric_limits<double>::epsilon()); // Now obtain the error estimate using two half-sized steps of h/2, to verify // the error estimate order. quadratic_context->SetTime(0.0); quadratic_context->get_mutable_continuous_state_vector()[0] = C; ie.Initialize(); ASSERT_TRUE(ie.IntegrateWithSingleFixedStepToTime(t_final / 2)); ASSERT_TRUE(ie.IntegrateWithSingleFixedStepToTime(t_final)); const double err_est_2h_2 = ie.get_error_estimate()->get_vector().GetAtIndex(0); // Since the error estimate is second order, the estimate from a half-step // should be a quarter the size for a quadratic system. EXPECT_NEAR(err_est_2h_2, 1.0 / 4 * err_est_h, 10 * std::numeric_limits<double>::epsilon()); // Verify the validity of general statistics. ImplicitIntegratorTest< ImplicitEulerIntegrator<double>>::CheckGeneralStatsValidity(&ie); } // Test the implicit Euler integrator. typedef ::testing::Types<ImplicitEulerIntegrator<double>> MyTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, ImplicitIntegratorTest, MyTypes); } // namespace analysis_test } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/runge_kutta2_integrator_test.cc
#include "drake/systems/analysis/runge_kutta2_integrator.h" #include <cmath> #include <gtest/gtest.h> #include "drake/systems/analysis/test_utilities/my_spring_mass_system.h" namespace drake { namespace systems { namespace { GTEST_TEST(IntegratorTest, MiscAPI) { // Create the spring-mass system. analysis_test::MySpringMassSystem<double> spring_mass(1., 1., 0.); // Setup integration step. const double h = 1e-3; // Create the integrator. RungeKutta2Integrator<double> integrator(spring_mass, h); // Test that setting the target accuracy fails. EXPECT_THROW(integrator.set_target_accuracy(1.0), std::logic_error); EXPECT_THROW(integrator.request_initial_step_size_target(1.0), std::logic_error); // Verifies that starting dense integration (i.e. demanding a dense // output) fails if the integrator has not been initialized yet. EXPECT_THROW(integrator.StartDenseIntegration(), std::logic_error); // Verifies that stopping dense integration (i.e. precluding further updates // of the dense output known to the integrator) fails if it has not // been started (via StartDenseIntegration()) since last Initialize() call // or construction. EXPECT_THROW(integrator.StopDenseIntegration(), std::logic_error); } GTEST_TEST(IntegratorTest, ContextAccess) { // Create the mass spring system. SpringMassSystem<double> spring_mass(1., 1., 0.); // Create a context. auto context = spring_mass.CreateDefaultContext(); // Setup integration step. const double h = 1e-3; // Create the integrator RungeKutta2Integrator<double> integrator(spring_mass, h, context.get()); integrator.get_mutable_context()->SetTime(3.); EXPECT_EQ(integrator.get_context().get_time(), 3.); EXPECT_EQ(context->get_time(), 3.); } /// Verifies error estimation is unsupported. GTEST_TEST(IntegratorTest, ErrorEst) { // Spring-mass system is necessary only to setup the problem. SpringMassSystem<double> spring_mass(1., 1., 0.); const double h = 1e-3; auto context = spring_mass.CreateDefaultContext(); RungeKutta2Integrator<double> integrator( spring_mass, h, context.get()); EXPECT_EQ(integrator.get_error_estimate_order(), 0); EXPECT_EQ(integrator.supports_error_estimation(), false); EXPECT_THROW(integrator.set_fixed_step_mode(false), std::logic_error); EXPECT_THROW(integrator.set_target_accuracy(1e-1), std::logic_error); EXPECT_THROW(integrator.request_initial_step_size_target(h), std::logic_error); } // Checks the validity of integrator statistics. void CheckStatsValidity(RungeKutta2Integrator<double>* integrator) { EXPECT_GE(integrator->get_previous_integration_step_size(), 0.0); EXPECT_GE(integrator->get_largest_step_size_taken(), 0.0); EXPECT_GE(integrator->get_num_steps_taken(), 0); EXPECT_EQ(integrator->get_error_estimate(), nullptr); EXPECT_GT(integrator->get_num_derivative_evaluations(), 0); } // Try a purely continuous system with no sampling. // d^2x/dt^2 = -kx/m // solution to this ODE: x(t) = c1*cos(omega*t) + c2*sin(omega*t) // where omega = sqrt(k/m) // x'(t) = -c1*sin(omega*t)*omega + c2*cos(omega*t)*omega // for t = 0, x(0) = c1, x'(0) = c2*omega GTEST_TEST(IntegratorTest, SpringMassStep) { const double spring_k = 300.0; // N/m const double mass = 2.0; // kg // Create the spring-mass system SpringMassSystem<double> spring_mass(spring_k, mass, 0.); // Create a context. auto context = spring_mass.CreateDefaultContext(); // Create the integrator. const double h = 1.0/1024; RungeKutta2Integrator<double> integrator(spring_mass, h, context.get()); // Setup the initial position and initial velocity. const double initial_position = 0.1; const double initial_velocity = 0.01; // Set initial conditions using integrator's internal Context. spring_mass.set_position(integrator.get_mutable_context(), initial_position); spring_mass.set_velocity(integrator.get_mutable_context(), initial_velocity); // Take all the defaults. integrator.Initialize(); // Build a dense output while integrating the solution. integrator.StartDenseIntegration(); // Integrate for 1 second. const double t_final = 1.0; integrator.IntegrateWithMultipleStepsToTime(t_final); EXPECT_NEAR(context->get_time(), t_final, h); // Should be exact. // Get the final position and velocity. const VectorBase<double>& xc_final = context->get_continuous_state_vector(); double x_final = xc_final.GetAtIndex(0); // Get the closed form solution. double x_final_true, unused_v_final_true; spring_mass.GetClosedFormSolution(initial_position, initial_velocity, t_final, &x_final_true, &unused_v_final_true); // Check the solution. const double xtol = 5e-3; EXPECT_NEAR(x_final_true, x_final, xtol); // Reclaim dense output and prevent further updates to it. std::unique_ptr<trajectories::PiecewisePolynomial<double>> dense_output = integrator.StopDenseIntegration(); // Verify that the built dense output is valid. for (double t = 0; t <= t_final; t += h / 2.) { double x_true, unused_v_true; spring_mass.GetClosedFormSolution(initial_position, initial_velocity, t, &x_true, &unused_v_true); const VectorX<double> x = dense_output->value(t); EXPECT_NEAR(x_true, x(0), xtol); } // Verify that integrator statistics are valid. CheckStatsValidity(&integrator); } // System where the state at t corresponds to the quadratic equation // 4t² + 4t + C, where C is the initial value (the state at t=0). class Quadratic : public LeafSystem<double> { public: Quadratic() { this->DeclareContinuousState(1); } private: void DoCalcTimeDerivatives( const Context<double>& context, ContinuousState<double>* deriv) const override { const double t = context.get_time(); (*deriv)[0] = 8 * t + 4; } }; // Tests accuracy for integrating the quadratic system (with the state at time t // corresponding to f(t) ≡ 4t² + 4t + C, where C is the initial state) over // t ∈ [0, 1]. The RK2 integrator is second order, meaning it uses the Taylor // Series expansion: // f(t+h) ≈ f(t) + hf'(t) + ½h²f''(t) + O(h³) // This formula indicates that the approximation error will be zero if // f'''(t) = 0, which is true for the quadratic equation. We check that the // RK2 integrator is indeed able to obtain the true result. GTEST_TEST(RK3IntegratorErrorEstimatorTest, QuadraticTest) { Quadratic quadratic; auto quadratic_context = quadratic.CreateDefaultContext(); const double C = 0.0; quadratic_context->get_mutable_continuous_state_vector()[0] = C; const double t_final = 1.0; RungeKutta2Integrator<double> rk2( quadratic, t_final, quadratic_context.get()); rk2.set_maximum_step_size(t_final); rk2.set_fixed_step_mode(true); rk2.Initialize(); ASSERT_TRUE(rk2.IntegrateWithSingleFixedStepToTime(t_final)); const double expected_result = t_final * (4 * t_final + 4) + C; EXPECT_NEAR( quadratic_context->get_continuous_state_vector()[0], expected_result, 10 * std::numeric_limits<double>::epsilon()); } GTEST_TEST(IntegratorTest, Symbolic) { using symbolic::Expression; using symbolic::Variable; // Create the mass spring system. SpringMassSystem<Expression> spring_mass(1., 1.); // Set the maximum step size. const double max_h = .01; // Create a context. auto context = spring_mass.CreateDefaultContext(); // Create the integrator. RungeKutta2Integrator<Expression> integrator( spring_mass, max_h, context.get()); integrator.Initialize(); const Variable q("q"); const Variable v("v"); const Variable work("work"); const Variable h("h"); context->SetContinuousState(Vector3<Expression>(q, v, work)); EXPECT_TRUE(integrator.IntegrateWithSingleFixedStepToTime(h)); } } // namespace } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/scalar_view_dense_output_test.cc
#include "drake/systems/analysis/scalar_view_dense_output.h" #include <gtest/gtest.h> #include "drake/common/autodiff.h" #include "drake/common/eigen_types.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/systems/analysis/hermitian_dense_output.h" namespace drake { namespace systems { namespace analysis { namespace { template <typename T> class ScalarViewDenseOutputTest : public ::testing::Test { protected: std::unique_ptr<DenseOutput<T>> CreateDummyDenseOutput() { auto dense_output = std::make_unique<HermitianDenseOutput<T>>(); typename HermitianDenseOutput<T>::IntegrationStep step( this->kInitialTime, this->kInitialState, this->kInitialStateDerivative); step.Extend(this->kFinalTime, this->kFinalState, this->kFinalStateDerivative); dense_output->Update(std::move(step)); dense_output->Consolidate(); return dense_output; } const double kInvalidTime{-1.0}; const double kInitialTime{0.0}; const double kMidTime{0.5}; const double kFinalTime{1.0}; const MatrixX<double> kInitialState{ (MatrixX<double>(3, 1) << 0., 0., 0.).finished()}; const MatrixX<T> kFinalState{ (MatrixX<double>(3, 1) << 1., 10., 100.).finished()}; const MatrixX<double> kInitialStateDerivative{ (MatrixX<double>(3, 1) << 0., 1., 0.).finished()}; const MatrixX<double> kFinalStateDerivative{ (MatrixX<double>(3, 1) << 1., 0., 1.).finished()}; const int kValidElementIndex{0}; const int kInvalidElementIndex{10}; }; typedef ::testing::Types<double, AutoDiffXd> ExtensionTypes; TYPED_TEST_SUITE(ScalarViewDenseOutputTest, ExtensionTypes); // Checks that ScalarViewDenseOutput properly wraps a // DenseOutput instance. TYPED_TEST(ScalarViewDenseOutputTest, ExtensionConsistency) { // Verifies that passing a null base dense output results in an error. DRAKE_EXPECT_THROWS_MESSAGE( ScalarViewDenseOutput<TypeParam>( std::unique_ptr<HermitianDenseOutput<TypeParam>>(), this->kValidElementIndex), ".*dense output.*is null.*"); // Verifies that views to invalid elements result in an error. DRAKE_EXPECT_THROWS_MESSAGE( ScalarViewDenseOutput<TypeParam>( this->CreateDummyDenseOutput(), this->kInvalidElementIndex), ".*out of.*dense output.*range.*"); // Instantiates scalar continuous extension properly. ScalarViewDenseOutput<TypeParam> dense_output( this->CreateDummyDenseOutput(), this->kValidElementIndex); // Retrieves dummy base continuous extension. const DenseOutput<TypeParam>* base_output = dense_output.get_base_output(); // Checks basic getters for consistency. EXPECT_EQ(dense_output.is_empty(), base_output->is_empty()); EXPECT_EQ(dense_output.start_time(), base_output->start_time()); EXPECT_EQ(dense_output.end_time(), base_output->end_time()); EXPECT_EQ(dense_output.size(), 1); // Checks evaluation preconditions. DRAKE_EXPECT_THROWS_MESSAGE( dense_output.Evaluate(this->kInvalidTime), ".*[Tt]ime.*out of.*dense output.*domain.*"); // Compares evaluations for consistency. EXPECT_EQ( dense_output.EvaluateScalar(this->kInitialTime), base_output->EvaluateNth(this->kInitialTime, this->kValidElementIndex)); EXPECT_EQ( dense_output.EvaluateScalar(this->kMidTime), base_output->EvaluateNth(this->kMidTime, this->kValidElementIndex)); EXPECT_EQ( dense_output.EvaluateScalar(this->kFinalTime), base_output->EvaluateNth(this->kFinalTime, this->kValidElementIndex)); } } // namespace } // namespace analysis } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/simulator_denorm_test.cc
#include <limits> #include <gtest/gtest.h> #include "drake/systems/analysis/simulator.h" namespace drake { namespace systems { namespace { // This test has to be segregated so that we can prevent valgrind // from running on it. The odd floating point register instructions are // not emulated in valgrind. From Valgrind manual: // // Valgrind has the following limitations in its implementation of x86/AMD64 // SSE2 FP arithmetic, relative to IEEE754 ... SSE2 has control bits which // make it treat denormalised numbers ... Valgrind detects, *ignores*, and // can warn about, attempts to enable either mode. // http://valgrind.org/docs/manual/manual-core.html#manual-core.limits // // The "ignored" part above would cause one of the tests below to fail. // The purpose of this test is to verify that the GetPreviousNormalizedValue() // method is not sensitive to the setting of floating point modes that affect // treatment of denormalized numbers. We do not necessarily have control over // those settings so want to make sure they don't matter. GTEST_TEST(SimulatorTest, PreviousNormalizedValueTest) { // Do the tests with the "denormalized numbers treated as zero" (DAZ) and // "denormalized numbers flushed to zero" (FTZ) modes enabled. These modes // are activated when shared libraries are built using the -ffast-math option // in gcc. #ifdef __x86_64__ const volatile double denorm_num = std::numeric_limits<double>::denorm_min(); const unsigned MXCSR_DAZ = (1 << 6); const unsigned MXCSR_FTZ = (1 << 15); const unsigned mxcsr = __builtin_ia32_stmxcsr() | MXCSR_DAZ | MXCSR_FTZ; __builtin_ia32_ldmxcsr(mxcsr); // Verify that the flags were set as expected. EXPECT_EQ(denorm_num, 0.0); #endif const double min_double = std::numeric_limits<double>::min(); EXPECT_EQ(internal::GetPreviousNormalizedValue(0.0), -min_double); EXPECT_EQ(internal::GetPreviousNormalizedValue(min_double/2), -min_double); EXPECT_EQ(internal::GetPreviousNormalizedValue(min_double), 0.0); EXPECT_EQ(internal::GetPreviousNormalizedValue(-min_double/2), -min_double); EXPECT_LE(internal::GetPreviousNormalizedValue(-min_double), -min_double); EXPECT_LE(internal::GetPreviousNormalizedValue(1.0), 1.0); EXPECT_NEAR(internal::GetPreviousNormalizedValue(1.0), 1.0, std::numeric_limits<double>::epsilon()); // Since mxcsr has the flags set, XORing against those flags will set them // to zero. #ifdef __x86_64__ __builtin_ia32_ldmxcsr(mxcsr ^ MXCSR_DAZ ^ MXCSR_FTZ); // Verify that the flags are set as expected. EXPECT_NE(denorm_num, 0.0); EXPECT_NE(std::numeric_limits<double>::min() / 2, 0.0); #endif // Do the tests again now that DAZ and FTZ modes are disabled. EXPECT_EQ(internal::GetPreviousNormalizedValue(0.0), -min_double); EXPECT_EQ(internal::GetPreviousNormalizedValue(min_double/2), -min_double); EXPECT_EQ(internal::GetPreviousNormalizedValue(min_double), 0.0); EXPECT_EQ(internal::GetPreviousNormalizedValue(-min_double/2), -min_double); EXPECT_LE(internal::GetPreviousNormalizedValue(-min_double), -min_double); EXPECT_LE(internal::GetPreviousNormalizedValue(1.0), 1.0); EXPECT_NEAR(internal::GetPreviousNormalizedValue(1.0), 1.0, std::numeric_limits<double>::epsilon()); } } // namespace } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/lyapunov_test.cc
#include "drake/systems/analysis/lyapunov.h" #include <cmath> #include <gtest/gtest.h> #include "drake/examples/pendulum/pendulum_plant.h" #include "drake/systems/framework/vector_system.h" namespace drake { namespace systems { namespace analysis { namespace { using symbolic::Variable; using symbolic::Expression; /// Cubic Polynomial System: /// ẋ = -x + x³ /// y = x class CubicPolynomialSystem : public systems::VectorSystem<double> { public: CubicPolynomialSystem() : systems::VectorSystem<double>(0, 0) { // Zero inputs, zero outputs. this->DeclareContinuousState(1); // One state variable. } private: // ẋ = -x + x³ virtual void DoCalcVectorTimeDerivatives( const systems::Context<double>&, const Eigen::VectorBlock<const Eigen::VectorXd>&, const Eigen::VectorBlock<const Eigen::VectorXd>& state, Eigen::VectorBlock<Eigen::VectorXd>* derivatives) const { using std::pow; (*derivatives)(0) = -state(0) + pow(state(0), 3.0); } }; VectorX<AutoDiffXd> cubic_bases(VectorX<AutoDiffXd> x) { return Vector1<AutoDiffXd>{x.dot(x)}; } // Verifies by only taking samples inside the region of attraction of the // origin, x ∈ [-1, 1]. This is taken from the example in // http://underactuated.mit.edu/underactuated.html?chapter=lyapunov . GTEST_TEST(LyapunovTest, CubicPolynomialTest) { CubicPolynomialSystem cubic; auto context = cubic.CreateDefaultContext(); Eigen::RowVectorXd x_samples = Eigen::RowVectorXd::LinSpaced(21, -1., 1.); Eigen::VectorXd params = SampleBasedLyapunovAnalysis( cubic, *context, &cubic_bases, x_samples, Vector1d{0.}); // Make sure that the solver found some reasonable, well-conditioned answer. EXPECT_GE(params(0), .1); EXPECT_LE(params(0), 10.); } template <typename T> VectorX<T> pendulum_bases(const VectorX<T>& x) { const T s = sin(x[0]); const T c = cos(x[0]); const T qd = x[1]; VectorX<T> monomials(9); monomials << 1, s, c, qd, s * s, s * c, s * qd, c * qd, qd * qd; return monomials; } GTEST_TEST(LyapunovTest, PendulumSampleBasedLyapunov) { examples::pendulum::PendulumPlant<double> pendulum; auto context = pendulum.CreateDefaultContext(); pendulum.get_input_port().FixValue(context.get(), 0.0); Eigen::VectorXd q_samples = Eigen::VectorXd::LinSpaced(31, -1.5 * M_PI, 1.5 * M_PI); Eigen::VectorXd qd_samples = Eigen::VectorXd::LinSpaced(21, -10., 10.); Eigen::Matrix2Xd x_samples(2, q_samples.size() * qd_samples.size()); int xi = 0; for (int qi = 0; qi < q_samples.size(); qi++) { for (int qdi = 0; qdi < qd_samples.size(); qdi++) { x_samples.col(xi++) = Eigen::Vector2d{q_samples(qi), qd_samples(qdi)}; } } // V(0) = 0. const Eigen::Vector2d x_zero = Eigen::Vector2d::Zero(); Eigen::VectorXd params = SampleBasedLyapunovAnalysis( pendulum, *context, &pendulum_bases<AutoDiffXd>, x_samples, x_zero); // Zero the small coefficients, for textual display. for (int i = 0; i < params.size(); i++) { if (fabs(params(i)) < 1e-4) { params(i) = 0.; } } // Check if V ends up near a constant factor times mechanical energy: const auto& p = pendulum.get_parameters(*context); Eigen::VectorXd energy_params = Eigen::VectorXd::Zero(9); energy_params(0) = p.mass() * p.gravity() * p.length(); energy_params(2) = -p.mass() * p.gravity() * p.length(); energy_params(8) = p.mass() * p.length() * p.length(); const double factor = energy_params(0) / params(0); params *= factor; EXPECT_NEAR(params[2], energy_params[2], 1e-4); Vector2<Expression> state{Variable("q"), Variable("qd")}; drake::log()->info( "E = " + energy_params.dot(pendulum_bases<Expression>(state)).to_string()); drake::log()->info("V = " + params.dot(pendulum_bases<Expression>(state)).to_string()); } } // namespace } // namespace analysis } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/runge_kutta5_integrator_test.cc
#include "drake/systems/analysis/runge_kutta5_integrator.h" #include <cmath> #include <gtest/gtest.h> #include "drake/common/eigen_types.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/math/rotation_matrix.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/analysis/test_utilities/explicit_error_controlled_integrator_test.h" #include "drake/systems/analysis/test_utilities/generic_integrator_test.h" #include "drake/systems/analysis/test_utilities/my_spring_mass_system.h" #include "drake/systems/analysis/test_utilities/quartic_scalar_system.h" #include "drake/systems/analysis/test_utilities/quintic_scalar_system.h" namespace drake { namespace systems { namespace analysis_test { typedef ::testing::Types<RungeKutta5Integrator<double>> Types; // NOLINTNEXTLINE(whitespace/line_length) INSTANTIATE_TYPED_TEST_SUITE_P(My, ExplicitErrorControlledIntegratorTest, Types); INSTANTIATE_TYPED_TEST_SUITE_P(My, PleidesTest, Types); INSTANTIATE_TYPED_TEST_SUITE_P(My, GenericIntegratorTest, Types); // Tests accuracy for integrating the quintic system (with the state at time t // corresponding to f(t) ≡ t⁵ + 2t⁴ + 3t³ + 4t² + 5t + C) over t ∈ [0, 1]. // RK5 is a fifth order integrator, meaning that it uses the Taylor Series // expansion: f(t+h) ≈ f(t) + hf'(t) + ½h²f''(t) + ⅙h³f'''(t) + ... + h⁵/120 // f'''''(t) + O(h⁶). The formula above indicates that the approximation error // will be zero if d⁶f/dt⁶ = 0, which is true for the quintic equation. GTEST_TEST(RK5IntegratorErrorEstimatorTest, QuinticTest) { QuinticScalarSystem quintic; auto quintic_context = quintic.CreateDefaultContext(); const double C = quintic.Evaluate(0); quintic_context->SetTime(0.0); quintic_context->get_mutable_continuous_state_vector()[0] = C; RungeKutta5Integrator<double> rk5(quintic, quintic_context.get()); const double t_final = 1.0; rk5.set_maximum_step_size(t_final); rk5.set_fixed_step_mode(true); rk5.Initialize(); ASSERT_TRUE(rk5.IntegrateWithSingleFixedStepToTime(t_final)); // Check for near-exact 5th-order results. The measure of accuracy is a // tolerance that scales with expected answer at t_final. const double expected_answer = t_final * (t_final * (t_final * (t_final * (t_final + 2) + 3) + 4) + 5) + 6; const double allowable_5th_order_error = expected_answer * std::numeric_limits<double>::epsilon(); const double actual_answer = quintic_context->get_continuous_state_vector()[0]; EXPECT_NEAR(actual_answer, expected_answer, allowable_5th_order_error); // This integrator calculates error by subtracting a 4th-order integration // result from a 5th-order integration result. Since the 4th-order integrator // has a Taylor series that is accurate to O(h⁵) and since we have no terms // beyond order h⁵, halving the step size should improve the error estimate // by a factor of 2⁵ = 32. We verify this. // First obtain the error estimate using a single step of h. Note that the // actual integration error is essentially zero, per the check above. const double err_est_h = rk5.get_error_estimate()->get_vector().GetAtIndex(0); // Now obtain the error estimate using two half steps of h/2. quintic_context->SetTime(0.0); quintic_context->get_mutable_continuous_state_vector()[0] = C; rk5.Initialize(); ASSERT_TRUE(rk5.IntegrateWithSingleFixedStepToTime(t_final / 2)); ASSERT_TRUE(rk5.IntegrateWithSingleFixedStepToTime(t_final)); const double err_est_2h_2 = rk5.get_error_estimate()->get_vector().GetAtIndex(0); EXPECT_NEAR(err_est_2h_2, 1.0 / 32 * err_est_h, 10 * std::numeric_limits<double>::epsilon()); } // Tests accuracy for integrating the quartic system (with the state at time t // corresponding to f(t) ≡ t⁴ + 2t³ + 3t² + 4t + C, where C is the initial // state) over t ∈ [0, 1]. The error estimator from RK5 is fourth order, meaning // that it uses the Taylor Series expansion: f(t+h) ≈ f(t) + hf'(t) + ½h²f''(t) // + ... + h⁴/24 f''''(t) + O(h⁵). This formula indicates that the approximation // error will be zero if d⁵f/dt⁵ = 0, which is true for the quartic equation. We // check that the error estimator gives a perfect error estimate for this // function. GTEST_TEST(RK5IntegratorErrorEstimatorTest, QuarticTest) { QuarticScalarSystem quartic; auto quartic_context = quartic.CreateDefaultContext(); const double C = quartic.Evaluate(0); quartic_context->SetTime(0.0); quartic_context->get_mutable_continuous_state_vector()[0] = C; RungeKutta5Integrator<double> rk5(quartic, quartic_context.get()); const double t_final = 1.0; rk5.set_maximum_step_size(t_final); rk5.set_fixed_step_mode(true); rk5.Initialize(); ASSERT_TRUE(rk5.IntegrateWithSingleFixedStepToTime(t_final)); const double err_est = rk5.get_error_estimate()->get_vector().GetAtIndex(0); // Note the very tight tolerance used, which will likely not hold for // arbitrary values of C, t_final, or polynomial coefficients. EXPECT_NEAR(err_est, 0.0, 2 * std::numeric_limits<double>::epsilon()); } } // namespace analysis_test } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/analysis
/home/johnshepherd/drake/systems/analysis/test/explicit_euler_integrator_test.cc
#include "drake/systems/analysis/explicit_euler_integrator.h" #include <cmath> #include <gtest/gtest.h> #include "drake/common/test_utilities/expect_no_throw.h" #include "drake/systems/analysis/test_utilities/my_spring_mass_system.h" namespace drake { namespace systems { namespace { GTEST_TEST(IntegratorTest, MiscAPI) { SpringMassSystem<double> spring_mass_dbl(1., 1., 0.); SpringMassSystem<AutoDiffXd> spring_mass_ad(1., 1., 0.); // Setup the integration step size. const double h = 1e-3; // Create a context. auto context_dbl = spring_mass_dbl.CreateDefaultContext(); auto context_ad = spring_mass_ad.CreateDefaultContext(); // Create the integrator as a double and as an autodiff type ExplicitEulerIntegrator<double> int_dbl(spring_mass_dbl, h, context_dbl.get()); ExplicitEulerIntegrator<AutoDiffXd> int_ad(spring_mass_ad, h, context_ad.get()); // Test that setting the target accuracy or initial step size target fails. EXPECT_THROW(int_dbl.set_target_accuracy(1.0), std::logic_error); EXPECT_THROW(int_dbl.request_initial_step_size_target(1.0), std::logic_error); // Verify that attempting to integrate in variable step mode fails. EXPECT_THROW(int_dbl.IntegrateWithMultipleStepsToTime(1.0), std::logic_error); } GTEST_TEST(IntegratorTest, ContextAccess) { // Create the mass spring system. SpringMassSystem<double> spring_mass(1., 1., 0.); // Setup the integration step size. const double h = 1e-3; // Create a context. auto context = spring_mass.CreateDefaultContext(); // Create the integrator. ExplicitEulerIntegrator<double> integrator( spring_mass, h, context.get()); // Use default Context. integrator.get_mutable_context()->SetTime(3.); EXPECT_EQ(integrator.get_context().get_time(), 3.); EXPECT_EQ(context->get_time(), 3.);\ integrator.reset_context(nullptr); EXPECT_THROW(integrator.Initialize(), std::logic_error); const double t_final = context->get_time() + h; EXPECT_THROW(integrator.IntegrateNoFurtherThanTime( t_final, t_final, t_final), std::logic_error); } /// Checks that the integrator can catch invalid h's. GTEST_TEST(IntegratorTest, InvalidDts) { // Spring-mass system is necessary only to setup the problem. SpringMassSystem<double> spring_mass(1., 1., 0.); const double h = 1e-3; auto context = spring_mass.CreateDefaultContext(); ExplicitEulerIntegrator<double> integrator( spring_mass, h, context.get()); integrator.Initialize(); const double t_final = context->get_time() + h; DRAKE_EXPECT_NO_THROW( integrator.IntegrateNoFurtherThanTime(t_final, t_final, t_final)); EXPECT_THROW(integrator. IntegrateNoFurtherThanTime(t_final, -1, t_final), std::logic_error); EXPECT_THROW(integrator. IntegrateNoFurtherThanTime(-1, t_final, t_final), std::logic_error); EXPECT_THROW(integrator. IntegrateNoFurtherThanTime(t_final, t_final, -1), std::logic_error); } /// Verifies error estimation is unsupported. GTEST_TEST(IntegratorTest, AccuracyEstAndErrorControl) { // Spring-mass system is necessary only to setup the problem. SpringMassSystem<double> spring_mass(1., 1., 0.); const double h = 1e-3; auto context = spring_mass.CreateDefaultContext(); ExplicitEulerIntegrator<double> integrator( spring_mass, h, context.get()); EXPECT_EQ(integrator.get_error_estimate_order(), 0); EXPECT_EQ(integrator.supports_error_estimation(), false); EXPECT_THROW(integrator.set_target_accuracy(1e-1), std::logic_error); EXPECT_THROW(integrator.request_initial_step_size_target(h), std::logic_error); } // Verifies that the stepping works with large magnitude times and small // magnitude step sizes. GTEST_TEST(IntegratorTest, MagDisparity) { const double spring_k = 300.0; // N/m const double mass = 2.0; // kg // Create the spring-mass system. SpringMassSystem<double> spring_mass(spring_k, mass, 0.); // Create a context. auto context = spring_mass.CreateDefaultContext(); // Set a large magnitude time. context->SetTime(1e10); // Setup the integration size and infinity. const double h = 1e-6; // Create the integrator. ExplicitEulerIntegrator<double> integrator( spring_mass, h, context.get()); // Use default Context. // Take all the defaults. integrator.Initialize(); // Take a fixed integration step. ASSERT_TRUE(integrator.IntegrateWithSingleFixedStepToTime( context->get_time() + h)); } // Try a purely continuous system with no sampling. // d^2x/dt^2 = -kx/m // solution to this ODE: x(t) = c1*cos(omega*t) + c2*sin(omega*t) // where omega = sqrt(k/m) // x'(t) = -c1*sin(omega*t)*omega + c2*cos(omega*t)*omega // for t = 0, x(0) = c1, x'(0) = c2*omega GTEST_TEST(IntegratorTest, SpringMassStep) { const double spring_k = 300.0; // N/m const double mass = 2.0; // kg // Create the spring-mass system. SpringMassSystem<double> spring_mass(spring_k, mass, 0.); // Create a context. auto context = spring_mass.CreateDefaultContext(); // Setup the integration size and infinity. const double h = 1e-6; const double inf = std::numeric_limits<double>::infinity(); // Create the integrator. ExplicitEulerIntegrator<double> integrator( spring_mass, h, context.get()); // Use default Context. // Setup the initial position and initial velocity. const double initial_position = 0.1; const double initial_velocity = 0.01; const double omega = std::sqrt(spring_k / mass); // Set initial condition. spring_mass.set_position(context.get(), initial_position); // Take all the defaults. integrator.Initialize(); // Setup c1 and c2 for ODE constants. const double c1 = initial_position; const double c2 = initial_velocity / omega; // Integrate for 1 second. const double t_final = 1.0; double t; for (t = 0.0; std::abs(t - t_final) > h; t += h) integrator.IntegrateNoFurtherThanTime(inf, inf, t_final); EXPECT_NEAR(context->get_time(), t, h); // Should be exact. // Get the final position. const double x_final = context->get_continuous_state().get_vector().GetAtIndex(0); // Check the solution. EXPECT_NEAR(c1 * std::cos(omega * t) + c2 * std::sin(omega * t), x_final, 5e-3); // Verify that integrator statistics are valid EXPECT_GE(integrator.get_previous_integration_step_size(), 0.0); EXPECT_GE(integrator.get_largest_step_size_taken(), 0.0); EXPECT_GE(integrator.get_num_steps_taken(), 0); EXPECT_EQ(integrator.get_error_estimate(), nullptr); EXPECT_GT(integrator.get_num_derivative_evaluations(), 0); } GTEST_TEST(IntegratorTest, StepSize) { const double infinity = std::numeric_limits<double>::infinity(); // Create the mass spring system. SpringMassSystem<double> spring_mass(1., 1., 0.); // Set the maximum step size. const double max_h = .01; // Create a context. auto context = spring_mass.CreateDefaultContext(); context->SetTime(0.0); double t = 0.0; // Create the integrator. ExplicitEulerIntegrator<double> integrator( spring_mass, max_h, context.get()); integrator.Initialize(); // The step ends on the next publish time. { const double publish_dt = 0.005; const double publish_time = context->get_time() + publish_dt; const double update_dt = 0.007; const double update_time = context->get_time() + update_dt; typename IntegratorBase<double>::StepResult result = integrator.IntegrateNoFurtherThanTime( publish_time, update_time, infinity); EXPECT_EQ(IntegratorBase<double>::kReachedPublishTime, result); EXPECT_EQ(publish_dt, context->get_time()); t = context->get_time(); } // The step ends on the next update time. { const double publish_dt = 0.0013; const double publish_time = context->get_time() + publish_dt; const double update_dt = 0.0011; const double update_time = context->get_time() + update_dt; typename IntegratorBase<double>::StepResult result = integrator.IntegrateNoFurtherThanTime( publish_time, update_time, infinity); EXPECT_EQ(IntegratorBase<double>::kReachedUpdateTime, result); EXPECT_EQ(t + update_dt, context->get_time()); t = context->get_time(); } // The step ends on the max step time, because both the publish and update // times are too far in the future. { const double publish_dt = 0.17; const double publish_time = context->get_time() + publish_dt; const double update_dt = 0.19; const double update_time = context->get_time() + update_dt; typename IntegratorBase<double>::StepResult result = integrator.IntegrateNoFurtherThanTime( publish_time, update_time, infinity); EXPECT_EQ(IntegratorBase<double>::kTimeHasAdvanced, result); EXPECT_EQ(t + max_h, context->get_time()); t = context->get_time(); } // The step ends on the next update time, even though it's a little larger // than the max step time, because the max step time stretches. // TODO(edrumwri): This test is brittle because it assumes that the stretch // "factor" is 1%. Update when stretch is programmatically // settable. { const double publish_dt = 42.0; const double publish_time = context->get_time() + publish_dt; const double update_dt = 0.01001; const double update_time = context->get_time() + update_dt; typename IntegratorBase<double>::StepResult result = integrator.IntegrateNoFurtherThanTime( publish_time, update_time, infinity); EXPECT_EQ(IntegratorBase<double>::kReachedUpdateTime, result); EXPECT_EQ(t + update_dt, context->get_time()); t = context->get_time(); } // The step ends on the simulation end time. { const double boundary_dt = 0.0009; const double boundary_time = context->get_time() + boundary_dt; ASSERT_TRUE(integrator.IntegrateWithSingleFixedStepToTime(boundary_time)); EXPECT_EQ(t + boundary_dt, context->get_time()); t = context->get_time(); } // The step ends on the simulation end time because it's shortest. { const double publish_dt = 0.0013; const double publish_time = context->get_time() + publish_dt; const double update_dt = 0.0011; const double update_time = context->get_time() + update_dt; const double boundary_dt = 0.0009; const double boundary_time = context->get_time() + boundary_dt; typename IntegratorBase<double>::StepResult result = integrator.IntegrateNoFurtherThanTime( publish_time, update_time, boundary_time); EXPECT_EQ(IntegratorBase<double>::kReachedBoundaryTime, result); EXPECT_EQ(t + boundary_dt, context->get_time()); t = context->get_time(); } // The step must still end on the desired step end time. This tests that // no stretching to update_dt is done. // TODO(edrumwri): This test is brittle because it assumes that the stretch // "factor" is 1%. Update when stretch is programmatically // settable. { const double publish_dt = 42.0; const double publish_time = context->get_time() + publish_dt; const double update_dt = 0.01001; const double update_time = context->get_time() + update_dt; const double boundary_dt = 0.01; const double boundary_time = context->get_time() + boundary_dt; typename IntegratorBase<double>::StepResult result = integrator.IntegrateNoFurtherThanTime( publish_time, update_time, boundary_time); EXPECT_EQ(IntegratorBase<double>::kReachedBoundaryTime, result); EXPECT_EQ(t + boundary_dt, context->get_time()); } } GTEST_TEST(IntegratorTest, Symbolic) { using symbolic::Expression; using symbolic::Variable; // Create the mass spring system. SpringMassSystem<Expression> spring_mass(1., 1.); // Set the maximum step size. const double max_h = .01; // Create a context. auto context = spring_mass.CreateDefaultContext(); // Create the integrator. ExplicitEulerIntegrator<Expression> integrator( spring_mass, max_h, context.get()); integrator.Initialize(); const Variable q("q"); const Variable v("v"); const Variable work("work"); const Variable h("h"); context->SetContinuousState(Vector3<Expression>(q, v, work)); EXPECT_TRUE(integrator.IntegrateWithSingleFixedStepToTime(h)); EXPECT_TRUE(context->get_continuous_state_vector()[0].EqualTo(q + h*v)); EXPECT_TRUE(context->get_continuous_state_vector()[1].EqualTo(v - h*q)); EXPECT_TRUE(context->get_continuous_state_vector()[2].EqualTo(work - h*q*v)); } } // namespace } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/accelerometer.h
#pragma once #include <memory> #include <vector> #include "drake/common/drake_copyable.h" #include "drake/math/rigid_transform.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/multibody/tree/multibody_tree_indexes.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/framework/leaf_system.h" namespace drake { namespace systems { namespace sensors { /// Sensor to represent an ideal accelerometer sensor. Currently does not /// represent noise or bias, but this could and should be added at a later /// date. This sensor measures the proper acceleration of a point on a given /// body B. Proper acceleration subtracts gravity from the coordinate /// acceleration a_WS_S. That is, /// aproper_WS_S = a_WS_S - g_S /// Note that measurement is taken with respect to the world frame, /// but expressed in the coordinates of the local sensor frame S. /// Sensor frame S is rigidly affixed to the given body B. Note, also, the sign /// of the gravity component. For typical settings (e.g. on Earth assuming a /// constant gravitational field), the direction of "-g_S" is "upwards." /// /// There are three inputs to this sensor (nominally from a MultibodyPlant): /// 1. A vector of body poses (e.g. plant.get_body_poses_output_port()) /// 2. A vector of spatial velocities /// (e.g. plant.get_body_spatial_velocities_output_port()) /// 3. A vector of spatial accelerations /// (e.g. plant.get_body_spatial_accelerations_output_port()) /// /// This class is therefore defined by: /// 1. The rigid body to which this sensor is rigidly affixed. /// 2. A rigid transform from the body frame to the sensor frame. /// /// @system /// name: Accelerometer /// input_ports: /// - body_poses /// - body_spatial_velocities /// - body_spatial_accelerations /// output_ports: /// - measurement /// @endsystem /// /// @ingroup sensor_systems template <typename T> class Accelerometer final : public LeafSystem<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Accelerometer) /// @param body the body B to which the sensor is affixed /// @param X_BS the pose of sensor frame S in body B /// @param gravity_vector the constant acceleration due to gravity /// expressed in world coordinates Accelerometer( const multibody::RigidBody<T>& body, const math::RigidTransform<double>& X_BS, const Eigen::Vector3d& gravity_vector = Eigen::Vector3d::Zero()); /// Scalar-converting copy constructor. See @ref system_scalar_conversion. template <typename U> explicit Accelerometer(const Accelerometer<U>&); const InputPort<T>& get_body_poses_input_port() const { return *body_poses_input_port_; } const InputPort<T>& get_body_velocities_input_port() const { return *body_velocities_input_port_; } const InputPort<T>& get_body_accelerations_input_port() const { return *body_accelerations_input_port_; } const OutputPort<T>& get_measurement_output_port() const { return *measurement_output_port_; } /// Returns the index of the RigidBody that was supplied in the constructor. const multibody::BodyIndex& body_index() const { return body_index_; } /// Returns the gravity vector supplied in the constructor, or zero if none. const Eigen::Vector3d& gravity_vector() const { return gravity_vector_; } /// Gets X_BS, the pose of sensor frame S in body B const math::RigidTransform<double>& pose() const { return X_BS_; } /// Static factory method that creates an Accelerometer object and connects /// it to the given plant. Modifies a Diagram by connecting the input ports /// of the new Accelerometer to the appropriate output ports of a /// MultibodyPlant. Must be called during Diagram building and given the /// appropriate builder. This is a convenience method to simplify some common /// boilerplate of Diagram wiring. Specifically, this makes three connections: /// /// 1. plant.get_body_poses_output_port() to this.get_body_poses_input_port() /// 2. plant.get_body_spatial_velocities_output_port() to /// this.get_body_velocities_input_port() /// 3. plant.get_body_spatial_accelerations_output_port() to /// this.get_body_spatial_accelerations_output_port() /// @param body the rigid body B to which the sensor is affixed /// @param X_BS the pose of sensor frame S in body B /// @param gravity_vector the constant acceleration due to gravity /// expressed in world coordinates /// @param plant the plant to which the sensor will be connected /// @param builder a pointer to the DiagramBuilder static const Accelerometer& AddToDiagram( const multibody::RigidBody<T>& body, const math::RigidTransform<double>& X_BS, const Eigen::Vector3d& gravity_vector, const multibody::MultibodyPlant<T>& plant, DiagramBuilder<T>* builder); private: Accelerometer( const multibody::BodyIndex& body_index, const math::RigidTransform<double>& X_BS, const Eigen::Vector3d& gravity_vector = Eigen::Vector3d::Zero()); // Outputs the transformed signal. void CalcOutput(const Context<T>& context, BasicVector<T>* output) const; const multibody::BodyIndex body_index_; const math::RigidTransform<double> X_BS_; const Eigen::Vector3d gravity_vector_; const InputPort<T>* body_poses_input_port_{nullptr}; const InputPort<T>* body_velocities_input_port_{nullptr}; const InputPort<T>* body_accelerations_input_port_{nullptr}; const OutputPort<T>* measurement_output_port_{nullptr}; }; } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/lcm_image_array_to_images.cc
#include "drake/systems/sensors/lcm_image_array_to_images.h" #include <vector> #include <zlib.h> // To ease build system upkeep, we annotate VTK includes with their deps. #include <vtkImageExport.h> // vtkIOImage #include <vtkImageReader2.h> // vtkIOImage #include <vtkNew.h> // vtkCommonCore #include "drake/common/drake_assert.h" #include "drake/common/text_logging.h" #include "drake/common/unused.h" #include "drake/lcmt_image_array.hpp" #include "drake/systems/sensors/lcm_image_traits.h" #include "drake/systems/sensors/vtk_image_reader_writer.h" // TODO(jwnimmer-tri) Simplify this code by using "image_io.h" instead of // "vtk_image_reader_writer.h", and using a DiagnosticPolicy instead of status // bools flying around everywhere. namespace drake { namespace systems { namespace sensors { namespace { bool is_color_image(int8_t type) { switch (type) { case lcmt_image::PIXEL_FORMAT_RGB: case lcmt_image::PIXEL_FORMAT_BGR: case lcmt_image::PIXEL_FORMAT_RGBA: case lcmt_image::PIXEL_FORMAT_BGRA: { return true; } default: { break; } } return false; } bool image_has_alpha(int8_t type) { switch (type) { case lcmt_image::PIXEL_FORMAT_RGBA: case lcmt_image::PIXEL_FORMAT_BGRA: { return true; } default: { break; } } return false; } template <PixelType kPixelType> bool DecompressVtk(ImageFileFormat format, const lcmt_image* lcm_image, Image<kPixelType>* image) { vtkSmartPointer<vtkImageReader2> reader = internal::MakeReader( format, lcm_image->data.data(), lcm_image->data.size()); reader->Update(); vtkNew<vtkImageExport> exporter; exporter->SetInputConnection(reader->GetOutputPort(0)); exporter->ImageLowerLeftOff(); exporter->Update(); if (exporter->GetDataMemorySize() != image->width() * image->height() * image->kPixelSize) { drake::log()->error("Malformed output decoding incoming LCM {} image", format); return false; } exporter->Export(image->at(0, 0)); return true; } template <PixelType kPixelType> bool DecompressZlib(const lcmt_image* lcm_image, Image<kPixelType>* image) { // NOLINTNEXTLINE(runtime/int) unsigned long dest_len = image->width() * image->height() * image->kPixelSize; const int status = uncompress(reinterpret_cast<Bytef*>(image->at(0, 0)), &dest_len, lcm_image->data.data(), lcm_image->size); if (status != Z_OK) { drake::log()->error("zlib decompression failed on incoming LCM image: {}", status); *image = Image<kPixelType>(); return false; } return true; } template <PixelType kPixelType> bool UnpackLcmImage(const lcmt_image* lcm_image, Image<kPixelType>* image) { DRAKE_DEMAND(lcm_image->pixel_format == LcmPixelTraits<Image<kPixelType>::kPixelFormat>::kPixelFormat); DRAKE_DEMAND(lcm_image->channel_type == LcmImageTraits<kPixelType>::kChannelType); image->resize(lcm_image->width, lcm_image->height); switch (lcm_image->compression_method) { case lcmt_image::COMPRESSION_METHOD_NOT_COMPRESSED: { memcpy(image->at(0, 0), lcm_image->data.data(), image->size()); return true; } case lcmt_image::COMPRESSION_METHOD_ZLIB: { return DecompressZlib(lcm_image, image); } case lcmt_image::COMPRESSION_METHOD_JPEG: { return DecompressVtk(ImageFileFormat::kJpeg, lcm_image, image); } case lcmt_image::COMPRESSION_METHOD_PNG: { return DecompressVtk(ImageFileFormat::kPng, lcm_image, image); } default: { break; } } drake::log()->error("Unsupported LCM compression method: {}", lcm_image->compression_method); *image = Image<kPixelType>(); return false; } } // namespace LcmImageArrayToImages::LcmImageArrayToImages() : image_array_t_input_port_index_( this->DeclareAbstractInputPort("image_array_t", Value<lcmt_image_array>()) .get_index()), color_image_output_port_index_( this->DeclareAbstractOutputPort( "color_image", &LcmImageArrayToImages::CalcColorImage) .get_index()), depth_image_output_port_index_( this->DeclareAbstractOutputPort( "depth_image", &LcmImageArrayToImages::CalcDepthImage) .get_index()), label_image_output_port_index_( this->DeclareAbstractOutputPort( "label_image", &LcmImageArrayToImages::CalcLabelImage) .get_index()) { // TODO(sammy-tri) Calculating our output ports can be kinda expensive. We // should cache the images. } void LcmImageArrayToImages::CalcColorImage(const Context<double>& context, ImageRgba8U* color_image) const { const auto& images = image_array_t_input_port().Eval<lcmt_image_array>(context); // Look through the image array and just grab the first color image. const lcmt_image* lcm_image = nullptr; for (int i = 0; i < images.num_images; i++) { if (is_color_image(images.images[i].pixel_format)) { lcm_image = &images.images[i]; break; } } if (!lcm_image) { *color_image = ImageRgba8U(); return; } const bool has_alpha = image_has_alpha(lcm_image->pixel_format); if (has_alpha) { UnpackLcmImage(lcm_image, color_image); } else { ImageRgb8U rgb_image; if (UnpackLcmImage(lcm_image, &rgb_image)) { color_image->resize(lcm_image->width, lcm_image->height); for (int x = 0; x < lcm_image->width; x++) { for (int y = 0; y < lcm_image->height; y++) { color_image->at(x, y)[0] = rgb_image.at(x, y)[0]; color_image->at(x, y)[1] = rgb_image.at(x, y)[1]; color_image->at(x, y)[2] = rgb_image.at(x, y)[2]; color_image->at(x, y)[3] = 0xff; } } } else { *color_image = ImageRgba8U(); } } // TODO(sam.creasey) Handle BGR images, or at least error. } void LcmImageArrayToImages::CalcDepthImage(const Context<double>& context, ImageDepth32F* depth_image) const { const auto& images = image_array_t_input_port().Eval<lcmt_image_array>(context); // Look through the image array and just grab the first depth image. const lcmt_image* lcm_image = nullptr; for (int i = 0; i < images.num_images; i++) { if (images.images[i].pixel_format == lcmt_image::PIXEL_FORMAT_DEPTH) { lcm_image = &images.images[i]; break; } } if (!lcm_image) { *depth_image = ImageDepth32F(); return; } bool is_32f = false; switch (lcm_image->channel_type) { case lcmt_image::CHANNEL_TYPE_UINT16: { is_32f = false; break; } case lcmt_image::CHANNEL_TYPE_FLOAT32: { is_32f = true; break; } default: { drake::log()->error("Unsupported depth image channel type: {}", lcm_image->channel_type); *depth_image = ImageDepth32F(); return; } } if (is_32f) { UnpackLcmImage(lcm_image, depth_image); } else { ImageDepth16U image_16u; if (UnpackLcmImage(lcm_image, &image_16u)) { ConvertDepth16UTo32F(image_16u, depth_image); } else { *depth_image = ImageDepth32F(); } } } void LcmImageArrayToImages::CalcLabelImage(const Context<double>& context, ImageLabel16I* label_image) const { const auto& images = image_array_t_input_port().Eval<lcmt_image_array>(context); // Look through the image array and just grab the first label image. const lcmt_image* lcm_image = nullptr; for (int i = 0; i < images.num_images; i++) { if (images.images[i].pixel_format == lcmt_image::PIXEL_FORMAT_LABEL) { lcm_image = &images.images[i]; break; } } if (lcm_image == nullptr) { *label_image = {}; return; } if (lcm_image->channel_type != lcmt_image::CHANNEL_TYPE_INT16) { drake::log()->error("Unsupported label image channel type: {}", lcm_image->channel_type); *label_image = {}; return; } UnpackLcmImage(lcm_image, label_image); } } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/rgbd_sensor_async.cc
#include "drake/systems/sensors/rgbd_sensor_async.h" #include <future> #include <limits> #include <map> #include <memory> #include <set> #include <string> #include <utility> #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/sensors/rgbd_sensor.h" /* Here's an outline of how RgbdSensorAsync is implemented. There are two logical state variables (stored as a single abstract state variable): 1. The Worker; this is essentially a std::future for the rendering task. 2. The RenderedImages; this is the result of rendering. The system has two periodic update events, both at the same rate but with different phase offsets: 1. The "capture" event updates the Worker state by launching a new render task. 2. The "output" event updates the RenderedImages state by waiting for the worker to finish and storing the resulting images. The only real trick is how to sufficiently encapsulate a rendering task so that it can run on a background thread. The Worker accomplishes that using a helper class, the SnapshotSensor. The SnapshotSensor (itself a diagram) contains a QueryObjectChef and RgbdSensor connected in series. The Worker allocates a standalone SnapshotSensor Context and fixes the chef's input port(s) to be a copy of the scene graph's FramePoseVector input port(s), and uses the RgbdSensor to produce a rendered image on its output port. */ namespace drake { namespace systems { namespace sensors { using geometry::FrameId; using geometry::FramePoseVector; using geometry::GeometryVersion; using geometry::QueryObject; using geometry::Role; using geometry::SceneGraph; using geometry::SceneGraphInspector; using geometry::render::ClippingRange; using geometry::render::ColorRenderCamera; using geometry::render::DepthRange; using geometry::render::DepthRenderCamera; using geometry::render::RenderCameraCore; using math::RigidTransformd; namespace { /* A stateless system with the exact same input ports and output ports as the given SceneGraph, but with a private scratch Context to allow fixed input ports for the frame kinematics input. */ class QueryObjectChef final : public LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(QueryObjectChef) explicit QueryObjectChef(const SceneGraph<double>* scene_graph) : scene_graph_(scene_graph) { DRAKE_DEMAND(scene_graph != nullptr); // Our input ports are exactly the same as the underlying scene_graph. for (InputPortIndex i{0}; i < scene_graph->num_input_ports(); ++i) { const auto& port = scene_graph->get_input_port(i); DeclareAbstractInputPort(port.get_name(), *port.Allocate()); } // We allocate a SceneGraph context into scratch storage in *our* context. Scratch scratch; scratch.scene_graph_context = scene_graph->CreateDefaultContext(); scratch_index_ = this->DeclareCacheEntry( "scratch", ValueProducer(scratch, &ValueProducer::NoopCalc), {this->nothing_ticket()}) .cache_index(); // Our output is calculated by the SceneGraph. We use the lambda-based port // declaration syntax here (vs member function callback syntax) to avoid // extra copying. DeclareAbstractOutputPort( "query", []() { return Value<QueryObject<double>>().Clone(); }, [this](const Context<double>& context, AbstractValue* output) { this->CalcOutput(context, output); }, {all_input_ports_ticket()}); } void CalcOutput(const Context<double>& context, AbstractValue* output) const { Scratch& scratch = get_cache_entry(scratch_index_) .get_mutable_cache_entry_value(context) .GetMutableValueOrThrow<Scratch>(); DRAKE_DEMAND(scratch.scene_graph_context != nullptr); Context<double>& scene_graph_context = *scratch.scene_graph_context; for (InputPortIndex i{0}; i < num_input_ports(); ++i) { const auto& port = get_input_port(i); if (port.HasValue(context)) { const auto& value = port.template Eval<AbstractValue>(context); scene_graph_context.FixInputPort(i, value); } } scene_graph_->get_query_output_port().Calc(scene_graph_context, output); } private: struct Scratch { copyable_unique_ptr<Context<double>> scene_graph_context; }; const SceneGraph<double>* const scene_graph_; CacheIndex scratch_index_; }; /* Combines QueryObjectChef + RgbdSensor in series, creating a sensor that renders from a static FramePoseVector instead of a live QueryObject. */ class SnapshotSensor final : public Diagram<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SnapshotSensor) SnapshotSensor(const SceneGraph<double>* scene_graph, FrameId parent_id, const RigidTransformd& X_PB, ColorRenderCamera color_camera, DepthRenderCamera depth_camera) { DRAKE_DEMAND(scene_graph != nullptr); geometry_version_ = scene_graph->model_inspector().geometry_version(); DiagramBuilder<double> builder; auto* chef = builder.AddNamedSystem<QueryObjectChef>("chef", scene_graph); auto* rgbd = builder.AddNamedSystem<RgbdSensor>("camera", parent_id, X_PB, color_camera, depth_camera); builder.Connect(*chef, *rgbd); for (InputPortIndex i{0}; i < chef->num_input_ports(); ++i) { const auto& input_port = chef->get_input_port(i); builder.ExportInput(input_port, input_port.get_name()); } for (OutputPortIndex i{0}; i < rgbd->num_output_ports(); ++i) { const auto& output_port = rgbd->get_output_port(i); builder.ExportOutput(output_port, output_port.get_name()); } builder.BuildInto(this); } /* Returns the version as of when this sensor was created. */ const GeometryVersion& geometry_version() const { return geometry_version_; } private: GeometryVersion geometry_version_; }; /* The results of camera rendering. */ struct RenderedImages { RigidTransformd X_WB; double time{std::numeric_limits<double>::quiet_NaN()}; std::shared_ptr<const ImageRgba8U> color; std::shared_ptr<const ImageDepth32F> depth; std::shared_ptr<const ImageLabel16I> label; }; /* The worker is an object where Start() copies the pose input for camera rendering and launches an async task, and Finish() blocks for the task to complete. The expected workflow is to create a Worker and then repeatedly Start and Finish in alternation (with exactly one Finish per Start). This encapsulates the lifetime of the async task along with the objects it must keep alive during rendering. */ class Worker { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Worker) Worker(std::shared_ptr<const SnapshotSensor> sensor, bool color, bool depth, bool label) : sensor_{std::move(sensor)}, color_{color}, depth_{depth}, label_{label} { DRAKE_DEMAND(sensor_ != nullptr); sensor_context_ = sensor_->CreateDefaultContext(); } /* Begins rendering the given geometry as an async task. */ void Start(double context_time, const QueryObject<double>& query); /* Waits until image rendering for the most recent call to Start() is finished and then returns the result. When there is no async task (e.g., if Start has not been called since the most recent Finish), returns a default-constructed value (i.e., with nullptr for the images). */ RenderedImages Finish(); private: const std::shared_ptr<const SnapshotSensor> sensor_; const bool color_; const bool depth_; const bool label_; std::unique_ptr<Context<double>> sensor_context_; std::future<RenderedImages> future_; }; } // namespace /* The abstract state for an RgbdSensorAsync. The `output` is what appears on RgbdSensorAsync output ports. The `worker` encapsulates the background task. If the systems framework offered unrestricted update events that only updated one specific AbstractStateIndex instead of the entire State, then it would make sense to split this up into two separate abstract states. In the meantime, it's simplest to keep all of our state in one place. */ struct RgbdSensorAsync::TickTockState { std::shared_ptr<Worker> worker; RenderedImages output; }; RgbdSensorAsync::RgbdSensorAsync(const SceneGraph<double>* scene_graph, FrameId parent_id, const RigidTransformd& X_PB, double fps, double capture_offset, double output_delay, std::optional<ColorRenderCamera> color_camera, std::optional<DepthRenderCamera> depth_camera, bool render_label_image) : scene_graph_{scene_graph}, parent_id_{parent_id}, X_PB_{X_PB}, fps_{fps}, capture_offset_{capture_offset}, output_delay_{output_delay}, color_camera_{std::move(color_camera)}, depth_camera_{std::move(depth_camera)}, render_label_image_{render_label_image} { DRAKE_THROW_UNLESS(scene_graph != nullptr); DRAKE_THROW_UNLESS(std::isfinite(fps) && (fps > 0)); DRAKE_THROW_UNLESS(std::isfinite(capture_offset) && (capture_offset >= 0)); DRAKE_THROW_UNLESS(std::isfinite(output_delay) && (output_delay > 0)); DRAKE_THROW_UNLESS(output_delay < (1 / fps)); DRAKE_THROW_UNLESS(color_camera_.has_value() || depth_camera_.has_value()); DRAKE_THROW_UNLESS(!render_label_image || color_camera_.has_value()); // TODO(jwnimmer-tri) Check that the render engine named by either of the two // cameras is not the (known non-threadsafe) VTK engine. // Input. DeclareAbstractInputPort("geometry_query", Value<QueryObject<double>>{}); // State. using Self = RgbdSensorAsync; auto state_index = DeclareAbstractState(Value<TickTockState>{}); DeclareInitializationUnrestrictedUpdateEvent(&Self::Initialize); DeclarePeriodicUnrestrictedUpdateEvent(1 / fps, capture_offset, &Self::CalcTick); DeclarePeriodicUnrestrictedUpdateEvent(1 / fps, capture_offset + output_delay, &Self::CalcTock); // Output. These port names are intended to match RgbdSensor's port names. const std::set<DependencyTicket> state = {abstract_state_ticket(state_index)}; if (color_camera_.has_value()) { DeclareAbstractOutputPort("color_image", &Self::CalcColor, state); } if (depth_camera_.has_value()) { DeclareAbstractOutputPort("depth_image_32f", &Self::CalcDepth32F, state); DeclareAbstractOutputPort("depth_image_16u", &Self::CalcDepth16U, state); } if (render_label_image) { DeclareAbstractOutputPort("label_image", &Self::CalcLabel, state); } DeclareAbstractOutputPort("body_pose_in_world", &Self::CalcX_WB, state); DeclareVectorOutputPort("image_time", 1, &Self::CalcImageTime, state); } const OutputPort<double>& RgbdSensorAsync::color_image_output_port() const { constexpr char name[] = "color_image"; return this->GetOutputPort(name); } const OutputPort<double>& RgbdSensorAsync::depth_image_32F_output_port() const { constexpr char name[] = "depth_image_32f"; return this->GetOutputPort(name); } const OutputPort<double>& RgbdSensorAsync::depth_image_16U_output_port() const { constexpr char name[] = "depth_image_16u"; return this->GetOutputPort(name); } const OutputPort<double>& RgbdSensorAsync::label_image_output_port() const { constexpr char name[] = "label_image"; return this->GetOutputPort(name); } const OutputPort<double>& RgbdSensorAsync::body_pose_in_world_output_port() const { constexpr char name[] = "body_pose_in_world"; return this->GetOutputPort(name); } const OutputPort<double>& RgbdSensorAsync::image_time_output_port() const { constexpr char name[] = "image_time"; return this->GetOutputPort(name); } const RgbdSensorAsync::TickTockState& RgbdSensorAsync::get_state( const Context<double>& context) const { return context.template get_abstract_state<TickTockState>(0); } RgbdSensorAsync::TickTockState& RgbdSensorAsync::get_mutable_state( State<double>* state) const { DRAKE_DEMAND(state != nullptr); return state->template get_mutable_abstract_state<TickTockState>(0); } EventStatus RgbdSensorAsync::Initialize(const Context<double>& context, State<double>* state) const { // Grab the downcast reference from our argument. unused(context); TickTockState& next_state = get_mutable_state(state); // If we are only going to render one of color or depth, invent dummy // properties for the other one to simplify the SnapshotSensor code. std::optional<ColorRenderCamera> color = color_camera_; std::optional<DepthRenderCamera> depth = depth_camera_; if (!color.has_value()) { DRAKE_DEMAND(depth.has_value()); const RenderCameraCore& core = depth->core(); color.emplace(core); } if (!depth.has_value()) { DRAKE_DEMAND(color.has_value()); const RenderCameraCore& core = color->core(); const ClippingRange& clip = core.clipping(); // N.B. Avoid using clip.far() here; it can trip the "16 bit mm depth" // logger spam from RgbdSensor. depth.emplace(core, DepthRange(clip.near(), clip.near() * 1.001)); } // The `sensor` is a separate, nested system that actually renders images. // The outer system (`this`) is just the event shims that will tick it. Our // job during initialization is to reset the nested system and any prior // output. auto sensor = std::make_shared<const SnapshotSensor>( scene_graph_, parent_id_, X_PB_, std::move(*color), std::move(*depth)); next_state.worker = std::make_shared<Worker>(std::move(sensor), color_camera_.has_value(), depth_camera_.has_value(), render_label_image_); next_state.output = {}; return EventStatus::Succeeded(); } void RgbdSensorAsync::CalcTick(const Context<double>& context, State<double>* state) const { // Get the geometry pose updates. const auto& query = get_input_port().Eval<QueryObject<double>>(context); // Grab the downcast references from our arguments. const TickTockState& prior_state = get_state(context); TickTockState& next_state = get_mutable_state(state); // Preserve the current output from the prior state. We're only going to // launch a worker task, without any changes to our output. next_state.output = prior_state.output; // Latch-initialize a worker we didn't have one yet. if (prior_state.worker == nullptr) { Initialize(context, state); } else { next_state.worker = prior_state.worker; } // Start the worker on its next task. next_state.worker->Start(context.get_time(), query); } void RgbdSensorAsync::CalcTock(const Context<double>& context, State<double>* state) const { // Grab the downcast references from our arguments. const TickTockState& prior_state = get_state(context); TickTockState& next_state = get_mutable_state(state); // If the user manually changes the State outside of a Simulator, we might hit // a tock without having been initialized. Guard that here to avoid crashing. if (prior_state.worker == nullptr) { next_state = {}; return; } // TODO(jwnimmer-tri) Consider adding a guard here so that out-of-sequence // tocks due to the user manually screwing with the State result in empty // images instead of stale images. // Finish the worker task, and copy it to the output ports. next_state.worker = prior_state.worker; next_state.output = next_state.worker->Finish(); } namespace { /* If the rendered image is non-null, copy it to output. Otherwise, set the the output to be empty (i.e., zero-sized width and height). */ template <typename ImageIn, typename ImageOut> void CopyImage(const ImageIn* rendered, ImageOut* output) { DRAKE_DEMAND(output != nullptr); if (rendered == nullptr) { output->resize(0, 0); return; } if constexpr (std::is_same_v<ImageIn, ImageOut>) { *output = *rendered; } else { ConvertDepth32FTo16U(*rendered, output); } } } // namespace void RgbdSensorAsync::CalcColor(const Context<double>& context, ImageRgba8U* output) const { DRAKE_DEMAND(color_camera_.has_value()); CopyImage(get_state(context).output.color.get(), output); } void RgbdSensorAsync::CalcLabel(const Context<double>& context, ImageLabel16I* output) const { DRAKE_DEMAND(color_camera_.has_value()); CopyImage(get_state(context).output.label.get(), output); } void RgbdSensorAsync::CalcDepth32F(const Context<double>& context, ImageDepth32F* output) const { DRAKE_DEMAND(depth_camera_.has_value()); CopyImage(get_state(context).output.depth.get(), output); } void RgbdSensorAsync::CalcDepth16U(const Context<double>& context, ImageDepth16U* output) const { DRAKE_DEMAND(depth_camera_.has_value()); CopyImage(get_state(context).output.depth.get(), output); } void RgbdSensorAsync::CalcX_WB(const Context<double>& context, RigidTransformd* output) const { *output = get_state(context).output.X_WB; } void RgbdSensorAsync::CalcImageTime(const Context<double>& context, BasicVector<double>* output) const { output->SetFromVector(Vector1d{get_state(context).output.time}); } namespace { void Worker::Start(double context_time, const QueryObject<double>& query) { // Confirm that the geometry version number has not changed since Initialize. const GeometryVersion& initialize_version = sensor_->geometry_version(); const GeometryVersion& current_version = query.inspector().geometry_version(); if (!current_version.IsSameAs(initialize_version, Role::kPerception)) { // TODO(jwnimmer-tri) Ideally, here we would update our copy of the geometry // to match `query` instead of throwing. That's somewhat complicated to // implement and test at the moment, so for now instead we have a warning in // our class overview docs cautioning about this. throw std::logic_error( "As the moment, RgbdSensorAsync cannot respond to changes in geometry " "shapes, textures, etc. after a simulation has started. If you change " "anything beyond poses, you must manually call Simulator::Initialize() " "to reset things before resuming the simulation."); } // Read the frame poses from the QueryObject. Note that deformable geometry is // not supported because this only propagates poses, not configurations. // TODO(jwnimmer-tri) After the render engine API adds support for deformable // geometry, we should upgrade this sensor to support deformables as well. std::map<std::string, FramePoseVector<double>> poses; const SceneGraphInspector<double>& inspector = query.inspector(); for (bool first = true; const auto& source_id : inspector.GetAllSourceIds()) { if (first) { first = false; // Skip the SceneGraph source that holds the "world" frame. DRAKE_DEMAND( inspector.BelongsToSource(inspector.world_frame_id(), source_id)); continue; } const std::string& source_name = inspector.GetName(source_id); auto& source_poses = poses[source_name + "_pose"]; for (const auto& frame_id : inspector.FramesForSource(source_id)) { source_poses.set_value(frame_id, query.GetPoseInParent(frame_id)); } } // Abandon our prior task (typically not necessary; valid() is usually false). if (future_.valid()) { future_.wait(); future_ = {}; } // Launch the rendering task. auto task = [this, context_time, poses = std::move(poses)]() -> RenderedImages { for (const auto& [port_name, pose_vector] : poses) { const auto& input_port = sensor_->GetInputPort(port_name); input_port.FixValue(sensor_context_.get(), pose_vector); } RenderedImages result; // TODO(jwnimmer-tri) Is there any way we can steal (move) the images from // the output ports, to avoid extra copying? I suppose we could call the // QueryObject directly instead of the RgbdSensor, but that would involve // duplicating (copying) some of its functionality into this class. if (color_) { result.color = std::make_shared<const ImageRgba8U>( sensor_->GetOutputPort("color_image") .template Eval<ImageRgba8U>(*sensor_context_)); } if (depth_) { result.depth = std::make_shared<const ImageDepth32F>( sensor_->GetOutputPort("depth_image_32f") .template Eval<ImageDepth32F>(*sensor_context_)); } if (label_) { result.label = std::make_shared<const ImageLabel16I>( sensor_->GetOutputPort("label_image") .template Eval<ImageLabel16I>(*sensor_context_)); } result.X_WB = sensor_->GetOutputPort("body_pose_in_world") .template Eval<RigidTransformd>(*sensor_context_); result.time = context_time; return result; }; future_ = std::async(std::launch::async, std::move(task)); } RenderedImages Worker::Finish() { if (!future_.valid()) { return {}; } future_.wait(); return future_.get(); } } // namespace } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/camera_config.h
#pragma once #include <optional> #include <string> #include <utility> #include <variant> #include "drake/common/eigen_types.h" #include "drake/common/name_value.h" #include "drake/common/schema/transform.h" #include "drake/geometry/render/render_camera.h" #include "drake/geometry/render_gl/render_engine_gl_params.h" #include "drake/geometry/render_gltf_client/render_engine_gltf_client_params.h" #include "drake/geometry/render_vtk/render_engine_vtk_params.h" #include "drake/geometry/rgba.h" namespace drake { namespace systems { namespace sensors { /** Configuration of a camera. This covers all of the parameters for both color (see geometry::render::ColorRenderCamera) and depth (see geometry::render::DepthRenderCamera) cameras. The various properties have restrictions on what they can be. - Values must be finite. - Some values must be positive (see notes on individual properties). - Ranges must be specified such that the "minimum" value is less than or equal to the "maximum" value. This includes the clipping range [`clipping_near`, `clipping_far`] and depth range [`z_near`, `z_far`]. - The depth range must lie *entirely* within the clipping range. The values are only checked when the configuration is operated on: during serialization, after deserialization, and when applying the configuration (see ApplyCameraConfig().) */ struct CameraConfig { /** Passes this object to an Archive. Refer to @ref yaml_serialization "YAML Serialization" for background. */ template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(width)); a->Visit(DRAKE_NVP(height)); a->Visit(DRAKE_NVP(focal)); a->Visit(DRAKE_NVP(center_x)); a->Visit(DRAKE_NVP(center_y)); a->Visit(DRAKE_NVP(clipping_near)); a->Visit(DRAKE_NVP(clipping_far)); a->Visit(DRAKE_NVP(z_near)); a->Visit(DRAKE_NVP(z_far)); a->Visit(DRAKE_NVP(X_PB)); a->Visit(DRAKE_NVP(X_BC)); a->Visit(DRAKE_NVP(X_BD)); a->Visit(DRAKE_NVP(renderer_name)); a->Visit(DRAKE_NVP(renderer_class)); a->Visit(DRAKE_NVP(background)); a->Visit(DRAKE_NVP(name)); a->Visit(DRAKE_NVP(fps)); a->Visit(DRAKE_NVP(capture_offset)); a->Visit(DRAKE_NVP(output_delay)); a->Visit(DRAKE_NVP(rgb)); a->Visit(DRAKE_NVP(depth)); a->Visit(DRAKE_NVP(label)); a->Visit(DRAKE_NVP(show_rgb)); a->Visit(DRAKE_NVP(do_compress)); a->Visit(DRAKE_NVP(lcm_bus)); ValidateOrThrow(); } /** Specification of a camera's intrinsic focal properties as focal *length* (in pixels). One or both values can be given. When only one value is given, the other is assumed to match. At least one value must be provided. */ struct FocalLength { /** Passes this object to an Archive. Refer to @ref yaml_serialization "YAML Serialization" for background. */ template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(x)); a->Visit(DRAKE_NVP(y)); } /** If specified, the focal length along this axis; otherwise, use focal length in the y-direction. */ std::optional<double> x; /** If specified, the focal length along this axis; otherwise, use focal length in the x-direction. */ std::optional<double> y; void ValidateOrThrow() const; /** Reports focal length along x-axis. @throws std::exception if both `x` and `y` are null. */ double focal_x() const; /** Resolves focal length along y-axis. @throws std::exception if both `x` and `y` are null. */ double focal_y() const; }; /** Specification of focal length via fields of view (in degrees). */ struct FovDegrees { /** Passes this object to an Archive. Refer to @ref yaml_serialization "YAML Serialization" for background. */ template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(x)); a->Visit(DRAKE_NVP(y)); } /** If specified, compute focal length along this axis; otherwise, use focal length given computation for `y`. */ std::optional<double> x; /** If specified, compute focal length along this axis; otherwise, use focal length given computation for `x`. */ std::optional<double> y; void ValidateOrThrow() const; /** Resolves focal length along x-axis based on image dimensions and defined value for `x` and/or `y`. @throws std::exception if both `x` and `y` are null. */ double focal_x(int width, int height) const; /** Resolves focal length along y-axis based on image dimensions and defined value for `y` and/or `x`. @throws std::exception if both `x` and `y` are null. */ double focal_y(int width, int height) const; }; /** @name Camera intrinsics See CameraInfo. */ //@{ /** %Image width (in pixels). @pre width > 0. */ int width{640}; /** %Image height (in pixels). @pre height > 0. */ int height{480}; /** The focal properties of the camera. It can be specified in one of two ways: - A FocalLength which specifies the focal lengths (in pixels) in the x- and y-directions. - An FovDegrees which defines focal length *implicitly* by deriving it from field of view measures (in degrees). For both specifications, if only one value is given (in either direction), the focal length (as reported by focal_x() and focal_y()) is determined by that single value and is assumed to be symmetric for both directions. @pre focal length(s) is a/are finite, positive number(s). */ std::variant<FocalLength, FovDegrees> focal{FovDegrees{.y = 45}}; /** Returns the focal length (in pixels) in the x-direction. */ double focal_x() const; /** Returns the focal length (in pixels) in the y-direction. */ double focal_y() const; /** The x-position of the principal point (in pixels). To query what the current value is, use principal_point(). @pre 0 < center_x < width or is std::nullopt. */ std::optional<double> center_x{}; /** The y-position of the principal point (in pixels). To query what the current value is, use principal_point(). @pre 0 < center_y < height or is std::nullopt. */ std::optional<double> center_y{}; /** Returns the position of the principal point. This respects the semantics that undefined center_x and center_y place the principal point in the center of the image. */ Vector2<double> principal_point() const { // This calculation should be kept in agreement with CameraInfo's. return {center_x.has_value() ? *center_x : width * 0.5 - 0.5, center_y.has_value() ? *center_y : height * 0.5 - 0.5}; } //@} /** @name Frustum-based camera properties See geometry::render::ClippingRange. */ //@{ /** The distance (in meters) from sensor origin to near clipping plane. @pre clipping_near is a positive, finite number. */ double clipping_near{0.01}; /** The distance (in meters) from sensor origin to far clipping plane. @pre clipping_far is a positive, finite number. */ double clipping_far{500.0}; //@} /** @name Depth camera range See geometry::render::DepthRange. */ //@{ /** The distance (in meters) from sensor origin to closest measurable plane. @pre z_near is a positive, finite number. */ double z_near{0.1}; /** The distance (in meters) from sensor origin to farthest measurable plane. @pre z_near is a positive, finite number. */ double z_far{5.0}; //@} /** @name Camera extrinsics The pose of the camera. As documented in RgbdSensor, the camera has four associated frames: P, B, C, D. The frames of the parent (to which the camera body is rigidly affixed), the camera body, color sensor, and depth sensor, respectively. Typically, the body is posed w.r.t. the parent (X_PB) and the sensors are posed w.r.t. the body (X_BC and X_BD). When unspecified, X_BD = X_BC = I by default. */ //@{ /** The pose of the body camera relative to a parent frame P. If `X_PB.base_frame` is unspecified, then the world frame is assumed to be the parent frame. @pre `X_PB.base_frame` is empty *or* refers to a valid, unique frame. */ schema::Transform X_PB; /** The pose of the color sensor relative to the camera body frame. @pre `X_BC.base_frame` is empty. */ schema::Transform X_BC; /** The pose of the depth sensor relative to the camera body frame. @pre `X_BD.base_frame` is empty. */ schema::Transform X_BD; //@} /** @name Renderer properties Every camera is supported by a geometry::render::RenderEngine instance. These properties configure the render engine for this camera. */ //@{ /** The name of the geometry::render::RenderEngine that this camera uses. Generally, it is more efficient for multiple cameras to share a single render engine instance; they should, therefore, share a common renderer_name value. @pre `renderer_name` is not empty. */ std::string renderer_name{"default"}; /** The choice of render engine implementation to use. It can be specified simply by providing a `string` containing the class _name_ of the RenderEngine to use (i.e., `"RenderEngineVtk"`, `"RenderEngineGl"`, or `"RenderEngineGltfClient"`). Or, it can be specified by providing parameters for one of those engines: RenderEngineVtkParams, RenderEngineGlParams, or RenderEngineGltfClientParams. If a `string` containing the render engine class _name_ is provided, the engine instantiated will use the default parameters -- equivalent to passing the set of default parameters. It is possible for multiple cameras to reference the same `renderer_name` but configure the renderer differently. This would be a configuration error. The following rules will help prevent problematic configurations: - Multiple cameras can reference the same value for `renderer_name`. - If multiple cameras reference the same value for `renderer_name`, only the *first* can use the engine parameters to specify it. Attempting to do so with a later camera will produce an error. - The later cameras can use engine class _name_. - If a later camera names a *different* engine class, that will result in an error. In YAML, it can be a bit trickier. Depending on how a collection of cameras is articulated, the concept of "first" may be unclear. In `examples/hardware_sim/scenario.h` the collection is a map. So, the camera configurations are not necessarily processed in the order they appear in the YAML file. Instead, the processing order depends on the mnemonic camera key. So, be aware, if you use a similar mapping, you may have to massage the key names to achieve the requisite processing order. Alternatively, a vector of %CameraConfig in your own scenario file, would guarantee that processing order is the same as file order. We intend to relax these restrictions in time, allowing equivalent, redundant specifications of a render engine (and throwing only on inconsistent specifications). Passing the empty string is equivalent to saying, "I don't care". If a render engine with that name has already been configured, the camera will use it (regardless of type). If the name doesn't already exist, the default, slower, more portable, and more robust RenderEngineVtk will be instantiated. RenderEngineGl can be selected if you are on Ubuntu and need the improved performance (at the *possible* cost of lesser image fidelity). In YAML, omitting `renderer_class` from the camera specification is equivalent to "passing the empty string". <h4>Configuring in YAML</h4> It isn't always obvious what the proper spelling in YAML is. The following examples illustrate how the `renderer_class` field can be defined in YAML files. 1. Use the RenderEngineVtk with all default parameters - providing the class name as a string. @code{yaml} renderer_class: RenderEngineVtk @endcode 2. Use the RenderEngineVtk with all default parameters - providing the engine parameters with default values. @code{yaml} renderer_class: !RenderEngineVtkParams {} @endcode 3. Use the RenderEngineVtk with a customized clear color (black). @code{yaml} renderer_class: !RenderEngineVtkParams default_clear_color: [0, 0, 0] @endcode 4. Use the RenderEngineGl with a customized clear color (black). @code{yaml} renderer_class: !RenderEngineGlParams default_clear_color: rgba: [0, 0, 0, 1] @endcode 5. Use the RenderEngineGltfClient with fully specified properties. @code{yaml} renderer_class: !RenderEngineGltfClientParams base_url: http://10.10.10.1 render_endpoint: server verbose: true cleanup: false @endcode 6. Explicitly request Drake's default render engine. @code{yaml} renderer_class: "" @endcode Things to note: - When providing the _parameters_ for the engine, the declaration must begin with `!` to announce it as a type (examples 2, 3, and 4). - A defaulted set of parameters must have a trailing `{}` (example 2). - Two engine parameter sets may have the same semantic parameter but spell it differently (`default_clear_color` in examples 3 and 4). @pre `renderer_class` is a string and either empty or one of `"RenderEngineVtk"`, `"RenderEngineGl"`, or `"RenderEngineGltfClient"`, or, it is a parameter type of one of Drake's RenderEngine implementations. @sa drake::geometry::SceneGraph::GetRendererTypeName(). */ std::variant<std::string, geometry::RenderEngineVtkParams, geometry::RenderEngineGlParams, geometry::RenderEngineGltfClientParams> renderer_class{""}; /** The "background" color. This is the color drawn where there are no objects visible. Its default value matches the default value for render::RenderEngineVtkParams::default_clear_color. See the documentation for geometry::Rgba::Serialize for how to define this value in YAML. This value is used only if the `render_class` specifies either `"RenderEngineVtk"` or `"RenderEngineGl"` by _name_ (RenderEngineGltfClient doesn't have a configurable background color.) */ geometry::Rgba background{204 / 255.0, 229 / 255.0, 255 / 255.0, 1.0}; //@} /** @name Publishing properties */ //@{ /** The camera name. This `name` is used as part of the corresponding RgbdSensor system's name and serves as a suffix of the LCM channel name. @pre `name` is not empty.*/ std::string name{"preview_camera"}; /** Publishing rate (in Hz) for both RGB and depth cameras (as requested). @pre fps is a positive, finite number. */ double fps{10.0}; /** Phase offset (in seconds) for image capture, relative to the simulator's time zero. This can be useful to stagger multiple cameras. Refer to the RgbdSensorAsync class for a comprehensive description. @pre capture_offset is non-negative and finite. */ double capture_offset{0.0}; /** Delay (in seconds) between when the scene graph geometry is "captured" and when the output image is published. Refer to the RgbdSensorAsync class for a comprehensive description. @pre output_delay is non-negative and strictly less than 1/fps. */ double output_delay{0.0}; /** If true, RGB images will be produced and published via LCM. */ bool rgb{true}; /** If true, depth images will be produced and published via LCM. */ bool depth{false}; /** If true, label images will be produced and published via LCM. */ bool label{false}; /** Controls whether the rendered RGB and/or label images are displayed (in separate windows controlled by the thread in which the camera images are rendered). As both image types are rendered from `ColorRenderCamera`, it applies to both of them and depends on whether the RenderEngine instance supports it. Note: This flag is intended for quick debug use during development instead of serving as an image viewer. Currently, there are known issues, e.g., flickering windows when multiple cameras share the same renderer or upside-down images if RenderEngineGl is set. See issue #18862 for the proposal to visualize images via Meldis. */ bool show_rgb{false}; /** Controls whether the images are broadcast in a compressed format. */ bool do_compress{true}; /** Which LCM URL to use. @see drake::systems::lcm::LcmBuses */ std::string lcm_bus{"default"}; //@} /** Creates color and depth camera data from this configuration. @throws std::exception if configuration values do not satisfy the documented prerequisites. */ std::pair<geometry::render::ColorRenderCamera, geometry::render::DepthRenderCamera> MakeCameras() const; /** Throws if the values are inconsistent. */ void ValidateOrThrow() const; }; } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/BUILD.bazel
load("//tools/lint:lint.bzl", "add_lint_tests") load( "//tools/skylark:alias.bzl", "drake_cc_library_aliases", ) load( "//tools/skylark:drake_cc.bzl", "drake_cc_binary", "drake_cc_googletest", "drake_cc_googletest_linux_only", "drake_cc_library", "drake_cc_package_library", ) load("//tools/skylark:test_tags.bzl", "vtk_test_tags") package(default_visibility = ["//visibility:public"]) drake_cc_package_library( name = "sensors", visibility = ["//visibility:public"], deps = [ ":accelerometer", ":beam_model", ":beam_model_params", ":camera_config", ":camera_config_functions", ":camera_info", ":gyroscope", ":image", ":image_file_format", ":image_io", ":image_to_lcm_image_array_t", ":image_writer", ":lcm_image_array_to_images", ":lcm_image_traits", ":rgbd_sensor", ":rgbd_sensor_async", ":rotary_encoders", ":sim_rgbd_sensor", ], ) drake_cc_library( name = "accelerometer", srcs = ["accelerometer.cc"], hdrs = ["accelerometer.h"], deps = [ "//math:geometric_transform", "//multibody/math", "//multibody/plant", "//multibody/tree:multibody_tree_indexes", "//systems/framework", ], ) drake_cc_library( name = "beam_model_params", srcs = [ "beam_model_params.cc", ], hdrs = [ "beam_model_params.h", "gen/beam_model_params.h", ], deps = [ "//common:dummy_value", "//common:essential", "//common:name_value", "//common/symbolic:expression", "//systems/framework:vector", ], ) drake_cc_library( name = "beam_model", srcs = ["beam_model.cc"], hdrs = ["beam_model.h"], deps = [ ":beam_model_params", "//common:unused", "//systems/framework", ], ) drake_cc_library( name = "camera_config", srcs = ["camera_config.cc"], hdrs = ["camera_config.h"], deps = [ ":camera_info", "//common:name_value", "//common/schema:transform", "//geometry:rgba", "//geometry/render:render_camera", "//geometry/render_gl:render_engine_gl_params", "//geometry/render_gltf_client:render_engine_gltf_client_params", "//geometry/render_vtk:render_engine_vtk_params", ], ) drake_cc_library( name = "camera_config_functions", srcs = ["camera_config_functions.cc"], hdrs = ["camera_config_functions.h"], interface_deps = [ ":camera_config", "//geometry:scene_graph", "//lcm:interface", "//multibody/plant", "//systems/framework:diagram_builder", "//systems/lcm:lcm_buses", ], deps = [ ":camera_info", ":rgbd_sensor", ":rgbd_sensor_async", ":sim_rgbd_sensor", "//common:overloaded", "//geometry/render_gl", "//geometry/render_gltf_client", "//geometry/render_vtk", "//math:geometric_transform", "//multibody/parsing:scoped_names", "//systems/lcm:lcm_config_functions", ], ) drake_cc_library( name = "camera_info", srcs = [ "camera_info.cc", ], hdrs = [ "camera_info.h", ], deps = [ "//systems/framework", ], ) drake_cc_library( name = "gyroscope", srcs = ["gyroscope.cc"], hdrs = ["gyroscope.h"], deps = [ "//math:geometric_transform", "//multibody/math", "//multibody/plant", "//multibody/tree:multibody_tree_indexes", "//systems/framework", ], ) drake_cc_library( name = "image", srcs = [ "image.cc", "pixel_types.cc", ], hdrs = [ "image.h", "pixel_types.h", ], deps = [ "//common:essential", "//common:reset_after_move", "//common/symbolic:expression", ], ) drake_cc_library( name = "image_file_format", srcs = ["image_file_format.cc"], hdrs = ["image_file_format.h"], deps = [ "//common:essential", ], ) drake_cc_library( name = "image_io", srcs = [ "image_io_internal.cc", "image_io_load.cc", "image_io_save.cc", ], hdrs = [ "image_io.h", "image_io_internal.h", ], install_hdrs_exclude = [ "image_io_internal.h", ], interface_deps = [ ":image", ":image_file_format", "//common:diagnostic_policy", "//common:essential", "//common:name_value", ], deps = [ ":vtk_diagnostic_event_observer", ":vtk_image_reader_writer", "//common:drake_export", "@vtk_internal//:vtkCommonCore", "@vtk_internal//:vtkCommonDataModel", "@vtk_internal//:vtkIOImage", ], ) drake_cc_library( name = "lcm_image_traits", srcs = [ "lcm_image_traits.cc", ], hdrs = [ "lcm_image_traits.h", ], deps = [ ":image", "//lcmtypes:image", ], ) drake_cc_library( name = "image_to_lcm_image_array_t", srcs = [ "image_to_lcm_image_array_t.cc", ], hdrs = [ "image_to_lcm_image_array_t.h", ], deps = [ ":lcm_image_traits", "//common:essential", "//lcmtypes:image_array", "//systems/framework", "@zlib", ], ) drake_cc_library( name = "lcm_image_array_to_images", srcs = [ "lcm_image_array_to_images.cc", ], hdrs = [ "lcm_image_array_to_images.h", ], interface_deps = [ ":image", "//common:essential", "//systems/framework:leaf_system", ], deps = [ ":lcm_image_traits", ":vtk_image_reader_writer", "//lcmtypes:image_array", "@vtk_internal//:vtkCommonCore", "@vtk_internal//:vtkIOImage", "@zlib", ], ) drake_cc_binary( name = "lcm_image_array_receive_example", srcs = [ "lcm_image_array_receive_example.cc", ], deps = [ ":image_to_lcm_image_array_t", ":lcm_image_array_to_images", "//common:add_text_logging_gflags", "//systems/analysis:simulator", "//systems/lcm:lcm_pubsub_system", "@gflags", ], ) drake_cc_library( name = "rgbd_sensor", srcs = [ "rgbd_sensor.cc", "rgbd_sensor_discrete.cc", ], hdrs = [ "rgbd_sensor.h", "rgbd_sensor_discrete.h", ], deps = [ ":camera_info", ":image", "//common:essential", "//geometry:geometry_ids", "//geometry:scene_graph", "//geometry/render:render_engine", "//systems/framework:leaf_system", "//systems/primitives:zero_order_hold", ], ) drake_cc_library( name = "rgbd_sensor_async", srcs = ["rgbd_sensor_async.cc"], hdrs = ["rgbd_sensor_async.h"], deps = [ ":camera_info", ":image", ":rgbd_sensor", "//geometry:scene_graph", "//systems/framework:diagram_builder", ], ) drake_cc_library( name = "rotary_encoders", srcs = ["rotary_encoders.cc"], hdrs = ["rotary_encoders.h"], deps = [ "//common:unused", "//systems/framework", ], ) drake_cc_library( name = "image_writer", srcs = ["image_writer.cc"], hdrs = ["image_writer.h"], interface_deps = [ ":image", "//common:essential", "//systems/framework:leaf_system", ], deps = [ ":image_io", ], ) drake_cc_library( name = "sim_rgbd_sensor", srcs = ["sim_rgbd_sensor.cc"], hdrs = ["sim_rgbd_sensor.h"], deps = [ ":image_to_lcm_image_array_t", ":rgbd_sensor", "//lcm", "//multibody/plant", "//systems/framework:diagram_builder", "//systems/lcm:lcm_publisher_system", ], ) drake_cc_library( name = "vtk_diagnostic_event_observer", srcs = ["vtk_diagnostic_event_observer.cc"], hdrs = ["vtk_diagnostic_event_observer.h"], internal = True, visibility = [ "//geometry/render_vtk:__pkg__", ], deps = [ "//common:diagnostic_policy", "//common:drake_export", "@vtk_internal//:vtkCommonCore", ], ) drake_cc_library( name = "vtk_image_reader_writer", srcs = ["vtk_image_reader_writer.cc"], hdrs = ["vtk_image_reader_writer.h"], internal = True, visibility = ["//:__subpackages__"], deps = [ ":image_file_format", "//common:unused", "@vtk_internal//:vtkCommonCore", "@vtk_internal//:vtkIOImage", ], ) # === test/ === drake_cc_googletest( name = "accelerometer_test", data = ["//examples/pendulum:models"], deps = [ ":accelerometer", "//common/test_utilities:eigen_matrix_compare", "//multibody/parsing", "//multibody/plant", "//systems/framework/test_utilities", ], ) drake_cc_googletest( name = "beam_model_test", deps = [ ":beam_model", "//common/proto:call_python", "//systems/analysis:simulator", "//systems/framework/test_utilities", "//systems/primitives:constant_vector_source", "//systems/primitives:random_source", "//systems/primitives:vector_log_sink", ], ) drake_cc_googletest( name = "camera_config_test", deps = [ ":camera_config", "//common/schema:transform", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_throws_message", "//common/yaml:yaml_io", "//geometry/render_vtk", "@fmt", ], ) drake_cc_googletest( name = "camera_config_functions_test", allow_network = ["render_gltf_client"], tags = vtk_test_tags(), deps = [ ":camera_config_functions", ":image_to_lcm_image_array_t", ":rgbd_sensor_async", ":sim_rgbd_sensor", "//common/test_utilities:expect_throws_message", "//common/yaml:yaml_io", "//geometry/render_gl", "//geometry/render_gltf_client", "//geometry/render_vtk", "//lcm:drake_lcm", "//systems/lcm:lcm_publisher_system", ], ) drake_cc_googletest( name = "camera_info_test", deps = [ ":camera_info", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_throws_message", ], ) drake_cc_googletest( name = "image_file_format_test", deps = [ ":image_file_format", ], ) drake_cc_googletest( name = "gyroscope_test", data = ["//examples/pendulum:models"], deps = [ ":gyroscope", "//common/test_utilities:eigen_matrix_compare", "//multibody/parsing", "//multibody/plant", "//systems/framework/test_utilities", ], ) drake_cc_googletest( name = "image_test", deps = [ ":image", ], ) drake_cc_library( name = "image_io_test_params", testonly = True, srcs = ["test/image_io_test_params.cc"], hdrs = ["test/image_io_test_params.h"], visibility = ["//visibility:private"], deps = [ ":image", ":image_file_format", "@gtest//:without_main", "@vtk_internal//:vtkCommonCore", "@vtk_internal//:vtkCommonDataModel", ], ) drake_cc_googletest( name = "image_io_internal_test", data = [ "test/jpeg_test.jpg", "test/png_color_test.png", "test/tiff_32f_test.tif", ], deps = [ ":image_io", "//common:find_resource", "@vtk_internal//:vtkCommonCore", ], ) drake_cc_googletest( name = "image_io_test", data = [ "test/png_color16_test.png", "test/tiff_rgb32f_test.tif", ], deps = [ ":image_io", ":image_io_test_params", "//common:find_resource", "//common:temp_directory", "//common/test_utilities:expect_throws_message", "//systems/sensors/test_utilities:image_compare", ], ) drake_cc_googletest( name = "image_writer_test", tags = vtk_test_tags(), deps = [ ":image_writer", "//common:temp_directory", "//common/test_utilities", "//systems/sensors/test_utilities:image_compare", ], ) drake_cc_googletest( name = "image_writer_free_functions_test", deps = [ ":image_writer", "//common:temp_directory", "//systems/sensors/test_utilities:image_compare", ], ) drake_cc_googletest( name = "pixel_types_test", deps = [ ":image", ], ) drake_cc_googletest( name = "rgbd_sensor_test", tags = vtk_test_tags(), deps = [ ":rgbd_sensor", "//common/test_utilities:eigen_matrix_compare", "//geometry/test_utilities:dummy_render_engine", ], ) drake_cc_googletest( name = "rgbd_sensor_async_test", deps = [ ":rgbd_sensor_async", "//common/test_utilities:expect_throws_message", "//geometry/test_utilities:dummy_render_engine", "//multibody/plant", "//systems/analysis:simulator", ], ) drake_cc_googletest( name = "rgbd_sensor_discrete_test", tags = vtk_test_tags(), deps = [ ":rgbd_sensor", "//common/test_utilities:eigen_matrix_compare", "//geometry/test_utilities:dummy_render_engine", ], ) drake_cc_googletest_linux_only( name = "rgbd_sensor_async_gl_test", timeout = "moderate", data = [ ":test/rgbd_sensor_async_gl_test.dmd.yaml", "@drake_models//:manipulation_station", ], # TODO(#21420) This test is currently broken on Ubuntu 24.04 ("Noble"). enable_condition = "//tools:ubuntu_jammy", tags = vtk_test_tags() + [ # Similar to #7520, the GL vendor's libraries are not sufficiently # instrumented for compatibility with TSan. "no_tsan", ], deps = [ ":image_writer", ":rgbd_sensor", ":rgbd_sensor_async", "//common/trajectories:piecewise_pose", "//geometry/render_gl", "//multibody/parsing", "//multibody/plant", "//systems/analysis:simulator", ], ) drake_cc_googletest( name = "rotary_encoders_test", deps = [ ":rotary_encoders", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:symbolic_test_util", "//systems/framework/test_utilities", ], ) drake_cc_googletest( name = "image_to_lcm_image_array_t_test", deps = [":image_to_lcm_image_array_t"], ) drake_cc_googletest( name = "lcm_image_array_to_images_test", data = glob([ "test/*.jpg", "test/*.png", ]), deps = [ ":lcm_image_array_to_images", "//common:find_resource", "//lcmtypes:image_array", ], ) drake_cc_googletest( name = "sim_rgbd_sensor_test", deps = [ ":image_to_lcm_image_array_t", ":rgbd_sensor", ":sim_rgbd_sensor", "//common/test_utilities:eigen_matrix_compare", "//lcm:drake_lcm", "//multibody/plant", "//systems/framework:diagram_builder", "//systems/lcm:lcm_publisher_system", "@fmt", ], ) drake_cc_googletest( name = "vtk_diagnostic_event_observer_test", deps = [ ":vtk_diagnostic_event_observer", ], ) drake_cc_googletest( name = "vtk_image_reader_writer_test", deps = [ ":image_io_test_params", ":vtk_image_reader_writer", "//common:temp_directory", "//common/test_utilities:expect_throws_message", "@vtk_internal//:vtkCommonCore", "@vtk_internal//:vtkCommonDataModel", "@vtk_internal//:vtkIOImage", ], ) add_lint_tests()
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/image_writer.h
#pragma once /** @file Provides utilities for writing images to disk. This file provides two sets of utilities: stand alone methods that can be invoked in any context and a System that can be connected into a diagram to automatically capture images during simulation at a fixed frequency. */ #include <string> #include <unordered_map> #include <utility> #include <vector> #include "drake/common/drake_copyable.h" #include "drake/systems/framework/leaf_system.h" #include "drake/systems/sensors/image.h" namespace drake { namespace systems { namespace sensors { /** @name Utility functions for writing common image types to disk. Given a fully-specified path to the file to write and corresponding image data, these functions will _attempt_ to write the image data to the file. The functions assume that the path is valid and writable. These functions will attempt to write the image to the given file path. The file format will be that indicated by the function name, but the extension will be whatever is provided as input. These function do not do validation on the provided file path (existence, writability, correspondence with image type, etc.) It relies on the caller to have done so. */ //@{ // TODO(jwnimmer-tri) Deprecate these in favor of the full-fledged ImageIo. /** Writes the color (8-bit, RGBA) image data to disk. */ void SaveToPng(const ImageRgba8U& image, const std::string& file_path); /** Writes the depth (32-bit) image data to disk. A 32-bit depth image can only be saved as TIFF (not PNG) because PNG files do not support channels larger than 16-bits and its support for floating point values is also limited at best. See ConvertDepth32FTo16U() for converting 32-bit to 16-bit to enable saving as PNG. */ void SaveToTiff(const ImageDepth32F& image, const std::string& file_path); /** Writes the depth (16-bit) image data to disk. See ConvertDepth16UTo32F() for converting 16-bit to 32-bit to enable saving as TIFF. */ void SaveToPng(const ImageDepth16U& image, const std::string& file_path); /** Writes the label (16-bit) image data to disk. */ void SaveToPng(const ImageLabel16I& image, const std::string& file_path); /** Writes the grey scale (8-bit) image data to disk. */ void SaveToPng(const ImageGrey8U& image, const std::string& file_path); //@} /** A system for periodically writing images to the file system. The system also provides direct image writing via a forced publish event. The system does not have a fixed set of input ports; the system can have an arbitrary number of image input ports. Each input port is independently configured with respect to: - publish frequency, - write location (directory) and image name, - input image format (which, in turn, implies a file-system format), - port name (which needs to be unique across all input ports in this system), and - context time at which output starts. By design, this system is intended to work with RgbdCamera, but can connect to any output port that provides images. @system name: ImageWriter input_ports: - (user assigned port name) - ... - (user assigned port name) @endsystem %ImageWriter supports three specific types of images: - ImageRgba8U - typically a color image written to disk as .png images. - ImageDepth32F - typically a depth image, written to disk as .tiff images. - ImageLabel16I - typically a label image, written to disk as .png images. - ImageDepth16U - typically a depth image, written to disk as .png images. - ImageGrey8U - typically a grey scale image, written to disk as .png images. Input ports are added to an %ImageWriter via DeclareImageInputPort(). See that function's documentation for elaboration on how to configure image output. It is important to note, that every declared image input port _must_ be connected; otherwise, attempting to write an image from that port, will cause an error in the system. If the user intends to write images directly instead of periodically, e.g., when running this system outside of Simulator::AdvanceTo, a call to `ForcedPublish(system_context)` will write all images from each input port simultaneously to disk. Note that one can invoke a forced publish on this system using the same context multiple times, resulting in multiple write operations, with each operation overwriting the same file(s). */ class ImageWriter : public LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ImageWriter) /** Constructs default instance with no image ports. */ ImageWriter(); /** Declares and configures a new image input port. A port is configured by providing: - a unique port name, - an output file format string, - a publish period, - a start time, and - an image type. Each port is evaluated independently, so that two ports on the same %ImageWriter can write images to different locations at different frequencies, etc. If images are to be kept in sync (e.g., registered color and depth images), they should be given the same period and start time. <h3>Specifying the times at which images are written</h3> Given a _positive_ publish period `p`, images will be written at times contained in the list of times: `t = [0, 1⋅p, 2⋅p, ...]`. The start time parameter determines what the _first_ output time will be. Given a "start time" value `tₛ`, the frames will be written at: `t = tₛ + [0, 1⋅p, 2⋅p, ...]`. <h3>Specifying write location and output file names</h3> When writing image data to disk, the location and name of the output files are controlled by a user-defined format string. The format string should be compatible with `fmt::format()`. %ImageWriter provides several _named_ format arguments that can be referenced in the format string: - `port_name` - The name of the port (see below). - `image_type` - One of `color`, `depth`, or `label`, depending on the image type requested. - `time_double` - The time (in seconds) stored in the context at the invocation of Publish(), represented as a double. - `time_usec` - The time (in microseconds) stored in the context at the invocation of Publish(), represented as a 64-bit integer. - `time_msec` - The time (in milliseconds) stored in the context at the invocation of Publish(), represented as an integer. - `count` - The number of write operations that have occurred from this port since system creation or the last invocation of ResetAllImageCounts() (the first write operation would get zero, the Nᵗʰ would get N - 1). This value increments _every_ time a write operation occurs. File names can then be specified as shown in the following examples (assuming the port was declared as a color image port, with a name of "my_port", a period of 0.02 s (50 Hz), and a start time of 5 s. - `/home/user/images/{port_name}/{time_usec}` creates a sequence like: - `/home/user/images/my_port/5000000.png` - `/home/user/images/my_port/5020000.png` - `/home/user/images/my_port/5040000.png` - ... - `/home/user/images/{image_type}/{time_msec:05}` creates a sequence like: - `/home/user/images/color/05000.png` - `/home/user/images/color/05020.png` - `/home/user/images/color/05040.png` - ... - `/home/user/{port_name}/my_image_{count:03}.txt` creates a sequence like: - `/home/user/my_port/my_image_000.txt.png` - `/home/user/my_port/my_image_001.txt.png` - `/home/user/my_port/my_image_002.txt.png` - ... We call attention particularly to the following: - Note the zero-padding arguments in the second and third examples. Making use of zero-padding typically facilitates _other_ processes. - If the file name format does not end with an appropriate extension (e.g., `.png` or `.tiff`), the extension will be added. - The directory specified in the format will be tested for validity (does it exist, is it a directory, can the program write to it). The full _file name_ will _not_ be validated. If it is invalid (e.g., too long, invalid characters, bad format substitution), images will silently not be created. - The third example uses the count flag -- regardless of start time, the first file written will always be zero, the second one, etc. - The directory can *only* depend `port_name` and `image_type`. It _cannot_ depend on values that change over time (e.g., `time_double`, `count`, etc. @param port_name The name of the port (must be unique among all image ports). This string is available in the format string as `port_name`. @param file_name_format The `fmt::format()`-compatible string which defines the context-dependent file name to write the image to. @param publish_period The period at which images read from this input port are written in calls to Publish(). @param start_time The minimum value for the context's time at which images will be written in calls to Publish(). @param pixel_type The representation of the per-pixel data (see PixelType). Must be one of {PixelType::kRgba8U, PixelType::kDepth32F, PixelType::kLabel16I, PixelType::kDepth16U, or PixelType::kGrey8U}. @throws std::exception if (1) the directory encoded in the `file_name_format` is not "valid" (see documentation above for definition), (2) `publish_period` is not positive, (3) `port_name` is used by a previous input port, or (4) `pixel_type` is not supported. */ const InputPort<double>& DeclareImageInputPort(PixelType pixel_type, std::string port_name, std::string file_name_format, double publish_period, double start_time); /** (Advanced) An overload where PixelType is a template parameter instead of a runtime parameter. @exclude_from_pydrake_mkdoc{This overload is not bound in pydrake.} */ template <PixelType kPixelType> const InputPort<double>& DeclareImageInputPort(std::string port_name, std::string file_name_format, double publish_period, double start_time); // Resets the saved image count for all declared input ports to zero. void ResetAllImageCounts() const; private: #ifndef DRAKE_DOXYGEN_CXX // Friend for facilitating unit testing. friend class ImageWriterTester; #endif // Does the work of writing image indexed by `index` to the disk. template <PixelType kPixelType> void WriteImage(const Context<double>& context, int index) const; // Writes an image for each configured input port. EventStatus WriteAllImages(const Context<double>& context) const; // Creates a file name from the given format string and time. std::string MakeFileName(const std::string& format, PixelType pixel_type, double time, const std::string& port_name, int count) const; // Given the file format string (and port-specific configuration values), // extracts, tests, and returns the output folder information. // The return value will not contain a trailing slash. // The tests are in support of the statement that the directory path cannot // depend on time. // Examples: // "a/b/c/" --> thrown exception. // "a/b/c" --> "a/b" // "a/{time_usec}/c" --> thrown exception. // "a/{port_name}/c" --> "a/my_port" (assuming port_name = "my_port"). std::string DirectoryFromFormat(const std::string& format, const std::string& port_name, PixelType pixel_type) const; enum class FolderState { kValid, kMissing, kIsFile, kUnwritable }; // Returns true if the directory path provided is valid: it exists, it's a // directory, and it's writable. static FolderState ValidateDirectory(const std::string& file_path); // The per-input port data. struct ImagePortInfo { ImagePortInfo(std::string format_in, PixelType pixel_type_in) : format(std::move(format_in)), pixel_type(pixel_type_in) {} const std::string format; const PixelType pixel_type; // NOTE: This is made mutable as a low-cost mechanism for incrementing // image writes without involving the overhead of discrete state. mutable int count{0}; // TODO(SeanCurtis-TRI): For copying this system, it may be necessary to // also store the period and start time so that the ports in the copy can // be properly instantiated. }; // For each input port, this stores the corresponding image data. It is an // invariant that port_info_.size() == num_input_ports(). std::vector<ImagePortInfo> port_info_; std::unordered_map<PixelType, std::string> labels_; std::unordered_map<PixelType, std::string> extensions_; }; } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/beam_model.cc
#include "drake/systems/sensors/beam_model.h" #include <memory> #include "drake/common/default_scalars.h" #include "drake/common/random.h" namespace drake { namespace systems { namespace sensors { template <typename T> BeamModel<T>::BeamModel(int num_depth_readings, double max_range) : LeafSystem<T>(SystemTypeTag<BeamModel>{}), max_range_(max_range) { DRAKE_DEMAND(num_depth_readings > 0); DRAKE_DEMAND(max_range >= 0.0); // Declare depth input port. this->DeclareInputPort("depth", kVectorValued, num_depth_readings); // Declare "event" random input port. this->DeclareInputPort("event", kVectorValued, num_depth_readings, RandomDistribution::kUniform); // Declare "hit" random input port. this->DeclareInputPort("hit", kVectorValued, num_depth_readings, RandomDistribution::kGaussian); // Declare "short" random input port. this->DeclareInputPort("short", kVectorValued, num_depth_readings, RandomDistribution::kExponential); // Declare "uniform" random input port. this->DeclareInputPort("uniform", kVectorValued, num_depth_readings, RandomDistribution::kUniform); // Declare measurement output port. this->DeclareVectorOutputPort("depth", num_depth_readings, &BeamModel<T>::CalcOutput); this->DeclareNumericParameter(BeamModelParams<T>()); // Add a constraint that the "event" probabilities in BeamModelParams sum to // one. Since probability_hit() is defined implicitly, this becomes the // inequality constraint: // 1 - probability_short() - probability_miss() - probability_uniform() ≥ 0. ContextConstraintCalc<T> calc_event_probabilities_constraint = [](const Context<T>& context, VectorX<T>* value) { const auto* params = dynamic_cast<const BeamModelParams<T>*>( &context.get_numeric_parameter(0)); DRAKE_DEMAND(params != nullptr); (*value)[0] = 1.0 - params->probability_short() - params->probability_miss() - params->probability_uniform(); }; this->DeclareInequalityConstraint( calc_event_probabilities_constraint, SystemConstraintBounds(Vector1d(0), std::nullopt), "event probabilities sum to one"); } template <typename T> template <typename U> BeamModel<T>::BeamModel(const BeamModel<U>& other) : BeamModel<T>(other.max_range(), other.get_depth_input_port().size()) {} template <typename T> BeamModelParams<T>& BeamModel<T>::get_mutable_parameters( Context<T>* context) const { return this->template GetMutableNumericParameter<BeamModelParams>(context, 0); } template <typename T> void BeamModel<T>::CalcOutput(const systems::Context<T>& context, BasicVector<T>* output) const { const auto params = dynamic_cast<const BeamModelParams<T>*>( &context.get_numeric_parameter(0)); DRAKE_DEMAND(params != nullptr); const auto& depth = get_depth_input_port().Eval(context); const auto& w_event = get_event_random_input_port().Eval(context); const auto& w_hit = get_hit_random_input_port().Eval(context); const auto& w_short = get_short_random_input_port().Eval(context); const auto& w_uniform = get_uniform_random_input_port().Eval(context); auto measurement = output->get_mutable_value(); // Loop through depth inputs and compute a noisy measurement based on the // mixture model. for (int i = 0; i < static_cast<int>(depth.size()); i++) { if (w_event[i] <= params->probability_uniform()) { // Then "uniform". measurement[i] = max_range_ * w_uniform[i]; } else if (w_event[i] <= params->probability_uniform() + params->probability_miss()) { // Then "miss". measurement[i] = max_range_; } else if (w_event[i] <= params->probability_uniform() + params->probability_miss() + params->probability_short() && (w_short[i] / params->lambda_short()) <= depth[i]) { // Then "short". // Note: Returns that would have been greater than depth[i] are instead // evaluated as "hit". measurement[i] = w_short[i] / params->lambda_short(); } else { // Then "hit". // Note: The tails of the Gaussian distribution are truncated to return // a value in [0, max_range_]. (Both) tails of the distribution are // treated as missed returns, so return max_range_. measurement[i] = depth[i] + params->sigma_hit() * w_hit[i]; if (measurement[i] < 0.0 || measurement[i] > max_range_) { measurement[i] = max_range_; } } } } } // namespace sensors } // namespace systems } // namespace drake DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_NONSYMBOLIC_SCALARS( class ::drake::systems::sensors::BeamModel)
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/rotary_encoders.cc
#include "drake/systems/sensors/rotary_encoders.h" #include <algorithm> #include <cmath> #include <iterator> #include <numeric> #include <vector> #include "drake/common/default_scalars.h" #include "drake/common/eigen_types.h" #include "drake/common/unused.h" #include "drake/systems/framework/basic_vector.h" namespace drake { namespace systems { namespace sensors { namespace { // Return a vector of the given size, with result[i] == i. std::vector<int> vector_iota(int size) { std::vector<int> result(size); std::iota(std::begin(result), std::end(result), 0); return result; } } // namespace template <typename T> RotaryEncoders<T>::RotaryEncoders(const std::vector<int>& ticks_per_revolution) : RotaryEncoders( ticks_per_revolution.size() /* input_port_size */, vector_iota(ticks_per_revolution.size()) /* input_vector_indices */, ticks_per_revolution) {} template <typename T> RotaryEncoders<T>::RotaryEncoders(int input_port_size, const std::vector<int>& input_vector_indices) : RotaryEncoders(input_port_size, input_vector_indices, std::vector<int>() /* ticks_per_revolution */) {} template <typename T> RotaryEncoders<T>::RotaryEncoders(int input_port_size, const std::vector<int>& input_vector_indices, const std::vector<int>& ticks_per_revolution) : VectorSystem<T>(SystemTypeTag<RotaryEncoders>{}, input_port_size, input_vector_indices.size() /* output_port_size */), num_encoders_(input_vector_indices.size()), indices_(input_vector_indices), ticks_per_revolution_(ticks_per_revolution) { DRAKE_DEMAND(input_port_size >= 0); DRAKE_ASSERT(*std::min_element(indices_.begin(), indices_.end()) >= 0); DRAKE_ASSERT(*std::max_element(indices_.begin(), indices_.end()) < input_port_size); DRAKE_DEMAND(ticks_per_revolution_.empty() || indices_.size() == ticks_per_revolution_.size()); DRAKE_ASSERT(ticks_per_revolution_.empty() || *std::min_element(ticks_per_revolution_.begin(), ticks_per_revolution_.end()) >= 0); // This vector is numeric parameter 0. this->DeclareNumericParameter( BasicVector<T>(VectorX<T>::Zero(num_encoders_))); } template <typename T> template <typename U> RotaryEncoders<T>::RotaryEncoders(const RotaryEncoders<U>& other) : RotaryEncoders(other.get_input_port().size(), other.indices_, other.ticks_per_revolution_) {} template <typename T> void RotaryEncoders<T>::DoCalcVectorOutput( const Context<T>& context, const Eigen::VectorBlock<const VectorX<T>>& input, const Eigen::VectorBlock<const VectorX<T>>& state, Eigen::VectorBlock<VectorX<T>>* output) const { unused(state); const VectorX<T>& calibration_offsets = context.get_numeric_parameter(0).value(); DRAKE_ASSERT(calibration_offsets.size() == num_encoders_); // Loop through the outputs. Eigen::VectorBlock<VectorX<T>>& y = *output; for (int i = 0; i < num_encoders_; i++) { const int index = indices_.empty() ? i : indices_[i]; // Calibration. y(i) = input(index) - calibration_offsets(i); // Quantization. if (!ticks_per_revolution_.empty()) { using std::floor; const T ticks_per_radian = ticks_per_revolution_[i] / (2.0 * M_PI); y(i) = floor(y(i) * ticks_per_radian) / ticks_per_radian; } } } template <typename T> void RotaryEncoders<T>::set_calibration_offsets( Context<T>* context, const Eigen::Ref<VectorX<T>>& calibration_offsets) const { DRAKE_DEMAND(calibration_offsets.rows() == num_encoders_); context->get_mutable_numeric_parameter(0).set_value(calibration_offsets); } template <typename T> const VectorX<T>& RotaryEncoders<T>::get_calibration_offsets( const Context<T>& context) const { return context.get_numeric_parameter(0).value(); } } // namespace sensors } // namespace systems } // namespace drake DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::sensors::RotaryEncoders)
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/camera_config_functions.h
#pragma once #include "drake/geometry/scene_graph.h" #include "drake/lcm/drake_lcm_interface.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/lcm/lcm_buses.h" #include "drake/systems/sensors/camera_config.h" namespace drake { namespace systems { namespace sensors { /** Constructs a simulated camera sensor (rgbd sensor and publishing systems) within `builder`. As specified, the RGB, depth, and/or label images from the camera are published via `lcm` on the channel <tt>DRAKE_RGBD_CAMERA_IMAGES_{camera_config.name}</tt>. @param[in] config The camera configuration. @param[in,out] builder The diagram to add sensor and publishing systems into. @param[in] lcm_buses (Optional) The available LCM buses to use for camera message publication. When not provided, uses the `lcm` interface if provided, or else the `config.lcm_bus` must be set to "default" in which case an appropriate drake::lcm::DrakeLcm object is constructed and used internally. @param[in] plant (Optional) The MultibodyPlant to use for kinematics. In the common case where a MultibodyPlant has already been added to `builder` using either AddMultibodyPlant() or AddMultibodyPlantSceneGraph(), the default value (nullptr) here is suitable and generally should be preferred. When provided, it must be a System that's been added to the given `builder`. When not provided, uses the system named "plant" in the given `builder`. @param[in] scene_graph (Optional) The SceneGraph to use for rendering. In the common case where a SceneGraph has already been added to `builder` using either AddMultibodyPlant() or AddMultibodyPlantSceneGraph(), the default value (nullptr) here is suitable and generally should be preferred. When provided, it must be a System that's been added to the given `builder`. When not provided, uses the system named "scene_graph" in the given `builder`. @param[in] lcm (Optional) The LCM interface used for visualization message publication. When not provided, uses the `config.lcm_bus` value to look up the appropriate interface from `lcm_buses`. @throws std::exception if camera_config contains invalid values. @pre The `builder` is non-null. @pre Either the `config.lcm_bus` is set to "default", or else `lcm_buses` is non-null and contains a bus named `config.lcm_bus`, or else `lcm` is non-null. @pre Either the given `builder` contains a MultibodyPlant system named "plant" or else the provided `plant` is non-null. @pre Either the given `builder` contains a SceneGraph system named "scene_graph" or else the provided `scene_graph` is non-null. @see drake::multibody::AddMultibodyPlant() @see drake::systems::lcm::ApplyLcmBusConfig() */ void ApplyCameraConfig(const CameraConfig& config, DiagramBuilder<double>* builder, const systems::lcm::LcmBuses* lcm_buses = nullptr, const multibody::MultibodyPlant<double>* plant = nullptr, geometry::SceneGraph<double>* scene_graph = nullptr, drake::lcm::DrakeLcmInterface* lcm = nullptr); } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/image.cc
#include "drake/systems/sensors/image.h" #include <algorithm> namespace drake { namespace systems { namespace sensors { namespace { /* Converts an input depth image to an output depth image using the given per-pixel conversion function. */ template <typename InputImage, typename OutputImage, typename Func> void ConvertDepthPixelwise(const InputImage& input, OutputImage* output, Func func) { const int width = input.width(); const int height = input.height(); if (!(output->width() == width && output->height() == height)) { output->resize(width, height); } const int size = input.size(); if (size == 0) { return; } const typename InputImage::T* const in = input.at(0, 0); typename OutputImage::T* const out = output->at(0, 0); for (int i = 0; i < size; ++i) { out[i] = func(in[i]); } } } // namespace // N.B. The `output` images below are phrased as an output argument rather than // a return value to allow the caller to reuse the same storage from one Convert // call to the next. void ConvertDepth32FTo16U(const ImageDepth32F& input, ImageDepth16U* output) { DRAKE_THROW_UNLESS(output != nullptr); ConvertDepthPixelwise( input, output, [](const ImageDepth32F::T pixel) -> ImageDepth16U::T { // Start by scaling from meters to millimeters, keeping all math as // 32-bit floats to mitigate roundoff errors. float result = pixel * 1000.0f; // Clamp too-far values (including +Inf and NaN) to the 16-bit constant. result = std::min<float>(ImageDepth16U::Traits::kTooFar, result); // Clamp too-close values (including -Inf) to the 16-bit constant. result = std::max<float>(ImageDepth16U::Traits::kTooClose, result); // Truncate towards zero. return result; }); } void ConvertDepth16UTo32F(const ImageDepth16U& input, ImageDepth32F* output) { DRAKE_THROW_UNLESS(output != nullptr); ConvertDepthPixelwise( input, output, [](const ImageDepth16U::T pixel) -> ImageDepth32F::T { using InPixel = ImageDepth16U::Traits; using OutPixel = ImageDepth32F::Traits; // No special case is necessary for kTooClose. static_assert(InPixel::kTooClose == 0 && OutPixel::kTooClose == 0); // Scale from millimeters to meters, with kTooFar as a special case, // using intermediate 64-bit doubles to mitigate roundoff errors. return (pixel == InPixel::kTooFar) ? OutPixel::kTooFar : 0.001 * pixel; }); } } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/image_io_internal.cc
#include "drake/systems/sensors/image_io_internal.h" #include <array> #include <fstream> #include <string> #include "drake/common/drake_assert.h" namespace drake { namespace systems { namespace sensors { namespace internal { namespace fs = std::filesystem; std::optional<ImageFileFormat> FileFormatFromExtension( const fs::path& filename) { std::string ext = filename.extension(); std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return std::tolower(c); }); if (ext == ".jpeg") { return ImageFileFormat::kJpeg; } else if (ext == ".jpg") { return ImageFileFormat::kJpeg; } else if (ext == ".png") { return ImageFileFormat::kPng; } else if (ext == ".tiff") { return ImageFileFormat::kTiff; } else if (ext == ".tif") { return ImageFileFormat::kTiff; } return std::nullopt; } namespace { /* Returns the first N bytes of the given input, or else all-zero bytes if something went wrong (e.g., can't open the file, too short, etc.) */ template <size_t N> std::array<uint8_t, N> ReadHeader( std::variant<const fs::path*, ImageIo::ByteSpan> input_any) { std::array<uint8_t, N> result = {0}; if (input_any.index() == 0) { const fs::path& path = *std::get<0>(input_any); std::ifstream file(path, std::ios::binary); std::array<char, N> buffer; file.read(buffer.data(), N); if (file.good()) { std::memcpy(result.data(), buffer.data(), N); } } else { const ImageIo::ByteSpan& buffer = std::get<1>(input_any); if (buffer.size >= N) { std::memcpy(result.data(), buffer.data, N); } } return result; } } // namespace // Implementation note: VTK does have functions to guess the image type, but // they are pretty complicated. For our narrow set of supported file formats, // we can do it ourselves on the cheap. std::optional<ImageFileFormat> GuessFileFormat( std::variant<const fs::path*, ImageIo::ByteSpan> input_any) { const std::array<uint8_t, 2> header = ReadHeader<2>(input_any); // https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format if (header[0] == 0xff && header[1] == 0xd8) { return ImageFileFormat::kJpeg; } // https://en.wikipedia.org/wiki/PNG if (header[0] == 0x89 && header[1] == 0x50) { return ImageFileFormat::kPng; } // https://en.wikipedia.org/wiki/TIFF if ((header[0] == 0x49 && header[1] == 0x49) || (header[0] == 0x4d && header[1] == 0x4d)) { return ImageFileFormat::kTiff; } return std::nullopt; } } // namespace internal } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/pixel_types.cc
#include "drake/systems/sensors/pixel_types.h" #include "drake/common/drake_assert.h" namespace drake { namespace systems { namespace sensors { std::string to_string(PixelType x) { switch (x) { case PixelType::kRgb8U: return "Rgb8U"; case PixelType::kBgr8U: return "Bgr8U"; case PixelType::kRgba8U: return "Rgba8U"; case PixelType::kBgra8U: return "Bgra8U"; case PixelType::kGrey8U: return "Grey8U"; case PixelType::kDepth16U: return "Depth16U"; case PixelType::kDepth32F: return "Depth32F"; case PixelType::kLabel16I: return "Label16I"; } DRAKE_UNREACHABLE(); } std::string to_string(PixelFormat x) { switch (x) { case PixelFormat::kRgb: return "Rgb"; case PixelFormat::kBgr: return "Bgr"; case PixelFormat::kRgba: return "Rgba"; case PixelFormat::kBgra: return "Bgra"; case PixelFormat::kGrey: return "Grey"; case PixelFormat::kDepth: return "Depth"; case PixelFormat::kLabel: return "Label"; } DRAKE_UNREACHABLE(); } std::string to_string(PixelScalar x) { switch (x) { case PixelScalar::k8U: return "8U"; case PixelScalar::k16I: return "16I"; case PixelScalar::k16U: return "16U"; case PixelScalar::k32F: return "32F"; } DRAKE_UNREACHABLE(); } } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/image_io_internal.h
#pragma once #include <algorithm> #include <filesystem> #include <optional> #include <variant> // To ease build system upkeep, we annotate VTK includes with their deps. #include <vtkType.h> // vtkCommonCore #include "drake/common/drake_assert.h" #include "drake/systems/sensors/image.h" #include "drake/systems/sensors/image_file_format.h" #include "drake/systems/sensors/image_io.h" // This file contains low-level ImageIo helper functions that are carved out in // support of direct unit testing. namespace drake { namespace systems { namespace sensors { namespace internal { /* Guesses a file format for the given filename, based on its extension. */ std::optional<ImageFileFormat> FileFormatFromExtension( const std::filesystem::path& filename); /* Guesses a file format for the given input using the initial few bytes of the file header. If the header is unintelligible, silently returns nullopt. */ std::optional<ImageFileFormat> GuessFileFormat( std::variant<const std::filesystem::path*, ImageIo::ByteSpan> input_any); /* Returns true iff the PixelType's channel ordering is BGR (in which case it will need to be reversed to match VTK's convention of RGB ordering). */ template <PixelType kPixelType> constexpr bool NeedsBgrSwizzle() { switch (kPixelType) { case PixelType::kBgr8U: case PixelType::kBgra8U: { return true; } case PixelType::kDepth16U: case PixelType::kDepth32F: case PixelType::kGrey8U: case PixelType::kLabel16I: case PixelType::kRgb8U: case PixelType::kRgba8U: return false; } DRAKE_UNREACHABLE(); } /* Returns the VTK scalar type enum for the given PixelType. */ template <PixelType kPixelType> constexpr int GetVtkScalarType() { switch (ImageTraits<kPixelType>::kPixelScalar) { case PixelScalar::k8U: return VTK_TYPE_UINT8; case PixelScalar::k16U: return VTK_TYPE_UINT16; case PixelScalar::k32F: return VTK_TYPE_FLOAT32; case PixelScalar::k16I: // As a backwards compatibility hack, we save 16I data into 16U. return VTK_TYPE_UINT16; } DRAKE_UNREACHABLE(); } /* Returns the Drake image scalar enum for the given VTK scalar type enum. */ constexpr std::optional<PixelScalar> GetDrakeScalarType(int vtk_scalar) { switch (vtk_scalar) { case VTK_TYPE_UINT8: return PixelScalar::k8U; case VTK_TYPE_UINT16: return PixelScalar::k16U; case VTK_TYPE_FLOAT32: return PixelScalar::k32F; default: break; } return std::nullopt; } /* Copies pixel data from one memory buffer to another, flipping the image vertically where the bottom row of `source` becomes the top row of `dest`. This implementation allows for a differing number of source and dest channels, but does not allow for anything more complicated (e.g., gaps in any strides). @tparam T Channel type scalar (typically uint8_t, uint16_t, or float). @tparam source_channels Number of source channels (typically 1, 3, or 4). @tparam swizzle Whether to swizzle channels (i.e., changing BGR to RGB). @tparam dest_channels Number of destination channels (typically 1, 3, or 4). This option is intended to either add or remove the alpha channel, so it must be within ±1 of source_channels. @tparam dest_pad Filler value to use when when dest_channels > source_channels. @param source Source memory buffer. @param dest Destination memory buffer. @param width Image width. @param height Image height. */ template <typename T, int source_channels, bool swizzle, int dest_channels = source_channels, uint8_t dest_pad = 0xff> void CopyAndFlipRaw(const T* source, T* dest, int width, int height) { static_assert(dest_channels >= source_channels - 1); static_assert(dest_channels <= source_channels + 1); constexpr int min_channels = std::min(source_channels, dest_channels); // Fast forward `dest` to point to the start of the final row. dest += (height - 1) * width * dest_channels; for (int v = 0; v < height; ++v) { for (int u = 0; u < width; ++u) { int c = 0; for (; c < min_channels; ++c) { const int source_channel = swizzle ? (min_channels - c - 1) : c; *(dest++) = source[source_channel]; } source += source_channels; for (; c < dest_channels; ++c) { *(dest++) = dest_pad; } } // Currently `dest` points just past the end of row we just copied. // Rewind it two rows worth, so it points to the start of the prior row. dest -= 2 * width * dest_channels; } } } // namespace internal } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/rgbd_sensor.cc
#include "drake/systems/sensors/rgbd_sensor.h" #include <limits> #include <utility> #include "drake/common/text_logging.h" #include "drake/geometry/scene_graph.h" namespace drake { namespace systems { namespace sensors { using geometry::FrameId; using geometry::QueryObject; using geometry::SceneGraph; using geometry::render::ColorRenderCamera; using geometry::render::DepthRenderCamera; using math::RigidTransformd; RgbdSensor::RgbdSensor(FrameId parent_id, const RigidTransformd& X_PB, const DepthRenderCamera& depth_camera, bool show_color_window) : RgbdSensor(parent_id, X_PB, ColorRenderCamera(depth_camera.core(), show_color_window), depth_camera) {} RgbdSensor::RgbdSensor(FrameId parent_id, const RigidTransformd& X_PB, ColorRenderCamera color_camera, DepthRenderCamera depth_camera) : parent_frame_id_(parent_id), color_camera_(std::move(color_camera)), depth_camera_(std::move(depth_camera)), X_PB_(X_PB) { const CameraInfo& color_intrinsics = color_camera_.core().intrinsics(); const CameraInfo& depth_intrinsics = depth_camera_.core().intrinsics(); query_object_input_port_ = &this->DeclareAbstractInputPort( "geometry_query", Value<geometry::QueryObject<double>>{}); ImageRgba8U color_image(color_intrinsics.width(), color_intrinsics.height()); color_image_port_ = &this->DeclareAbstractOutputPort( "color_image", color_image, &RgbdSensor::CalcColorImage); ImageDepth32F depth32(depth_intrinsics.width(), depth_intrinsics.height()); depth_image_32F_port_ = &this->DeclareAbstractOutputPort( "depth_image_32f", depth32, &RgbdSensor::CalcDepthImage32F); ImageDepth16U depth16(depth_intrinsics.width(), depth_intrinsics.height()); depth_image_16U_port_ = &this->DeclareAbstractOutputPort( "depth_image_16u", depth16, &RgbdSensor::CalcDepthImage16U); ImageLabel16I label_image(color_intrinsics.width(), color_intrinsics.height()); label_image_port_ = &this->DeclareAbstractOutputPort( "label_image", label_image, &RgbdSensor::CalcLabelImage); body_pose_in_world_output_port_ = &this->DeclareAbstractOutputPort( "body_pose_in_world", &RgbdSensor::CalcX_WB); image_time_output_port_ = &this->DeclareVectorOutputPort( "image_time", 1, &RgbdSensor::CalcImageTime, {this->time_ticket()}); // The depth_16U represents depth in *millimeters*. With 16 bits there is // an absolute limit on the farthest distance it can register. This tests to // see if the user has specified a maximum depth value that exceeds that // value. const float kMaxValidDepth16UInM = (std::numeric_limits<uint16_t>::max() - 1) / 1000.; const double max_depth = depth_camera_.depth_range().max_depth(); if (max_depth > kMaxValidDepth16UInM) { drake::log()->warn( "Specified max depth is {} m > max valid depth for 16 bits {} m. " "depth_image_16u might not be able to capture the full depth range.", max_depth, kMaxValidDepth16UInM); } } const InputPort<double>& RgbdSensor::query_object_input_port() const { return *query_object_input_port_; } const OutputPort<double>& RgbdSensor::color_image_output_port() const { return *color_image_port_; } const OutputPort<double>& RgbdSensor::depth_image_32F_output_port() const { return *depth_image_32F_port_; } const OutputPort<double>& RgbdSensor::depth_image_16U_output_port() const { return *depth_image_16U_port_; } const OutputPort<double>& RgbdSensor::label_image_output_port() const { return *label_image_port_; } const OutputPort<double>& RgbdSensor::body_pose_in_world_output_port() const { return *body_pose_in_world_output_port_; } const OutputPort<double>& RgbdSensor::image_time_output_port() const { return *image_time_output_port_; } void RgbdSensor::CalcColorImage(const Context<double>& context, ImageRgba8U* color_image) const { const QueryObject<double>& query_object = get_query_object(context); query_object.RenderColorImage(color_camera_, parent_frame_id_, X_PB_, color_image); } void RgbdSensor::CalcDepthImage32F(const Context<double>& context, ImageDepth32F* depth_image) const { const QueryObject<double>& query_object = get_query_object(context); query_object.RenderDepthImage(depth_camera_, parent_frame_id_, X_PB_, depth_image); } void RgbdSensor::CalcDepthImage16U(const Context<double>& context, ImageDepth16U* depth_image) const { ImageDepth32F depth32(depth_image->width(), depth_image->height()); CalcDepthImage32F(context, &depth32); ConvertDepth32FTo16U(depth32, depth_image); } void RgbdSensor::CalcLabelImage(const Context<double>& context, ImageLabel16I* label_image) const { const QueryObject<double>& query_object = get_query_object(context); query_object.RenderLabelImage(color_camera_, parent_frame_id_, X_PB_, label_image); } void RgbdSensor::CalcX_WB(const Context<double>& context, RigidTransformd* X_WB) const { DRAKE_DEMAND(X_WB != nullptr); if (parent_frame_id_ == SceneGraph<double>::world_frame_id()) { *X_WB = X_PB_; } else { const QueryObject<double>& query_object = get_query_object(context); *X_WB = query_object.GetPoseInWorld(parent_frame_id_) * X_PB_; } } void RgbdSensor::CalcImageTime(const Context<double>& context, BasicVector<double>* output) const { output->SetFromVector(Vector1d{context.get_time()}); } } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/lcm_image_traits.cc
#include "drake/systems/sensors/lcm_image_traits.h" // This is an empty file to confirm that our header parses on its own.
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/vtk_diagnostic_event_observer.h
#pragma once // To ease build system upkeep, we annotate VTK includes with their deps. #include <vtkCommand.h> // vtkCommonCore #include <vtkObject.h> // vtkCommonCore #include "drake/common/diagnostic_policy.h" #include "drake/common/drake_assert.h" #include "drake/common/drake_export.h" namespace drake { namespace systems { namespace sensors { namespace internal { /* Forwards warnings and/or errors from VTK into a Drake DiagnosticPolicy. */ class DRAKE_NO_EXPORT VtkDiagnosticEventObserver final : public vtkCommand { public: VtkDiagnosticEventObserver(); ~VtkDiagnosticEventObserver() final; static VtkDiagnosticEventObserver* New() { return new VtkDiagnosticEventObserver; } /* Sets where ErrorEvent and WarningEvent should forward to. This must be called immediately after construction. */ void set_diagnostic(const drake::internal::DiagnosticPolicy* diagnostic) { DRAKE_DEMAND(diagnostic != nullptr); diagnostic_ = diagnostic; } // NOLINTNEXTLINE(runtime/int) To match the VTK signature. void Execute(vtkObject*, unsigned long event, void* calldata) final; private: const drake::internal::DiagnosticPolicy* diagnostic_{}; }; } // namespace internal } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/camera_config_functions.cc
#include "drake/systems/sensors/camera_config_functions.h" #include <initializer_list> #include <map> #include <memory> #include <optional> #include <string> #include <fmt/format.h> #include "drake/common/eigen_types.h" #include "drake/common/never_destroyed.h" #include "drake/common/nice_type_name.h" #include "drake/common/overloaded.h" #include "drake/geometry/render/render_camera.h" #include "drake/geometry/render_gl/factory.h" #include "drake/geometry/render_gltf_client/factory.h" #include "drake/geometry/render_vtk/factory.h" #include "drake/math/rigid_transform.h" #include "drake/multibody/parsing/scoped_names.h" #include "drake/systems/lcm/lcm_config_functions.h" #include "drake/systems/sensors/rgbd_sensor.h" #include "drake/systems/sensors/rgbd_sensor_async.h" #include "drake/systems/sensors/sim_rgbd_sensor.h" namespace drake { namespace systems { namespace sensors { using drake::lcm::DrakeLcmInterface; using drake::systems::lcm::LcmBuses; using Eigen::Vector3d; using geometry::MakeRenderEngineGl; using geometry::MakeRenderEngineGltfClient; using geometry::MakeRenderEngineVtk; using geometry::RenderEngineGlParams; using geometry::RenderEngineGltfClientParams; using geometry::RenderEngineVtkParams; using geometry::SceneGraph; using geometry::render::ColorRenderCamera; using geometry::render::DepthRenderCamera; using internal::AddSimRgbdSensor; using internal::AddSimRgbdSensorLcmPublisher; using internal::SimRgbdSensor; using math::RigidTransformd; using multibody::Frame; using multibody::MultibodyPlant; using multibody::parsing::GetScopedFrameByName; namespace { // Given a valid string containing a supported RenderEngine class name, returns // the full name as would be returned by SceneGraph::GetRendererTypeName(). // @pre We already know that `class_name` is a "supported" value. const std::string& LookupEngineType(const std::string& class_name) { using Dict = std::map<std::string, std::string>; static const never_destroyed<Dict> type_lookup( std::initializer_list<Dict::value_type>{ {"RenderEngineVtk", "drake::geometry::render_vtk::internal::RenderEngineVtk"}, {"RenderEngineGl", "drake::geometry::render_gl::internal::RenderEngineGl"}, {"RenderEngineGltfClient", "drake::geometry::render_gltf_client::internal::" "RenderEngineGltfClient"}}); return type_lookup.access().at(class_name); } template <typename ParamsType> const char* GetEngineName(const ParamsType&) { if constexpr (std::is_same_v<ParamsType, RenderEngineVtkParams>) { return "RenderEngineVtk"; } else if constexpr (std::is_same_v<ParamsType, RenderEngineGlParams>) { return "RenderEngineGl"; // NOLINTNEXTLINE(readability/braces) The line break confuses the linter. } else if constexpr (std::is_same_v<ParamsType, RenderEngineGltfClientParams>) { return "RenderEngineGltfClient"; } } void MakeEngineByClassName(const std::string& class_name, const CameraConfig& config, SceneGraph<double>* scene_graph) { if (class_name == "RenderEngineGl") { if (!geometry::kHasRenderEngineGl) { throw std::logic_error( "Invalid camera configuration; renderer_class = 'RenderEngineGl' " "is not supported in current build."); } RenderEngineGlParams params{.default_clear_color = config.background}; scene_graph->AddRenderer(config.renderer_name, MakeRenderEngineGl(params)); return; } else if (class_name == "RenderEngineGltfClient") { scene_graph->AddRenderer(config.renderer_name, MakeRenderEngineGltfClient({})); return; } // Note: if we add *other* supported render engine implementations, add the // logic for detecting and instantiating those types here. // Fall through to the default render engine type (name is either empty or // the only remaining possible value: "RenderEngineVtk"). DRAKE_DEMAND(class_name.empty() || class_name == "RenderEngineVtk"); RenderEngineVtkParams params; const geometry::Rgba& rgba = config.background; params.default_clear_color = Vector3d{rgba.r(), rgba.g(), rgba.b()}; scene_graph->AddRenderer(config.renderer_name, MakeRenderEngineVtk(params)); } // Validates the render engine specification in `config`. If the specification // is valid, upon return, the specified RenderEngine is defined in `scene_graph` // (this may require creating the RenderEngine instance). Throws if the // specification is invalid. // @pre If config.renderer_class *names* a class, it is a "supported" value. void ValidateEngineAndMaybeAdd(const CameraConfig& config, SceneGraph<double>* scene_graph) { DRAKE_DEMAND(scene_graph != nullptr); // Querying for the type_name of the named renderer will simultaneously tell // if a render engine already exists (non-empty value) *and* give us a string // to match against config.renderer_class. const std::string type_name = scene_graph->GetRendererTypeName(config.renderer_name); // Non-empty type name says that it already exists. bool already_exists = !type_name.empty(); if (already_exists) { std::visit<void>( overloaded{ [&type_name, &config](const std::string& class_name) { if (!class_name.empty() && LookupEngineType(class_name) != type_name) { throw std::logic_error(fmt::format( "Invalid camera configuration; requested renderer_name " "= '{}' and renderer_class = '{}'. The name is already " "used with a different type: {}.", config.renderer_name, class_name, type_name)); } }, [&config](auto&&) { throw std::logic_error(fmt::format( "Invalid camera configuration; requested renderer_name " " = '{}' with renderer parameters, but the named renderer " "already exists. Only the first instance of the named " "renderer can use parameters.", config.renderer_name)); }}, config.renderer_class); } if (already_exists) return; std::visit<void>( overloaded{ [&config, scene_graph](const std::string& class_name) { MakeEngineByClassName(class_name, config, scene_graph); }, [&config, scene_graph](const RenderEngineVtkParams& params) { scene_graph->AddRenderer(config.renderer_name, MakeRenderEngineVtk(params)); }, [&config, scene_graph](const RenderEngineGlParams& params) { if (!geometry::kHasRenderEngineGl) { throw std::logic_error( "Invalid camera configuration; renderer_class = " "'RenderEngineGl' is not supported in current build."); } scene_graph->AddRenderer(config.renderer_name, MakeRenderEngineGl(params)); }, [&config, scene_graph](const RenderEngineGltfClientParams& params) { scene_graph->AddRenderer(config.renderer_name, MakeRenderEngineGltfClient(params)); }}, config.renderer_class); } } // namespace void ApplyCameraConfig(const CameraConfig& config, DiagramBuilder<double>* builder, const LcmBuses* lcm_buses, const MultibodyPlant<double>* plant, SceneGraph<double>* scene_graph, DrakeLcmInterface* lcm) { if (!(config.rgb || config.depth || config.label)) { return; } // Find the plant and scene graph. if (plant == nullptr) { plant = &builder->GetDowncastSubsystemByName<MultibodyPlant>("plant"); } if (scene_graph == nullptr) { scene_graph = &builder->GetMutableDowncastSubsystemByName<SceneGraph>("scene_graph"); } config.ValidateOrThrow(); ValidateEngineAndMaybeAdd(config, scene_graph); // Extract the camera extrinsics from the config struct. const Frame<double>& base_frame = config.X_PB.base_frame ? GetScopedFrameByName(*plant, *config.X_PB.base_frame) : plant->world_frame(); const RigidTransformd X_PB = config.X_PB.GetDeterministicValue(); // Extract camera intrinsics from the config struct. const auto [color_camera, depth_camera] = config.MakeCameras(); // Add the sensor system. When there is no output delay, we use an RgbdSensor; // when there is an output delay, we need to use an RgbdSensorAsync. System<double>* camera_sys{}; if (config.output_delay == 0.0) { const SimRgbdSensor sim_camera(config.name, base_frame, config.fps, X_PB, color_camera, depth_camera); camera_sys = AddSimRgbdSensor(*scene_graph, *plant, sim_camera, builder); } else { const auto [frame_A, X_AB] = internal::GetGeometryFrame(base_frame, X_PB); camera_sys = builder->AddSystem<RgbdSensorAsync>( scene_graph, frame_A, X_AB, config.fps, config.capture_offset, config.output_delay, (config.rgb || config.label) ? std::optional<ColorRenderCamera>{color_camera} : std::nullopt, config.depth ? std::optional<DepthRenderCamera>{depth_camera} : std::nullopt, config.label); camera_sys->set_name(fmt::format("rgbd_sensor_{}", config.name)); builder->Connect(scene_graph->get_query_output_port(), camera_sys->get_input_port()); } // Find the LCM bus. lcm = FindOrCreateLcmBus(lcm, lcm_buses, builder, "ApplyCameraConfig", config.lcm_bus); DRAKE_DEMAND(lcm != nullptr); if (lcm->get_lcm_url() == LcmBuses::kLcmUrlMemqNull) { // The user has opted-out of LCM. return; } // TODO(jwnimmer-tri) When the Simulator has concurrent update + publish // events, it effectively runs the publish event before the update event. // Therefore, we need to fudge the publish time here so that the published // image is correct. Once the framework allows us to schedule publish events // with the ordering we want, we should remove this 0.1% fudge factor. const double lcm_publisher_offset = config.capture_offset + (1.001 * config.output_delay); // Connect the sensor to the lcm system. AddSimRgbdSensorLcmPublisher( config.name, config.fps, lcm_publisher_offset, config.rgb ? &camera_sys->GetOutputPort("color_image") : nullptr, config.depth ? &camera_sys->GetOutputPort("depth_image_16u") : nullptr, config.label ? &camera_sys->GetOutputPort("label_image") : nullptr, config.do_compress, builder, lcm); } } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/sim_rgbd_sensor.h
#pragma once #include <string> #include <utility> #include "drake/geometry/scene_graph.h" #include "drake/lcm/drake_lcm_interface.h" #include "drake/math/rigid_transform.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/sensors/rgbd_sensor.h" namespace drake { namespace systems { namespace sensors { namespace internal { /* Specification of an RGB-D sensor: its sensor properties, how it connects into the plant, and publication configuration. */ class SimRgbdSensor { public: // TODO(sean-curtis): The name "serial" has some issues. // - "Serial" as a noun, doesn't mean serial number. Strictly speaking, its // actual meaning is inappropriate for this context. // - In practice, it's merely a suffix that gets applied to LCM channels // and system names. It need not be a "serial number". It could be any // value convenient to the author of the model. // - The main interface (CameraConfig) has the field `name` which gets // mapped to serial in its construction of SimRgbdSensor. So, we have // "name" vs "serial" consistency problems. // We should pick and document the name that we want with intention. /* RgbdSensor is a meta sensor that contains multiple cameras. Please refer to `drake/systems/sensors/rgbd_sensor.h` for more details. @param serial The identifier for the sensor - this is used in the name of the RgbdSensor as well as to provide names for the image LCM channels. @param frame_P The parent frame P in MultibodyPlant the sensor is affixed to. This frame gets aliased by `this`. @param rate_hz The publishing rate for the sensor. @param X_PB The pose of the sensor frame B expressed with respect to its parent frame P. @param color_properties The properties of the color camera. @param depth_properties The properties of the depth camera. @warning Note that frame P may not have a *direct* analog in a SceneGraph; instead, SceneGraph will have a frame for body A (the body that parent frame P is attached to). In this case, usages must account for X_AP when adding a camera. For example, see the implementation of `AddSimRgbdSensor`. */ SimRgbdSensor(const std::string& serial, const multibody::Frame<double>& frame_P, double rate_hz, const math::RigidTransformd& X_PB, const geometry::render::ColorRenderCamera& color_properties, const geometry::render::DepthRenderCamera& depth_properties) : serial_(serial), frame_(&frame_P), rate_hz_(rate_hz), X_PB_(X_PB), color_properties_(color_properties), depth_properties_(depth_properties) {} const std::string& serial() const { return serial_; } const multibody::Frame<double>& frame() const { return *frame_; } const math::RigidTransform<double>& X_PB() const { return X_PB_; } const geometry::render::ColorRenderCamera& color_properties() const { return color_properties_; } const geometry::render::DepthRenderCamera& depth_properties() const { return depth_properties_; } double rate_hz() const { return rate_hz_; } private: std::string serial_; const multibody::Frame<double>* frame_{}; double rate_hz_{}; math::RigidTransformd X_PB_; geometry::render::ColorRenderCamera color_properties_; geometry::render::DepthRenderCamera depth_properties_; }; // TODO(eric.cousineau): Ew... Is there a way to not need the plant? /* Adds an RGB-D camera, as described by `sim_camera`, to the diagram. @param scene_graph The SceneGraph that supplies the rendered image for the camera. @param plant The plant that owns the frame the sensor will be affixed to. @param sim_camera The description of the camera. @param[in,out] builder The new RgbdSensor will be added to this builder's diagram. @pre The description in `sim_camera` is compatible with the configuration in SceneGraph (e.g., camera properties refer to an existing RenderEngine). */ RgbdSensor* AddSimRgbdSensor(const geometry::SceneGraph<double>& scene_graph, const multibody::MultibodyPlant<double>& plant, const SimRgbdSensor& sim_camera, DiagramBuilder<double>* builder); /* Helper function that converts a plant frame with offset (per SimRgbdSensor) to a geometry frame with offset (per RgbdSensor). @param X_PB is relative to the plant_frame "P". */ std::pair<geometry::FrameId, math::RigidTransformd> GetGeometryFrame( const multibody::Frame<double>& plant_frame, const math::RigidTransformd& X_PB); /* Adds LCM publishers for images (RGB, depth, and/or label), at the camera's specified rate. @param serial The SimRgbdSensor.serial(). @param fps The SimRgbdSensor.rate_hz(). @param publish_offset Phase offset for publishing; see LcmPublisherSystem for a comprehensive description. @param rgb_port The (optional) port for color images. @param depth_16u_port The (optional) port for depth images. @param label_port The (optional) port for label images. @param do_compress If true, the published images will be compressed. @param[in,out] builder The publishing infrastructure will be added to this builder's diagram. @param[in,out] lcm The lcm interface to use. This interface object must remain alive at least as long as the systems added to `builder`. @pre lcm != nullptr. @pre builder != nullptr. @pre rgb_port is null or ImageRgba8U-valued. @pre depth_16u_port is null or ImageDepth16U-valued. @pre label_port is null or ImageLabel16I-valued. */ void AddSimRgbdSensorLcmPublisher(std::string_view serial, double fps, double publish_offset, const OutputPort<double>* rgb_port, const OutputPort<double>* depth_16u_port, const OutputPort<double>* label_port, bool do_compress, DiagramBuilder<double>* builder, drake::lcm::DrakeLcmInterface* lcm); // A backwards-compatibility overload to simplify unit testing. void AddSimRgbdSensorLcmPublisher(const SimRgbdSensor& sim_camera, const OutputPort<double>* rgb_port, const OutputPort<double>* depth_16u_port, const OutputPort<double>* label_port, bool do_compress, DiagramBuilder<double>* builder, drake::lcm::DrakeLcmInterface* lcm); } // namespace internal } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/rgbd_sensor_async.h
#pragma once #include <optional> #include "drake/common/drake_copyable.h" #include "drake/geometry/geometry_ids.h" #include "drake/geometry/query_object.h" #include "drake/geometry/render/render_camera.h" #include "drake/geometry/scene_graph.h" #include "drake/math/rigid_transform.h" #include "drake/systems/framework/leaf_system.h" #include "drake/systems/sensors/camera_info.h" #include "drake/systems/sensors/image.h" namespace drake { namespace systems { namespace sensors { /** A sensor similar to RgbdSensorDiscrete but the rendering occurs on a background thread to offer improved performance. @experimental @warning This system is intended for use only with the out-of-process glTF rendering engine (MakeRenderEngineGltfClient()). Other render engines (e.g., MakeRenderEngineVtk() or MakeRenderEngineGl()) are either not thread-safe or perform poorly when used here. We hope to add async support for those engines down the road (see #19437 for details). @system name: RgbdSensorAsync input_ports: - geometry_query output_ports: - color_image (optional) - depth_image_32f (optional) - depth_image_16u (optional) - label_image (optional) - body_pose_in_world - image_time @endsystem This sensor works by capturing the i'th state of the world at time `t_capture = capture_offset + i / fps` and outputting the corresponding rendered image at time `t_output = t_capture + output_delay`, i.e., `t_output = capture_offset + i / fps + output_delay`. For example, with the following constructor settings: - capture_offset = 0 ms - output_delay = 50 ms - fps = 5 Hz (i.e., 200 ms) We have the following timing schedule: | Time | Event | Current output images | | :----: | :-----: | :----------------------: | | 0 ms | capture | empty (i.e., zero-sized) | | 50 ms | output | the scene as of 0 ms | | 200 ms | capture | ^ | | 250 ms | output | the scene as of 200 ms | | 400 ms | capture | ^ | | ... | ... | ... | The `capture_offset` is typically zero, but can be useful to stagger multiple cameras in the same scene to trigger at different times if desired (e.g., to space out rendering events for better performance). The `output_delay` can be used to model delays of a physical camera (e.g., for firmware processing on the device or transmitting the image over a USB or network connection, etc.). The image rendering between the capture event and the output event happens on a background thread, allowing simulation time to continue to advance during the rendering's `output_delay`. This helps smooth over the runtime latency associated with rendering. See also RgbdSensorDiscrete for a simpler (unthreaded) discrete sensor model, or RgbdSensor for a continuous model. @warning As the moment, this implementation cannnot respond to changes to geometry shapes, textures, etc. after a simulation has started. The only thing it responds to are changes to geometry poses. If you change anything beyond poses, you must manually call Simulator::Initialize() to reset things before resuming the simulation, or else you'll get an exception. This holds true for changes to both SceneGraph's model geometry and the copy of the geometry in a scene graph Context. */ class RgbdSensorAsync final : public LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(RgbdSensorAsync); /** Constructs a sensor with the given parameters. Refer to the class overview documentation for additional exposition and examples of the parameters. @param scene_graph The SceneGraph to use for image rendering. This pointer is retained by the constructor so must remain valid for the lifetime of this object. After construction, this system's `geometry_query` input port must be connected to the relevant output port of the given `scene_graph`. @param parent_id The frame "P" to which the sensor body is affixed. See RgbdSensor for details. @param X_PB The transform relating parent and sensor body. See RgbdSensor for details. @param fps How often (frames per second) to sample the `geometry_query` input and render the associated images. Must be strictly positive and finite. @param capture_offset The time of the first sample of `geometry_query` input. Typically zero. Must be non-negative and finite. @param output_delay How long after the `geometry_query` input sample the output ports should change to reflect the new rendered image(s). Must be strictly positive and strictly less than 1/fps. @param color_camera The properties for the `color_image` output port. When nullopt, there will be no `color_image` output port. At least one of `color_camera` or `depth_camera` must be provided. @param depth_camera The properties for the `depth_image_32f` and `depth_image_16u` output ports. When nullopt, there will be no such output ports. At least one of `color_camera` or `depth_camera` must be provided. @param render_label_image Whether to provide the `label_image` output port. May be set to true only when a `color_camera` has also been provided. */ RgbdSensorAsync( const geometry::SceneGraph<double>* scene_graph, geometry::FrameId parent_id, const math::RigidTransformd& X_PB, double fps, double capture_offset, double output_delay, std::optional<geometry::render::ColorRenderCamera> color_camera, std::optional<geometry::render::DepthRenderCamera> depth_camera = {}, bool render_label_image = false); /** Returns the `parent_id` passed to the constructor. */ geometry::FrameId parent_id() const { return parent_id_; } /** Returns the `X_PB` passed to the constructor. */ const math::RigidTransformd& X_PB() const { return X_PB_; } /** Returns the `fps` passed to the constructor. */ double fps() const { return fps_; } /** Returns the `capture_offset` passed to the constructor. */ double capture_offset() const { return capture_offset_; } /** Returns the `output_delay` passed to the constructor. */ double output_delay() const { return output_delay_; } /** Returns the `color_camera` passed to the constructor. */ const std::optional<geometry::render::ColorRenderCamera>& color_camera() const { return color_camera_; } /** Returns the `depth_camera` passed to the constructor. */ const std::optional<geometry::render::DepthRenderCamera>& depth_camera() const { return depth_camera_; } // TODO(jwnimmer-tri) Add an output port for the timestamp associated with // the other output ports (images, etc.) to make it easier for the user to // know when any given image was captured. /** Returns the abstract-valued output port that contains an ImageRgba8U. @throws std::exception when color output is not enabled. */ const OutputPort<double>& color_image_output_port() const; /** Returns the abstract-valued output port that contains an ImageDepth32F. @throws std::exception when depth output is not enabled. */ const OutputPort<double>& depth_image_32F_output_port() const; /** Returns the abstract-valued output port that contains an ImageDepth16U. @throws std::exception when depth output is not enabled. */ const OutputPort<double>& depth_image_16U_output_port() const; /** Returns the abstract-valued output port that contains an ImageLabel16I. @throws std::exception when label output is not enabled. */ const OutputPort<double>& label_image_output_port() const; /** Returns the abstract-valued output port (containing a RigidTransform) which reports the pose of the body in the world frame (X_WB). */ const OutputPort<double>& body_pose_in_world_output_port() const; /** Returns the vector-valued output port (with size == 1) which reports the simulation time when the image outputs were captured, in seconds. When there are no images available on the output ports (e.g., at the beginning of a simulation), the value will be NaN. */ const OutputPort<double>& image_time_output_port() const; private: struct TickTockState; const TickTockState& get_state(const Context<double>&) const; TickTockState& get_mutable_state(State<double>*) const; EventStatus Initialize(const Context<double>&, State<double>*) const; void CalcTick(const Context<double>&, State<double>*) const; void CalcTock(const Context<double>&, State<double>*) const; void CalcColor(const Context<double>&, ImageRgba8U*) const; void CalcLabel(const Context<double>&, ImageLabel16I*) const; void CalcDepth32F(const Context<double>&, ImageDepth32F*) const; void CalcDepth16U(const Context<double>&, ImageDepth16U*) const; void CalcX_WB(const Context<double>&, math::RigidTransformd*) const; void CalcImageTime(const Context<double>&, BasicVector<double>*) const; const geometry::SceneGraph<double>* const scene_graph_; const geometry::FrameId parent_id_; const math::RigidTransformd X_PB_; const double fps_; const double capture_offset_; const double output_delay_; const std::optional<geometry::render::ColorRenderCamera> color_camera_; const std::optional<geometry::render::DepthRenderCamera> depth_camera_; const bool render_label_image_; }; } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/gyroscope.h
#pragma once #include <memory> #include <vector> #include "drake/common/drake_copyable.h" #include "drake/math/rotation_matrix.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/multibody/tree/multibody_tree_indexes.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/framework/leaf_system.h" namespace drake { namespace systems { namespace sensors { /// Sensor to represent an ideal gyroscopic sensor. Currently does not /// represent noise or bias, but this could and should be added at a later /// date. This sensor measures the angular velocity of a given body B relative /// to the world frame. The sensor frame S is rigidly affixed to the given /// body B. The measurement, written w_WS_S, is expressed in the coordinates /// of frame S. Note that, since S is fixed to B, the angular velocity of the /// two frames is identical, w_WS_S = w_WB_S. /// /// There are two inputs to this sensor (nominally from a MultibodyPlant): /// 1. A vector of body poses (e.g. plant.get_body_poses_output_port()), /// 2. A vector of spatial velocities, /// (e.g. plant.get_body_spatial_velocities_output_port()). /// /// This class is therefore defined by: /// 1. The Body to which this sensor is rigidly affixed, /// 2. The pose of the sensor frame in the body frame. /// Note that the translational component of the transformation is not strictly /// needed by a gyroscope, as the position of the sensor does not affect the /// measurement. However, as a sensor does have a physical location, it is /// included here for completeness and in case it might be useful for display or /// other purposes. /// /// @system /// name: Gyroscope /// input_ports: /// - body_poses /// - body_spatial_velocities /// output_ports: /// - measurement /// @endsystem /// /// @ingroup sensor_systems template <typename T> class Gyroscope final : public LeafSystem<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Gyroscope) /// Constructor for %Gyroscope using full transform. /// @param body the body B to which the sensor is affixed /// @param X_BS the pose of sensor frame S in body B Gyroscope(const multibody::RigidBody<T>& body, const math::RigidTransform<double>& X_BS); /// Scalar-converting copy constructor. See @ref system_scalar_conversion. template <typename U> explicit Gyroscope(const Gyroscope<U>&); const InputPort<T>& get_body_poses_input_port() const { return *body_poses_input_port_; } const InputPort<T>& get_body_velocities_input_port() const { return *body_velocities_input_port_; } const OutputPort<T>& get_measurement_output_port() const { return *measurement_output_port_; } /// Returns the index of the RigidBody that was supplied in the constructor. const multibody::BodyIndex& body_index() const { return body_index_; } /// Gets X_BS, the pose of sensor frame S in body B. const math::RigidTransform<double>& pose() const { return X_BS_; } /// Static factory method that creates a %Gyroscope object and connects /// it to the given plant. Modifies a Diagram by connecting the input ports /// of the new %Gyroscope to the appropriate output ports of a /// MultibodyPlant. Must be called during Diagram building and given the /// appropriate builder. This is a convenience method to simplify some common /// boilerplate of Diagram wiring. Specifically, this makes three connections: /// /// 1. plant.get_body_poses_output_port() to this.get_body_poses_input_port() /// 2. plant.get_body_spatial_velocities_output_port() to /// this.get_body_velocities_input_port() /// @param body the body B to which the sensor is affixed /// @param X_BS X_BS the pose of sensor frame S in body B /// @param plant the plant to which the sensor will be connected /// @param builder a pointer to the DiagramBuilder static const Gyroscope& AddToDiagram( const multibody::RigidBody<T>& body, const math::RigidTransform<double>& X_BS, const multibody::MultibodyPlant<T>& plant, DiagramBuilder<T>* builder); private: Gyroscope(const multibody::BodyIndex& body_index, const math::RigidTransform<double>& X_BS); // Computes the transformed signal. void CalcOutput(const Context<T>& context, BasicVector<T>* output) const; const multibody::BodyIndex body_index_; const math::RigidTransform<double> X_BS_; const InputPort<T>* body_poses_input_port_{nullptr}; const InputPort<T>* body_velocities_input_port_{nullptr}; const OutputPort<T>* measurement_output_port_{nullptr}; }; } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/vtk_image_reader_writer.h
#pragma once #include <cstdint> #include <filesystem> #include <vector> // To ease build system upkeep, we annotate VTK includes with their deps. #include <vtkImageReader2.h> // vtkIOImage #include <vtkImageWriter.h> // vtkIOImage #include <vtkSmartPointer.h> // vtkCommonCore #include "drake/systems/sensors/image_file_format.h" namespace drake { namespace systems { namespace sensors { namespace internal { // This file provides internal helper functions that encapsulate VTK's reader // and writer classes for the file formats Drake cares about. /* Constructs a VTK image reader for a specific file format, already connected to read the data from the given filename. */ vtkSmartPointer<vtkImageReader2> MakeReader( ImageFileFormat format, const std::filesystem::path& filename); /* Constructs a VTK image reader for a specific file format, already connected to read the data from the given memory buffer of `size` bytes. @warning The reader retains a pointer to the `input`, so it can read from it when requested to. The `input` buffer must outlive the returned reader. */ vtkSmartPointer<vtkImageReader2> MakeReader(ImageFileFormat format, const void* input, size_t size); /* Constructs a VTK image writer for a specific file format, already connected to write the data to the given destination filename. */ vtkSmartPointer<vtkImageWriter> MakeWriter( ImageFileFormat format, const std::filesystem::path& filename); /* Constructs a VTK image writer for a specific file format, already connected to write the data to the given memory @warning The TIFF file format cannot currently be written to a memory buffer, rather only to a file. Passing `format == kTiff` will throw an exception. @warning The writer retains a pointer to the `output`, so it can set it during the Write() operation. The `output` buffer must outlive the returned writer. */ vtkSmartPointer<vtkImageWriter> MakeWriter(ImageFileFormat format, std::vector<uint8_t>* output); } // namespace internal } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/camera_config.cc
#include "drake/systems/sensors/camera_config.h" #include <cmath> #include "drake/systems/sensors/camera_info.h" namespace drake { namespace systems { namespace sensors { using geometry::render::ClippingRange; using geometry::render::ColorRenderCamera; using geometry::render::DepthRange; using geometry::render::DepthRenderCamera; using geometry::render::RenderCameraCore; using math::RigidTransform; void CameraConfig::FocalLength::ValidateOrThrow() const { // N.B. The positive, finiteness of the values is tested when we validate // CameraConfig by construction render cameras. if (!x.has_value() && !y.has_value()) { throw std::logic_error( "Invalid camera configuration; you must define at least x or y " "for FocalLength."); } } double CameraConfig::FocalLength::focal_x() const { ValidateOrThrow(); if (x.has_value()) { return *x; } else { return *y; } } double CameraConfig::FocalLength::focal_y() const { ValidateOrThrow(); if (y.has_value()) { return *y; } else { return *x; } } void CameraConfig::FovDegrees::ValidateOrThrow() const { // N.B. The positive, finiteness of the values is tested when we validate // CameraConfig by construction render cameras. if (!x.has_value() && !y.has_value()) { throw std::logic_error( "Invalid camera configuration; you must define at least x or y " "for FovDegrees."); } } namespace { // Computes the focal length along a single axis based on the image // dimension and field of view (in a degrees) in that direction. // This computation must be kept in agreement with that in CameraInfo. double CalcFocalLength(int image_dimension, double fov_degrees) { const double fov_rad = M_PI * fov_degrees / 180.0; return image_dimension * 0.5 / std::tan(0.5 * fov_rad); } } // namespace double CameraConfig::FovDegrees::focal_x(int width_in, int height_in) const { ValidateOrThrow(); if (x.has_value()) { return CalcFocalLength(width_in, *x); } else { return focal_y(width_in, height_in); } } double CameraConfig::FovDegrees::focal_y(int width_in, int height_in) const { ValidateOrThrow(); if (y.has_value()) { return CalcFocalLength(height_in, *y); } else { return focal_x(width_in, height_in); } } double CameraConfig::focal_x() const { if (std::holds_alternative<FocalLength>(focal)) { return std::get<FocalLength>(focal).focal_x(); } else { return std::get<FovDegrees>(focal).focal_x(width, height); } } double CameraConfig::focal_y() const { if (std::holds_alternative<FocalLength>(focal)) { return std::get<FocalLength>(focal).focal_y(); } else { return std::get<FovDegrees>(focal).focal_y(width, height); } } std::pair<ColorRenderCamera, DepthRenderCamera> CameraConfig::MakeCameras() const { const Vector2<double> center = principal_point(); CameraInfo intrinsics(width, height, focal_x(), focal_y(), center.x(), center.y()); ClippingRange clipping_range(clipping_near, clipping_far); RenderCameraCore color_core(renderer_name, intrinsics, clipping_range, X_BC.GetDeterministicValue()); RenderCameraCore depth_core(renderer_name, intrinsics, clipping_range, X_BD.GetDeterministicValue()); DepthRange depth_range(z_near, z_far); return {ColorRenderCamera(color_core, show_rgb), DepthRenderCamera(depth_core, depth_range)}; } void CameraConfig::ValidateOrThrow() const { // If we haven't specified any image types, it is trivially valid. if (!(rgb || depth || label)) { return; } // We validate the focal length substruct here, instead of during its local // Serialize. We don't want to validate anything if the cameras are disabled, // and because the default focal length is a property of the CameraConfig // instead of the child struct, we must not validate the child in isolation. std::visit( [](auto&& child) -> void { child.ValidateOrThrow(); }, focal); // We don't worry about the other variant alternatives; if we're here, we've // constructed a set of parameters, and we'll defer to the RenderEngine to // determine if the values are valid. if (std::holds_alternative<std::string>(renderer_class)) { const auto& class_name = std::get<std::string>(renderer_class); if (!class_name.empty() && !(class_name == "RenderEngineVtk" || class_name == "RenderEngineGl" || class_name == "RenderEngineGltfClient")) { throw std::logic_error(fmt::format( "Invalid camera configuration; the given renderer_class value '{}' " "must be empty (to use the default) or be one of 'RenderEngineVtk', " "'RenderEngineGl', or 'RenderEngineGltfClient'.", class_name)); } } // This throws for us if we have bad bad numerical camera values (or an empty // renderer_name). MakeCameras(); if (name.empty()) { throw std::logic_error( "Invalid camera configuration; name cannot be empty."); } if (renderer_name.empty()) { throw std::logic_error( "Invalid camera configuration; renderer_name cannot be empty."); } // We need to check the quantities unique to CameraConfig. if (fps <= 0 || !std::isfinite(fps)) { throw std::logic_error( fmt::format("Invalid camera configuration; FPS ({}) must be a finite, " "positive value.", fps)); } if (capture_offset < 0 || !std::isfinite(capture_offset)) { throw std::logic_error(fmt::format( "Invalid camera configuration; capture_offset ({}) must be a finite, " "non-negative value.", capture_offset)); } if (X_BC.base_frame.has_value() && !X_BC.base_frame->empty()) { throw std::logic_error( fmt::format("Invalid camera configuration; X_BC must not specify a " "base frame. '{}' found.", *X_BC.base_frame)); } if (X_BD.base_frame.has_value() && !X_BD.base_frame->empty()) { throw std::logic_error( fmt::format("Invalid camera configuration; X_BD must not specify a " "base frame. '{}' found.", *X_BD.base_frame)); } } } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/image_io_save.cc
/* clang-format off to disable clang-format-includes */ #include "drake/systems/sensors/image_io.h" /* clang-format on */ #include <stdexcept> // To ease build system upkeep, we annotate VTK includes with their deps. #include <vtkImageData.h> // vtkCommonDataModel #include <vtkImageWriter.h> // vtkIOImage #include <vtkNew.h> // vtkCommonCore #include <vtkSmartPointer.h> // vtkCommonCore #include "drake/systems/sensors/image_io_internal.h" #include "drake/systems/sensors/vtk_image_reader_writer.h" // This file implements half of the class ImageIo (the Save functions). namespace drake { namespace systems { namespace sensors { namespace { template <PixelType kPixelType> void CopyImage(const Image<kPixelType>& source_image, vtkImageData* dest_image) { // Allocate the VTK storage. const int width = source_image.width(); const int height = source_image.height(); constexpr int depth = 1; constexpr int num_channels = Image<kPixelType>::kNumChannels; dest_image->SetDimensions(width, height, depth); dest_image->AllocateScalars(internal::GetVtkScalarType<kPixelType>(), num_channels); // Copy the bytes. using T = typename ImageTraits<kPixelType>::ChannelType; const T* const source = source_image.at(0, 0); T* dest = reinterpret_cast<T*>(dest_image->GetScalarPointer()); constexpr bool swizzle = internal::NeedsBgrSwizzle<kPixelType>(); internal::CopyAndFlipRaw<T, num_channels, swizzle>(source, dest, width, height); } } // namespace void ImageIo::SaveImpl(ImageAnyConstPtr image_any, std::optional<ImageFileFormat> format, OutputAny output_any) const { // Choose which file format to use. const ImageFileFormat chosen_format = [format, output_any]() { if (format.has_value()) { return *format; } else { DRAKE_DEMAND(output_any.index() == 0); const std::filesystem::path& path = *std::get<0>(output_any); if (std::optional<ImageFileFormat> from_ext = internal::FileFormatFromExtension(path)) { return *from_ext; } else { throw std::logic_error(fmt::format( "ImageIo::Save(path='{}') requires SetFileFormat() to be called " "first because the path does not imply any supported format.", path.string())); } } }(); // Make the VTK writer. vtkSmartPointer<vtkImageWriter> writer; if (output_any.index() == 0) { writer = internal::MakeWriter(chosen_format, *std::get<0>(output_any)); } else { writer = internal::MakeWriter(chosen_format, std::get<1>(output_any)); } // Copy the Drake image buffer to a VTK image buffer. Drake uses (x=0, y=0) // as the top left corner, but VTK uses it as the bottom left corner, and // neither has an option to switch the representation. Therefore, we always // need to eat an extra copy here. vtkNew<vtkImageData> vtk_image; visit( [&vtk_image](const auto* drake_image) { CopyImage(*drake_image, vtk_image.Get()); }, image_any); // Use the writer to encode/compress the image per the file format. writer->SetInputData(vtk_image.GetPointer()); writer->Write(); // TODO(jwnimmer-tri) We should more carefully check the VTK objects for // errors (or warnings), and propagate those up through our diagnostic policy. } } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/vtk_image_reader_writer.cc
#include "drake/systems/sensors/vtk_image_reader_writer.h" #include <functional> #include <utility> #include <variant> // To ease build system upkeep, we annotate VTK includes with their deps. #include <vtkCommand.h> // vtkCommonCore #include <vtkJPEGReader.h> // vtkIOImage #include <vtkJPEGWriter.h> // vtkIOImage #include <vtkPNGReader.h> // vtkIOImage #include <vtkPNGWriter.h> // vtkIOImage #include <vtkTIFFReader.h> // vtkIOImage #include <vtkTIFFWriter.h> // vtkIOImage #include <vtkUnsignedCharArray.h> // vtkCommonCore #include "drake/common/drake_assert.h" #include "drake/common/unused.h" namespace drake { namespace systems { namespace sensors { namespace internal { namespace { namespace fs = std::filesystem; vtkSmartPointer<vtkImageReader2> MakeReaderObject(ImageFileFormat format) { switch (format) { case ImageFileFormat::kJpeg: return vtkSmartPointer<vtkJPEGReader>::New(); case ImageFileFormat::kPng: return vtkSmartPointer<vtkPNGReader>::New(); case ImageFileFormat::kTiff: { auto result = vtkSmartPointer<vtkTIFFReader>::New(); // VTK's TIFF reader doesn't use VTK's default coordinate conventions // unless we specifically tell it to. result->SetOrientationType(4 /* ORIENTATION_BOTLEFT */); return result; } } DRAKE_UNREACHABLE(); } } // namespace vtkSmartPointer<vtkImageReader2> MakeReader(ImageFileFormat format, const fs::path& filename) { vtkSmartPointer<vtkImageReader2> reader = MakeReaderObject(format); reader->SetFileName(filename.c_str()); return reader; } vtkSmartPointer<vtkImageReader2> MakeReader(ImageFileFormat format, const void* input, size_t size) { vtkSmartPointer<vtkImageReader2> reader = MakeReaderObject(format); reader->SetMemoryBuffer(input); reader->SetMemoryBufferLength(size); return reader; } namespace { vtkSmartPointer<vtkImageWriter> MakeWriterObject(ImageFileFormat format) { switch (format) { case ImageFileFormat::kJpeg: return vtkSmartPointer<vtkJPEGWriter>::New(); case ImageFileFormat::kPng: return vtkSmartPointer<vtkPNGWriter>::New(); case ImageFileFormat::kTiff: return vtkSmartPointer<vtkTIFFWriter>::New(); } DRAKE_UNREACHABLE(); } /* Trampolines VTK progress events into a Drake-specific callback. */ class VtkProgressObserver final : public vtkCommand { public: VtkProgressObserver() = default; void set_progress_callback(std::function<void(double)> callback) { callback_ = std::move(callback); } // Boilerplate for VTK smart pointers. static VtkProgressObserver* New() { return new VtkProgressObserver; } private: // NOLINTNEXTLINE(runtime/int) To match the VTK signature. void Execute(vtkObject*, unsigned long event, void* calldata) final { if (event == vtkCommand::ProgressEvent) { const double amount = *static_cast<const double*>(calldata); if (callback_ != nullptr) { callback_(amount); } } } std::function<void(double)> callback_; }; } // namespace vtkSmartPointer<vtkImageWriter> MakeWriter(ImageFileFormat format, const fs::path& filename) { vtkSmartPointer<vtkImageWriter> writer = MakeWriterObject(format); writer->SetFileName(filename.c_str()); return writer; } vtkSmartPointer<vtkImageWriter> MakeWriter(ImageFileFormat format, std::vector<uint8_t>* output) { DRAKE_DEMAND(output != nullptr); if (format == ImageFileFormat::kTiff) { throw std::logic_error("Cannot save TIFF images to a memory buffer"); } vtkSmartPointer<vtkImageWriter> writer = MakeWriterObject(format); // The "write to memory" API is only available on the concrete subclasses, // so we'll always need to call it with a visitor, instead of virtually. std::variant<vtkJPEGWriter*, vtkPNGWriter*> writer_variant; switch (format) { case ImageFileFormat::kJpeg: writer_variant = static_cast<vtkJPEGWriter*>(writer.Get()); break; case ImageFileFormat::kPng: writer_variant = static_cast<vtkPNGWriter*>(writer.Get()); break; case ImageFileFormat::kTiff: DRAKE_UNREACHABLE(); } std::visit( [](auto* typed_writer) { typed_writer->WriteToMemoryOn(); }, writer_variant); // Either a FileName or FilePrefix is mandatory. writer->SetFilePrefix("drake"); // Add an observer to the writer that copies the encoded image into the // `output` buffer. vtkNew<VtkProgressObserver> observer; observer->set_progress_callback([output, writer_variant](double amount) { // TODO(jwnimmer) Use the `amount` to decide when the writing is finished. // At the moment, VTK mistakenly posts 0% progress both when it starts and // when it finishes, so we can't use 100% to know when its time to copy. unused(amount); std::visit( [output](auto* typed_writer) { vtkUnsignedCharArray* range = typed_writer->GetResult(); // The result pointer `range` only exists after writing is complete. // Use that to know when we're actually done. if (range != nullptr) { output->clear(); const size_t size = range->GetNumberOfTuples(); const uint8_t* const data = range->GetPointer(0); output->insert(output->begin(), data, data + size); } }, writer_variant); }); writer->AddObserver(vtkCommand::ProgressEvent, observer); return writer; } } // namespace internal } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/beam_model_params.h
#pragma once // This file was previously auto-generated, but now is just a normal source // file in git. However, it still retains some historical oddities from its // heritage. In general, we do recommend against subclassing BasicVector in // new code. #include <cmath> #include <limits> #include <stdexcept> #include <string> #include <utility> #include <vector> #include <Eigen/Core> #include "drake/common/drake_bool.h" #include "drake/common/dummy_value.h" #include "drake/common/name_value.h" #include "drake/common/never_destroyed.h" #include "drake/common/symbolic/expression.h" #include "drake/systems/framework/basic_vector.h" namespace drake { namespace systems { namespace sensors { /// Describes the row indices of a BeamModelParams. struct BeamModelParamsIndices { /// The total number of rows (coordinates). static const int kNumCoordinates = 5; // The index of each individual coordinate. static const int kLambdaShort = 0; static const int kSigmaHit = 1; static const int kProbabilityShort = 2; static const int kProbabilityMiss = 3; static const int kProbabilityUniform = 4; /// Returns a vector containing the names of each coordinate within this /// class. The indices within the returned vector matches that of this class. /// In other words, `BeamModelParamsIndices::GetCoordinateNames()[i]` /// is the name for `BasicVector::GetAtIndex(i)`. static const std::vector<std::string>& GetCoordinateNames(); }; /// Specializes BasicVector with specific getters and setters. template <typename T> class BeamModelParams final : public drake::systems::BasicVector<T> { public: /// An abbreviation for our row index constants. typedef BeamModelParamsIndices K; /// Default constructor. Sets all rows to their default value: /// @arg @c lambda_short defaults to 1.0 dimensionless. /// @arg @c sigma_hit defaults to 0.0 m. /// @arg @c probability_short defaults to 0.0 dimensionless. /// @arg @c probability_miss defaults to 0.0 dimensionless. /// @arg @c probability_uniform defaults to 0.0 dimensionless. BeamModelParams() : drake::systems::BasicVector<T>(K::kNumCoordinates) { this->set_lambda_short(1.0); this->set_sigma_hit(0.0); this->set_probability_short(0.0); this->set_probability_miss(0.0); this->set_probability_uniform(0.0); } // Note: It's safe to implement copy and move because this class is final. /// @name Implements CopyConstructible, CopyAssignable, MoveConstructible, /// MoveAssignable //@{ BeamModelParams(const BeamModelParams& other) : drake::systems::BasicVector<T>(other.values()) {} BeamModelParams(BeamModelParams&& other) noexcept : drake::systems::BasicVector<T>(std::move(other.values())) {} BeamModelParams& operator=(const BeamModelParams& other) { this->values() = other.values(); return *this; } BeamModelParams& operator=(BeamModelParams&& other) noexcept { this->values() = std::move(other.values()); other.values().resize(0); return *this; } //@} /// Create a symbolic::Variable for each element with the known variable /// name. This is only available for T == symbolic::Expression. template <typename U = T> typename std::enable_if_t<std::is_same_v<U, symbolic::Expression>> SetToNamedVariables() { this->set_lambda_short(symbolic::Variable("lambda_short")); this->set_sigma_hit(symbolic::Variable("sigma_hit")); this->set_probability_short(symbolic::Variable("probability_short")); this->set_probability_miss(symbolic::Variable("probability_miss")); this->set_probability_uniform(symbolic::Variable("probability_uniform")); } [[nodiscard]] BeamModelParams<T>* DoClone() const final { return new BeamModelParams; } /// @name Getters and Setters //@{ /// The rate parameter of the (truncated) exponential distribution governing /// short returns /// @note @c lambda_short is expressed in units of dimensionless. /// @note @c lambda_short has a limited domain of [0.0, +Inf]. const T& lambda_short() const { ThrowIfEmpty(); return this->GetAtIndex(K::kLambdaShort); } /// Setter that matches lambda_short(). void set_lambda_short(const T& lambda_short) { ThrowIfEmpty(); this->SetAtIndex(K::kLambdaShort, lambda_short); } /// Fluent setter that matches lambda_short(). /// Returns a copy of `this` with lambda_short set to a new value. [[nodiscard]] BeamModelParams<T> with_lambda_short( const T& lambda_short) const { BeamModelParams<T> result(*this); result.set_lambda_short(lambda_short); return result; } /// The standard deviation of the (truncated) Gaussian distribution governing /// the noisy returns of the true depth (aka hit) /// @note @c sigma_hit is expressed in units of m. /// @note @c sigma_hit has a limited domain of [0.0, +Inf]. const T& sigma_hit() const { ThrowIfEmpty(); return this->GetAtIndex(K::kSigmaHit); } /// Setter that matches sigma_hit(). void set_sigma_hit(const T& sigma_hit) { ThrowIfEmpty(); this->SetAtIndex(K::kSigmaHit, sigma_hit); } /// Fluent setter that matches sigma_hit(). /// Returns a copy of `this` with sigma_hit set to a new value. [[nodiscard]] BeamModelParams<T> with_sigma_hit(const T& sigma_hit) const { BeamModelParams<T> result(*this); result.set_sigma_hit(sigma_hit); return result; } /// The total probability of getting a short return is /// probability_short * p(lambda_short*w_short <= input_depth) /// @note @c probability_short is expressed in units of dimensionless. /// @note @c probability_short has a limited domain of [0.0, 1.0]. const T& probability_short() const { ThrowIfEmpty(); return this->GetAtIndex(K::kProbabilityShort); } /// Setter that matches probability_short(). void set_probability_short(const T& probability_short) { ThrowIfEmpty(); this->SetAtIndex(K::kProbabilityShort, probability_short); } /// Fluent setter that matches probability_short(). /// Returns a copy of `this` with probability_short set to a new value. [[nodiscard]] BeamModelParams<T> with_probability_short( const T& probability_short) const { BeamModelParams<T> result(*this); result.set_probability_short(probability_short); return result; } /// The probability of ignoring the input depth and simply returning the max /// range of the sensor /// @note @c probability_miss is expressed in units of dimensionless. /// @note @c probability_miss has a limited domain of [0.0, 1.0]. const T& probability_miss() const { ThrowIfEmpty(); return this->GetAtIndex(K::kProbabilityMiss); } /// Setter that matches probability_miss(). void set_probability_miss(const T& probability_miss) { ThrowIfEmpty(); this->SetAtIndex(K::kProbabilityMiss, probability_miss); } /// Fluent setter that matches probability_miss(). /// Returns a copy of `this` with probability_miss set to a new value. [[nodiscard]] BeamModelParams<T> with_probability_miss( const T& probability_miss) const { BeamModelParams<T> result(*this); result.set_probability_miss(probability_miss); return result; } /// The probability of ignoring the input depth and simple returning a uniform /// random value between 0 and the max range of the sensor /// @note @c probability_uniform is expressed in units of dimensionless. /// @note @c probability_uniform has a limited domain of [0.0, 1.0]. const T& probability_uniform() const { ThrowIfEmpty(); return this->GetAtIndex(K::kProbabilityUniform); } /// Setter that matches probability_uniform(). void set_probability_uniform(const T& probability_uniform) { ThrowIfEmpty(); this->SetAtIndex(K::kProbabilityUniform, probability_uniform); } /// Fluent setter that matches probability_uniform(). /// Returns a copy of `this` with probability_uniform set to a new value. [[nodiscard]] BeamModelParams<T> with_probability_uniform( const T& probability_uniform) const { BeamModelParams<T> result(*this); result.set_probability_uniform(probability_uniform); return result; } //@} /// Visit each field of this named vector, passing them (in order) to the /// given Archive. The archive can read and/or write to the vector values. /// One common use of Serialize is the //common/yaml tools. template <typename Archive> void Serialize(Archive* a) { T& lambda_short_ref = this->GetAtIndex(K::kLambdaShort); a->Visit(drake::MakeNameValue("lambda_short", &lambda_short_ref)); T& sigma_hit_ref = this->GetAtIndex(K::kSigmaHit); a->Visit(drake::MakeNameValue("sigma_hit", &sigma_hit_ref)); T& probability_short_ref = this->GetAtIndex(K::kProbabilityShort); a->Visit(drake::MakeNameValue("probability_short", &probability_short_ref)); T& probability_miss_ref = this->GetAtIndex(K::kProbabilityMiss); a->Visit(drake::MakeNameValue("probability_miss", &probability_miss_ref)); T& probability_uniform_ref = this->GetAtIndex(K::kProbabilityUniform); a->Visit( drake::MakeNameValue("probability_uniform", &probability_uniform_ref)); } /// See BeamModelParamsIndices::GetCoordinateNames(). static const std::vector<std::string>& GetCoordinateNames() { return BeamModelParamsIndices::GetCoordinateNames(); } /// Returns whether the current values of this vector are well-formed. drake::boolean<T> IsValid() const { using std::isnan; drake::boolean<T> result{true}; result = result && !isnan(lambda_short()); result = result && (lambda_short() >= T(0.0)); result = result && !isnan(sigma_hit()); result = result && (sigma_hit() >= T(0.0)); result = result && !isnan(probability_short()); result = result && (probability_short() >= T(0.0)); result = result && (probability_short() <= T(1.0)); result = result && !isnan(probability_miss()); result = result && (probability_miss() >= T(0.0)); result = result && (probability_miss() <= T(1.0)); result = result && !isnan(probability_uniform()); result = result && (probability_uniform() >= T(0.0)); result = result && (probability_uniform() <= T(1.0)); return result; } void GetElementBounds(Eigen::VectorXd* lower, Eigen::VectorXd* upper) const final { const double kInf = std::numeric_limits<double>::infinity(); *lower = Eigen::Matrix<double, 5, 1>::Constant(-kInf); *upper = Eigen::Matrix<double, 5, 1>::Constant(kInf); (*lower)(K::kLambdaShort) = 0.0; (*lower)(K::kSigmaHit) = 0.0; (*lower)(K::kProbabilityShort) = 0.0; (*upper)(K::kProbabilityShort) = 1.0; (*lower)(K::kProbabilityMiss) = 0.0; (*upper)(K::kProbabilityMiss) = 1.0; (*lower)(K::kProbabilityUniform) = 0.0; (*upper)(K::kProbabilityUniform) = 1.0; } private: void ThrowIfEmpty() const { if (this->values().size() == 0) { throw std::out_of_range( "The BeamModelParams vector has been moved-from; " "accessor methods may no longer be used"); } } }; } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/image_file_format.cc
#include "drake/systems/sensors/image_file_format.h" #include "drake/common/drake_assert.h" namespace drake { namespace systems { namespace sensors { std::string to_string(ImageFileFormat format) { switch (format) { case ImageFileFormat::kJpeg: return "jpeg"; case ImageFileFormat::kPng: return "png"; case ImageFileFormat::kTiff: return "tiff"; } DRAKE_UNREACHABLE(); } } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/image_io_load.cc
/* clang-format off to disable clang-format-includes */ #include "drake/systems/sensors/image_io.h" /* clang-format on */ #include <memory> #include <string> #include <vector> // To ease build system upkeep, we annotate VTK includes with their deps. #include <vtkCommand.h> // vtkCommonCore #include <vtkImageExport.h> // vtkIOImage #include <vtkNew.h> // vtkCommonCore #include <vtkSmartPointer.h> // vtkCommonCore #include "drake/common/drake_assert.h" #include "drake/common/drake_export.h" #include "drake/systems/sensors/image_io_internal.h" #include "drake/systems/sensors/vtk_diagnostic_event_observer.h" #include "drake/systems/sensors/vtk_image_reader_writer.h" // This file implements half of the class ImageIo (the Load functions). namespace drake { namespace systems { namespace sensors { using drake::internal::DiagnosticDetail; using drake::internal::DiagnosticPolicy; using internal::VtkDiagnosticEventObserver; // These are nested classes within ImageIo. It's convenient to lift them up into // our namespace for brevity. using InputAny = std::variant<const std::filesystem::path*, ImageIo::ByteSpan>; using Metadata = ImageIo::Metadata; /* When we ask VTK to read an image file, this is what we get back. */ struct DRAKE_NO_EXPORT ImageIo::LoaderTools { /* This contains borrowed pointers to memory owned elsewhere. */ InputAny input_any; /* The `errors` vector collects errors during loading. The error handling strategy is somewhat complicated: because VTK is not exception-safe, we must not throw errors as exceptions; instead, we must stash them here and later call `FlushDiagnostics()` to propagate them. The flow is like this: • Some vtkObject like vtkPNGReader detects a problem with the file it's loading, so it calls vtkErrorWithObjectMacro to post the error. • By default the posted error would have been printed to stderr and then ignored, but we've subscribed to error messages using a Drake-specific VtkDiagnosticEventObserver object, so our reader_observer.Execute() function ends up being called instead. • The Execute() function forwards the error to a DiagnosticPolicy, specifically our LoaderTools::diagnostic member. (Note in particular that LoaderTools::diagnostic and ImageIo::diagnostic_ are two different objects and policies; don't conflate the two.) • Our LoaderTools::diagnostic policy has been configured to do two things: - Tack on the image filename, for context. (Relatively few of the VTK error messages already mention the filename.) - Append the error to the `errors` collection. Then, once the VTK code is no longer on the call stack, the ImageIo function that is using the LoaderTools must call ImageIo::FlushDiagnostics() to copy the errors from LoaderTools::diagnostic into ImageIo::diagnostic_. Because those mechanisms require passing around raw pointers, we must store the error details on the heap, not in temporaries. */ std::unique_ptr<std::vector<DiagnosticDetail>> errors = std::make_unique<std::vector<DiagnosticDetail>>(); std::unique_ptr<DiagnosticPolicy> diagnostic = std::make_unique<DiagnosticPolicy>(); /* The metadata. Note that `metadata.format` will match `format` when the image has been loaded successfully, but otherwise might be stale. */ ImageFileFormat format{ImageFileFormat::kPng}; Metadata metadata; /* The VTK guts. */ vtkNew<VtkDiagnosticEventObserver> reader_observer; vtkSmartPointer<vtkImageReader2> reader; vtkNew<vtkImageExport> loader; }; /* Creates the loader infrastructure for the given input. Always returns something, even if the file is missing or can't be parsed or etc. When a required `format` is set, only that image format will be permitted. The pointer contained in `input_any` is aliased so must outlive the return value. */ ImageIo::LoaderTools ImageIo::MakeLoaderTools( InputAny input_any, std::optional<ImageFileFormat> format) const { // The return value aliases the `input_any` borrowed pointer. LoaderTools tools{.input_any = input_any}; // Wire up the diagnostic policy to incorporate the filename. We only wire up // errors because VTK doesn't use warnings while loading. const std::string diagnostic_filename = (input_any.index() == 0) ? std::get<0>(input_any)->string() : "ImageIo"; tools.diagnostic->SetActionForErrors( [diagnostic_filename, errors = tools.errors.get()](const DiagnosticDetail& detail) { DiagnosticDetail updated = detail; updated.filename = diagnostic_filename; errors->push_back(std::move(updated)); }); tools.reader_observer->set_diagnostic(tools.diagnostic.get()); // Decide which file format to use (with PNG as a last resort). if (format.has_value()) { tools.format = *format; } else if (std::optional<ImageFileFormat> guess = internal::GuessFileFormat(input_any)) { tools.format = *guess; } else { tools.format = ImageFileFormat::kPng; } // Wire up the VTK guts and load the file. if (input_any.index() == 0) { tools.reader = internal::MakeReader(tools.format, *std::get<0>(input_any)); } else { tools.reader = internal::MakeReader( tools.format, std::get<1>(input_any).data, std::get<1>(input_any).size); } tools.reader->AddObserver(vtkCommand::ErrorEvent, tools.reader_observer); tools.reader->Update(); // Note that we do NOT call ImageLowerLeftOff() here. That means that the // lower left pixel is (0, 0), counting upwards moving up the image. tools.loader->SetInputConnection(tools.reader->GetOutputPort(0)); tools.loader->Update(); // Fill out the metadata. tools.metadata.format = tools.format; const int* const dims = tools.loader->GetDataDimensions(); tools.metadata.width = dims[0]; tools.metadata.height = dims[1]; tools.metadata.depth = dims[2]; tools.metadata.channels = tools.loader->GetDataNumberOfScalarComponents(); const int vtk_scalar = tools.loader->GetDataScalarType(); if (std::optional<PixelScalar> pixel_scalar = internal::GetDrakeScalarType(vtk_scalar)) { tools.metadata.scalar = *pixel_scalar; } else { tools.diagnostic->Error(fmt::format( "The image uses an unsupported scalar type (VTK type {})", vtk_scalar)); tools.metadata.channels = 0; } return tools; } // Refer to the comment on ImageIo::LoaderTools::errors for an explanation of // flushing and why we need it. void ImageIo::FlushDiagnostics(const LoaderTools& tools) const { for (const DiagnosticDetail& error : *tools.errors) { diagnostic_.Error(error); } tools.errors->clear(); } namespace { template <typename LoaderTools, PixelType kPixelType> void CopyVtkToDrakeImage(const LoaderTools& tools, Image<kPixelType>* image) { DRAKE_DEMAND(image != nullptr); const Metadata& metadata = tools.metadata; // Reject unsupported depths. It doesn't seem possible for this to happen in // practice with the formats we support. DRAKE_THROW_UNLESS(metadata.depth == 1); // Reject mismatched scalars. const PixelScalar expected_scalar = ImageTraits<kPixelType>::kPixelScalar; if (metadata.scalar != expected_scalar) { // As a backwards compatibility hack, we allow loading 16U data into 16I. const bool allow_hack = ((metadata.scalar == PixelScalar::k16U) && (expected_scalar == PixelScalar::k16I)); if (!allow_hack) { tools.diagnostic->Error( fmt::format("Can't load image with scalar={} into scalar={}.", metadata.scalar, expected_scalar)); return; } } // Reject mismatched num_channels. We generally require the input channel // count to equal the output channel count, but we carve out special cases // where we go from three to four channels (adding alpha to rgb) or four to // three (removing alpha from rgba). constexpr int num_channels = ImageTraits<kPixelType>::kNumChannels; const bool add_alpha = (metadata.channels == 3 && num_channels == 4); const bool drop_alpha = (metadata.channels == 4 && num_channels == 3); if (!add_alpha && !drop_alpha && (metadata.channels != num_channels)) { tools.diagnostic->Error(fmt::format( "Can't load image with channels={} into object with channels={}.", metadata.channels, num_channels)); return; } // Blit everything. constexpr bool swizzle = internal::NeedsBgrSwizzle<kPixelType>(); using T = typename Image<kPixelType>::T; const T* const source = reinterpret_cast<T*>(tools.loader->GetPointerToData()); const int width = metadata.width; const int height = metadata.height; image->resize(width, height); T* dest = image->at(0, 0); if constexpr (sizeof(T) > 1) { DRAKE_DEMAND(!add_alpha); DRAKE_DEMAND(!drop_alpha); internal::CopyAndFlipRaw<T, num_channels, swizzle>(source, dest, width, height); } else { if (add_alpha) { DRAKE_DEMAND(metadata.channels == 3); DRAKE_DEMAND(num_channels == 4); internal::CopyAndFlipRaw<T, 3, swizzle, 4>(source, dest, width, height); } else if (drop_alpha) { DRAKE_DEMAND(metadata.channels == 4); DRAKE_DEMAND(num_channels == 3); internal::CopyAndFlipRaw<T, 4, swizzle, 3>(source, dest, width, height); } else { DRAKE_DEMAND(metadata.channels == num_channels); internal::CopyAndFlipRaw<T, num_channels, swizzle>(source, dest, width, height); } } } } // namespace std::optional<Metadata> ImageIo::LoadMetadataImpl(InputAny input_any) const { // Attempt to parse. LoaderTools tools = MakeLoaderTools(input_any, /* format = */ std::nullopt); // Return the metadata (if we have any). if (!tools.errors->empty()) { // We want to suppress error messages, so we don't call FlushDiagnostics(). return std::nullopt; } return tools.metadata; } ImageAny ImageIo::LoadImpl(InputAny input_any, std::optional<ImageFileFormat> format) const { // Parse the image. LoaderTools tools = MakeLoaderTools(input_any, format); FlushDiagnostics(tools); const Metadata& metadata = tools.metadata; // Construct the image type (chosen based on depth, scalar, and channels). bool match = false; ImageAny result; if (metadata.depth == 1) { switch (metadata.scalar) { case PixelScalar::k8U: { if (metadata.channels == 4) { match = true; result.emplace<ImageRgba8U>(); } else if (metadata.channels == 3) { match = true; result.emplace<ImageRgb8U>(); } else if (metadata.channels == 1) { match = true; result.emplace<ImageGrey8U>(); } break; } case PixelScalar::k16U: { if (metadata.channels == 1) { match = true; result.emplace<ImageDepth16U>(); } break; } case PixelScalar::k32F: { if (metadata.channels == 1) { match = true; result.emplace<ImageDepth32F>(); } break; } case PixelScalar::k16I: DRAKE_UNREACHABLE(); } } // Call a helper function to copy the data into the image. if (match) { std::visit( [&](auto& image) { CopyVtkToDrakeImage(tools, &image); }, result); } else { tools.diagnostic->Error(fmt::format( "Can't load image (depth={}, channels={}, scalar={}) into any known " "Image<PixelType> template instantiation", metadata.depth, metadata.channels, metadata.scalar)); } FlushDiagnostics(tools); return result; } void ImageIo::LoadImpl(InputAny input_any, std::optional<ImageFileFormat> format, ImageAnyMutablePtr image_any) const { // Parse the image. LoaderTools tools = MakeLoaderTools(input_any, format); FlushDiagnostics(tools); // Copy out the bytes. std::visit( [&](auto* image) { CopyVtkToDrakeImage(tools, image); }, image_any); FlushDiagnostics(tools); } } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/sim_rgbd_sensor.cc
#include "drake/systems/sensors/sim_rgbd_sensor.h" #include <memory> #include <optional> #include <regex> #include "drake/systems/lcm/lcm_publisher_system.h" #include "drake/systems/sensors/image_to_lcm_image_array_t.h" namespace drake { namespace systems { namespace sensors { namespace internal { using geometry::SceneGraph; using geometry::render::ColorRenderCamera; using geometry::render::DepthRenderCamera; using math::RigidTransformd; using multibody::MultibodyPlant; // TODO(#10247) Remove this function once all MbP frames are geometry frames. std::pair<geometry::FrameId, RigidTransformd> GetGeometryFrame( const multibody::Frame<double>& sensor_frame, const RigidTransformd& X_PB) { // 'A' is the body for the parent sensor frame. // `P` is the parent of the sensor frame. // `B` is the sensor frame. const auto& frame_P = sensor_frame; const auto& body_A = frame_P.body(); const auto& plant = sensor_frame.GetParentPlant(); const std::optional<geometry::FrameId> body_A_id = plant.GetBodyFrameIdIfExists(body_A.index()); DRAKE_THROW_UNLESS(body_A_id.has_value()); // We must include the offset of the body to ensure that we posture the camera // appropriately. const RigidTransformd X_AP = frame_P.GetFixedPoseInBodyFrame(); const RigidTransformd X_AB = X_AP * X_PB; return std::make_pair(*body_A_id, X_AB); } RgbdSensor* AddSimRgbdSensor(const SceneGraph<double>& scene_graph, const MultibodyPlant<double>& /* plant */, const SimRgbdSensor& sim_rgbd_sensor, DiagramBuilder<double>* builder) { DRAKE_DEMAND(builder != nullptr); const auto [frame_A, X_AB] = GetGeometryFrame(sim_rgbd_sensor.frame(), sim_rgbd_sensor.X_PB()); auto* rgbd_sensor_sys = builder->AddSystem<RgbdSensor>( frame_A, X_AB, sim_rgbd_sensor.color_properties(), sim_rgbd_sensor.depth_properties()); // `set_name` is only used for debugging. rgbd_sensor_sys->set_name("rgbd_sensor_" + sim_rgbd_sensor.serial()); builder->Connect(scene_graph.get_query_output_port(), rgbd_sensor_sys->query_object_input_port()); return rgbd_sensor_sys; } void AddSimRgbdSensorLcmPublisher(std::string_view serial, double fps, double publish_offset, const OutputPort<double>* rgb_port, const OutputPort<double>* depth_16u_port, const OutputPort<double>* label_port, bool do_compress, DiagramBuilder<double>* builder, drake::lcm::DrakeLcmInterface* lcm) { DRAKE_DEMAND(builder != nullptr); DRAKE_DEMAND(lcm != nullptr); if (!rgb_port && !depth_16u_port && !label_port) return; auto image_to_lcm_image_array = builder->AddSystem<ImageToLcmImageArrayT>(do_compress); image_to_lcm_image_array->set_name(fmt::format("image_to_lcm_{}", serial)); if (depth_16u_port) { const auto& lcm_depth_port = image_to_lcm_image_array->DeclareImageInputPort<PixelType::kDepth16U>( "depth"); builder->Connect(*depth_16u_port, lcm_depth_port); } if (rgb_port) { const auto& lcm_rgb_port = image_to_lcm_image_array->DeclareImageInputPort<PixelType::kRgba8U>( "rgb"); builder->Connect(*rgb_port, lcm_rgb_port); } if (label_port) { const auto& lcm_label_port = image_to_lcm_image_array->DeclareImageInputPort<PixelType::kLabel16I>( "label"); builder->Connect(*label_port, lcm_label_port); } auto image_array_lcm_publisher = builder->AddSystem(lcm::LcmPublisherSystem::Make<lcmt_image_array>( fmt::format("DRAKE_RGBD_CAMERA_IMAGES_{}", serial), lcm, 1.0 / fps, publish_offset)); builder->Connect(image_to_lcm_image_array->image_array_t_msg_output_port(), image_array_lcm_publisher->get_input_port()); } void AddSimRgbdSensorLcmPublisher(const SimRgbdSensor& sim_camera, const OutputPort<double>* rgb_port, const OutputPort<double>* depth_16u_port, const OutputPort<double>* label_port, bool do_compress, DiagramBuilder<double>* builder, drake::lcm::DrakeLcmInterface* lcm) { const double publish_offset = 0.0; AddSimRgbdSensorLcmPublisher(sim_camera.serial(), sim_camera.rate_hz(), publish_offset, rgb_port, depth_16u_port, label_port, do_compress, builder, lcm); } } // namespace internal } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/vtk_diagnostic_event_observer.cc
#include "drake/systems/sensors/vtk_diagnostic_event_observer.h" #include <string> namespace drake { namespace systems { namespace sensors { namespace internal { using drake::internal::DiagnosticDetail; using drake::internal::DiagnosticPolicy; VtkDiagnosticEventObserver::VtkDiagnosticEventObserver() = default; VtkDiagnosticEventObserver::~VtkDiagnosticEventObserver() = default; namespace { /* Adjusts the given VTK error or warning message to better conform to Drake style. (VTK likes to spew newlines, but that's annoying in a timestamped and record-oriented console log file.) */ std::string ConvertVtkMessageToDrakeStyle(const char* message) { DRAKE_DEMAND(message != nullptr); std::string result(message); // Remove trailing newlines. while (result.size() > 0 && result.back() == '\n') { result.resize(result.size() - 1); } // Replace embedded newlines. while (true) { auto pos = result.find('\n'); if (pos == std::string::npos) { break; } result = result.replace(pos, 1, ": "); } return result; } } // namespace // NOLINTNEXTLINE(runtime/int) To match the VTK signature. void VtkDiagnosticEventObserver::Execute(vtkObject*, unsigned long event, void* calldata) { switch (event) { case vtkCommand::ErrorEvent: { DRAKE_DEMAND(diagnostic_ != nullptr); const char* message = static_cast<char*>(calldata); diagnostic_->Error(ConvertVtkMessageToDrakeStyle(message)); return; } case vtkCommand::WarningEvent: { DRAKE_DEMAND(diagnostic_ != nullptr); const char* message = static_cast<char*>(calldata); diagnostic_->Warning(ConvertVtkMessageToDrakeStyle(message)); return; } } } } // namespace internal } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/lcm_image_array_receive_example.cc
/// @file This program is an example of using the LcmImageArrayToImages and /// ImageToLcmImageArrayT systems. It receives an incoming stream of /// lcmt_image_array messages, unpacks and repacks the color and /// depth frames, and retransmits the images. The output can be viewed in /// Meldis once #18862 is finished. #include <gflags/gflags.h> #include "drake/lcmt_image_array.hpp" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/lcm/lcm_interface_system.h" #include "drake/systems/lcm/lcm_publisher_system.h" #include "drake/systems/lcm/lcm_subscriber_system.h" #include "drake/systems/sensors/image.h" #include "drake/systems/sensors/image_to_lcm_image_array_t.h" #include "drake/systems/sensors/lcm_image_array_to_images.h" DEFINE_string(channel_name, "DRAKE_RGBD_CAMERA_IMAGES_IN", "Channel name to receive images on"); DEFINE_string(publish_name, "DRAKE_RGBD_CAMERA_IMAGES", "Channel name to publish images on"); DEFINE_double(duration, 5., "Total duration of the simulation in secondes."); namespace drake { namespace systems { namespace sensors { namespace { int DoMain() { DiagramBuilder<double> builder; auto lcm = builder.AddSystem<systems::lcm::LcmInterfaceSystem>(); auto image_sub = builder.AddSystem( systems::lcm::LcmSubscriberSystem::Make<lcmt_image_array>( FLAGS_channel_name, lcm)); auto array_to_images = builder.AddSystem<LcmImageArrayToImages>(); builder.Connect(image_sub->get_output_port(), array_to_images->image_array_t_input_port()); auto image_to_lcm_image_array = builder.AddSystem<ImageToLcmImageArrayT>(true); builder.Connect( array_to_images->color_image_output_port(), image_to_lcm_image_array->DeclareImageInputPort<PixelType::kRgba8U>( "color")); builder.Connect( array_to_images->depth_image_output_port(), image_to_lcm_image_array->DeclareImageInputPort<PixelType::kDepth32F>( "depth")); auto image_array_lcm_publisher = builder.AddSystem(lcm::LcmPublisherSystem::Make<lcmt_image_array>( FLAGS_publish_name, lcm, 0.1 /* publish period */)); builder.Connect(image_to_lcm_image_array->image_array_t_msg_output_port(), image_array_lcm_publisher->get_input_port()); auto diagram = builder.Build(); auto context = diagram->CreateDefaultContext(); auto simulator = std::make_unique<systems::Simulator<double>>( *diagram, std::move(context)); simulator->set_publish_at_initialization(true); simulator->set_publish_every_time_step(false); simulator->set_target_realtime_rate(1.0); simulator->Initialize(); simulator->AdvanceTo(FLAGS_duration); return 0; } } // namespace } // namespace sensors } // namespace systems } // namespace drake int main(int argc, char* argv[]) { gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::systems::sensors::DoMain(); }
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/accelerometer.cc
#include "drake/systems/sensors/accelerometer.h" #include "drake/multibody/math/spatial_algebra.h" namespace drake { namespace systems { namespace sensors { using math::RigidTransform; using math::RotationMatrix; using multibody::SpatialAcceleration; using multibody::SpatialVelocity; template <typename T> Accelerometer<T>::Accelerometer(const multibody::RigidBody<T>& body, const RigidTransform<double>& X_BS, const Eigen::Vector3d& gravity_vector) : Accelerometer(body.index(), X_BS, gravity_vector) {} template <typename T> Accelerometer<T>::Accelerometer(const multibody::BodyIndex& body_index, const RigidTransform<double>& X_BS, const Eigen::Vector3d& gravity_vector) : LeafSystem<T>(SystemTypeTag<Accelerometer>{}), body_index_(body_index), X_BS_(X_BS), gravity_vector_(gravity_vector) { // Declare measurement output port. measurement_output_port_ = &this->DeclareVectorOutputPort( "measurement", 3, &Accelerometer<T>::CalcOutput); body_poses_input_port_ = &this->DeclareAbstractInputPort( "body_poses", Value<std::vector<RigidTransform<T>>>()); body_velocities_input_port_ = &this->DeclareAbstractInputPort( "body_spatial_velocities", Value<std::vector<SpatialVelocity<T>>>()); body_accelerations_input_port_ = &this->DeclareAbstractInputPort( "body_spatial_accelerations", Value<std::vector<SpatialAcceleration<T>>>()); } template <typename T> void Accelerometer<T>::CalcOutput(const Context<T>& context, BasicVector<T>* output) const { const auto& X_WB = get_body_poses_input_port().template Eval<std::vector<RigidTransform<T>>>( context)[body_index_]; const auto& V_WB = get_body_velocities_input_port() .template Eval<std::vector<SpatialVelocity<T>>>(context)[body_index_]; const auto& A_WB = get_body_accelerations_input_port() .template Eval<std::vector<SpatialAcceleration<T>>>( context)[body_index_]; // Kinematic term expressed in world coordinates unless specified // Sensor frame position and orientation. const RotationMatrix<T>& R_WB = X_WB.rotation(); // Express sensor position in world coordinates const Vector3<T>& p_BS_W = R_WB * X_BS_.translation().template cast<T>(); const RotationMatrix<T>& R_BS = X_BS_.rotation().template cast<T>(); // Acceleration of the accelerometer expressed in world coordinates const auto A_WS = A_WB.Shift(p_BS_W, V_WB.rotational()); // Rotation from world to accelerometer const auto R_SW = R_BS.inverse() * R_WB.inverse(); // Rotate to local frame and return output->SetFromVector(R_SW * (A_WS.translational() - gravity_vector_)); } template <typename T> const Accelerometer<T>& Accelerometer<T>::AddToDiagram( const multibody::RigidBody<T>& body, const RigidTransform<double>& X_BS, const Eigen::Vector3d& gravity_vector, const multibody::MultibodyPlant<T>& plant, DiagramBuilder<T>* builder) { const auto& accelerometer = *builder->template AddSystem<Accelerometer<T>>( body, X_BS, gravity_vector); builder->Connect(plant.get_body_poses_output_port(), accelerometer.get_body_poses_input_port()); builder->Connect(plant.get_body_spatial_velocities_output_port(), accelerometer.get_body_velocities_input_port()); builder->Connect(plant.get_body_spatial_accelerations_output_port(), accelerometer.get_body_accelerations_input_port()); return accelerometer; } template <typename T> template <typename U> Accelerometer<T>::Accelerometer(const Accelerometer<U>& other) : Accelerometer(other.body_index(), other.pose(), other.gravity_vector()) {} DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::sensors::Accelerometer) } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/lcm_image_traits.h
#pragma once #include <cstdint> #include "drake/lcmt_image.hpp" #include "drake/systems/sensors/pixel_types.h" namespace drake { namespace systems { namespace sensors { template <PixelFormat> struct LcmPixelTraits; template <> struct LcmPixelTraits<PixelFormat::kRgb> { static constexpr uint8_t kPixelFormat = lcmt_image::PIXEL_FORMAT_RGB; }; template <> struct LcmPixelTraits<PixelFormat::kBgr> { static constexpr uint8_t kPixelFormat = lcmt_image::PIXEL_FORMAT_BGR; }; template <> struct LcmPixelTraits<PixelFormat::kRgba> { static constexpr uint8_t kPixelFormat = lcmt_image::PIXEL_FORMAT_RGBA; }; template <> struct LcmPixelTraits<PixelFormat::kBgra> { static constexpr uint8_t kPixelFormat = lcmt_image::PIXEL_FORMAT_BGRA; }; template <> struct LcmPixelTraits<PixelFormat::kGrey> { static constexpr uint8_t kPixelFormat = lcmt_image::PIXEL_FORMAT_GRAY; }; template <> struct LcmPixelTraits<PixelFormat::kDepth> { static constexpr uint8_t kPixelFormat = lcmt_image::PIXEL_FORMAT_DEPTH; }; template <> struct LcmPixelTraits<PixelFormat::kLabel> { static constexpr uint8_t kPixelFormat = lcmt_image::PIXEL_FORMAT_LABEL; }; template <PixelType> struct LcmImageTraits; template <> struct LcmImageTraits<PixelType::kRgb8U> { static constexpr uint8_t kChannelType = lcmt_image::CHANNEL_TYPE_UINT8; }; template <> struct LcmImageTraits<PixelType::kBgr8U> { static constexpr uint8_t kChannelType = lcmt_image::CHANNEL_TYPE_UINT8; }; template <> struct LcmImageTraits<PixelType::kRgba8U> { static constexpr uint8_t kChannelType = lcmt_image::CHANNEL_TYPE_UINT8; }; template <> struct LcmImageTraits<PixelType::kBgra8U> { static constexpr uint8_t kChannelType = lcmt_image::CHANNEL_TYPE_UINT8; }; template <> struct LcmImageTraits<PixelType::kGrey8U> { static constexpr uint8_t kChannelType = lcmt_image::CHANNEL_TYPE_UINT8; }; template <> struct LcmImageTraits<PixelType::kDepth16U> { static constexpr uint8_t kChannelType = lcmt_image::CHANNEL_TYPE_UINT16; }; template <> struct LcmImageTraits<PixelType::kDepth32F> { static constexpr uint8_t kChannelType = lcmt_image::CHANNEL_TYPE_FLOAT32; }; template <> struct LcmImageTraits<PixelType::kLabel16I> { static constexpr uint8_t kChannelType = lcmt_image::CHANNEL_TYPE_INT16; }; } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/image_writer.cc
#include "drake/systems/sensors/image_writer.h" #include <unistd.h> #include <filesystem> #include <regex> #include <string> #include <utility> #include <vector> #include <fmt/format.h> #include "drake/systems/sensors/image_io.h" namespace drake { namespace systems { namespace sensors { void SaveToPng(const ImageRgba8U& image, const std::string& file_path) { ImageIo{}.Save(image, file_path, ImageFileFormat::kPng); } void SaveToTiff(const ImageDepth32F& image, const std::string& file_path) { ImageIo{}.Save(image, file_path, ImageFileFormat::kTiff); } void SaveToPng(const ImageDepth16U& image, const std::string& file_path) { ImageIo{}.Save(image, file_path, ImageFileFormat::kPng); } void SaveToPng(const ImageLabel16I& image, const std::string& file_path) { ImageIo{}.Save(image, file_path, ImageFileFormat::kPng); } void SaveToPng(const ImageGrey8U& image, const std::string& file_path) { ImageIo{}.Save(image, file_path, ImageFileFormat::kPng); } ImageWriter::ImageWriter() { // NOTE: This excludes *many* of the defined `PixelType` values. labels_[PixelType::kRgba8U] = "color"; extensions_[PixelType::kRgba8U] = ".png"; labels_[PixelType::kDepth32F] = "depth"; extensions_[PixelType::kLabel16I] = ".png"; labels_[PixelType::kLabel16I] = "label"; extensions_[PixelType::kDepth32F] = ".tiff"; labels_[PixelType::kDepth16U] = "depth"; extensions_[PixelType::kDepth16U] = ".png"; labels_[PixelType::kGrey8U] = "grey_scale"; extensions_[PixelType::kGrey8U] = ".png"; // Declares a forced publish event to accommodate non-periodic image saving, // e.g., when saving images outside of Simulator::AdvanceTo. DeclareForcedPublishEvent(&ImageWriter::WriteAllImages); } template <PixelType kPixelType> const InputPort<double>& ImageWriter::DeclareImageInputPort( std::string port_name, std::string file_name_format, double publish_period, double start_time) { // Test to confirm valid pixel type. static_assert(kPixelType == PixelType::kRgba8U || kPixelType == PixelType::kDepth32F || kPixelType == PixelType::kDepth16U || kPixelType == PixelType::kLabel16I || kPixelType == PixelType::kGrey8U, "ImageWriter: the only supported pixel types are: kRgba8U, " "kDepth32F, kDepth16U, kGrey8U, and kLabel16I"); if (publish_period <= 0) { throw std::logic_error("ImageWriter: publish period must be positive"); } // Confirms the implied directory is valid. const std::string test_dir = DirectoryFromFormat(file_name_format, port_name, kPixelType); FolderState folder_state = ValidateDirectory(test_dir); if (folder_state != FolderState::kValid) { const char* const reason = [folder_state]() { switch (folder_state) { case FolderState::kValid: DRAKE_UNREACHABLE(); case FolderState::kMissing: return "the directory does not exist"; case FolderState::kIsFile: return "the directory is actually a file"; case FolderState::kUnwritable: return "no permissions to write the directory"; } DRAKE_UNREACHABLE(); }(); throw std::logic_error( fmt::format("ImageWriter: The format string `{}` implied the invalid " "directory: '{}'; {}", file_name_format, test_dir, reason)); } // Confirms file has appropriate extension. const std::string& extension = extensions_[kPixelType]; if (file_name_format.substr(file_name_format.size() - extension.size()) != extension) { file_name_format += extension; } // TODO(SeanCurtis-TRI): Handle other issues that may arise with filename: // - invalid symbols // - invalid length // - more? // Now configure the system for the valid port declaration. const auto& port = DeclareAbstractInputPort(port_name, Value<Image<kPixelType>>()); // There is no DeclarePeriodicPublishEvent that accepts a lambda, so we must // use the advanced API to add our event. PublishEvent<double> event( TriggerType::kPeriodic, [port_index = port.get_index()](const System<double>& system, const Context<double>& context, const PublishEvent<double>&) { const auto& self = dynamic_cast<const ImageWriter&>(system); self.WriteImage<kPixelType>(context, port_index); return EventStatus::Succeeded(); }); DeclarePeriodicEvent<PublishEvent<double>>(publish_period, start_time, event); port_info_.emplace_back(std::move(file_name_format), kPixelType); return port; } const InputPort<double>& ImageWriter::DeclareImageInputPort( PixelType pixel_type, std::string port_name, std::string file_name_format, double publish_period, double start_time) { switch (pixel_type) { case PixelType::kRgb8U: break; case PixelType::kBgr8U: break; case PixelType::kRgba8U: { return this->template DeclareImageInputPort<PixelType::kRgba8U>( std::move(port_name), std::move(file_name_format), publish_period, start_time); } case PixelType::kBgra8U: break; case PixelType::kDepth16U: { return this->template DeclareImageInputPort<PixelType::kDepth16U>( std::move(port_name), std::move(file_name_format), publish_period, start_time); } case PixelType::kDepth32F: { return this->template DeclareImageInputPort<PixelType::kDepth32F>( std::move(port_name), std::move(file_name_format), publish_period, start_time); } case PixelType::kLabel16I: { return this->template DeclareImageInputPort<PixelType::kLabel16I>( std::move(port_name), std::move(file_name_format), publish_period, start_time); } case PixelType::kGrey8U: { return this->template DeclareImageInputPort<PixelType::kGrey8U>( std::move(port_name), std::move(file_name_format), publish_period, start_time); } } throw std::logic_error(fmt::format( "ImageWriter::DeclareImageInputPort does not support pixel_type={}", static_cast<int>(pixel_type))); } void ImageWriter::ResetAllImageCounts() const { for (const auto& port_info : port_info_) { port_info.count = 0; } } template <PixelType kPixelType> void ImageWriter::WriteImage(const Context<double>& context, int index) const { const auto& port = get_input_port(index); const ImagePortInfo& data = port_info_[index]; const Image<kPixelType>& image = port.Eval<Image<kPixelType>>(context); ImageIo{}.Save(image, MakeFileName(data.format, data.pixel_type, context.get_time(), port.get_name(), data.count++)); } EventStatus ImageWriter::WriteAllImages(const Context<double>& context) const { auto periodic_events = this->AllocateCompositeEventCollection(); this->GetPeriodicEvents(context, periodic_events.get()); return this->Publish(context, periodic_events->get_publish_events()); } std::string ImageWriter::MakeFileName(const std::string& format, PixelType pixel_type, double time, const std::string& port_name, int count) const { DRAKE_DEMAND(labels_.contains(pixel_type)); int64_t u_time = static_cast<int64_t>(time * 1e6 + 0.5); int m_time = static_cast<int>(time * 1e3 + 0.5); return fmt::format(fmt_runtime(format), fmt::arg("port_name", port_name), fmt::arg("image_type", labels_.at(pixel_type)), fmt::arg("time_double", time), fmt::arg("time_usec", u_time), fmt::arg("time_msec", m_time), fmt::arg("count", count)); } std::string ImageWriter::DirectoryFromFormat(const std::string& format, const std::string& port_name, PixelType pixel_type) const { // Extract the directory. Note that in any error messages to the user, we'll // report using the argument name from the public method. if (format.empty()) { throw std::logic_error("ImageWriter: The file_name_format cannot be empty"); } if (format.back() == '/') { throw std::logic_error(fmt::format( "ImageWriter: The file_name_format '{}' cannot end with a '/'", format)); } size_t index = format.rfind('/'); std::string dir_format = format.substr(0, index); // NOTE: [bcdelmosu] are all the characters in: double, msec, and usec. // Technically, this will also key on '{time_mouse}', but if someone is // putting that in their file path, they deserve whatever they get. std::regex invalid_args("\\{count|time_[bcdelmosu]+\\}"); std::smatch match; std::regex_search(dir_format, match, invalid_args); if (!match.empty()) { throw std::logic_error( "ImageWriter: The directory path cannot include time or image count"); } return MakeFileName(dir_format, pixel_type, 0, port_name, 0); } ImageWriter::FolderState ImageWriter::ValidateDirectory( const std::string& file_path_str) { std::filesystem::path file_path(file_path_str); if (std::filesystem::exists(file_path)) { if (std::filesystem::is_directory(file_path)) { if (::access(file_path.string().c_str(), W_OK) == 0) { return FolderState::kValid; } else { return FolderState::kUnwritable; } } else { return FolderState::kIsFile; } } else { return FolderState::kMissing; } } template const InputPort<double>& ImageWriter::DeclareImageInputPort< PixelType::kRgba8U>(std::string port_name, std::string file_name_format, double publish_period, double start_time); template const InputPort<double>& ImageWriter::DeclareImageInputPort< PixelType::kDepth32F>(std::string port_name, std::string file_name_format, double publish_period, double start_time); template const InputPort<double>& ImageWriter::DeclareImageInputPort< PixelType::kLabel16I>(std::string port_name, std::string file_name_format, double publish_period, double start_time); template const InputPort<double>& ImageWriter::DeclareImageInputPort< PixelType::kDepth16U>(std::string port_name, std::string file_name_format, double publish_period, double start_time); template const InputPort<double>& ImageWriter::DeclareImageInputPort< PixelType::kGrey8U>(std::string port_name, std::string file_name_format, double publish_period, double start_time); template void ImageWriter::WriteImage<PixelType::kRgba8U>( const Context<double>& context, int index) const; template void ImageWriter::WriteImage<PixelType::kDepth32F>( const Context<double>& context, int index) const; template void ImageWriter::WriteImage<PixelType::kLabel16I>( const Context<double>& context, int index) const; template void ImageWriter::WriteImage<PixelType::kDepth16U>( const Context<double>& context, int index) const; template void ImageWriter::WriteImage<PixelType::kGrey8U>( const Context<double>& context, int index) const; } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/rgbd_sensor_discrete.cc
#include "drake/systems/sensors/rgbd_sensor_discrete.h" #include <utility> #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/primitives/zero_order_hold.h" #include "drake/systems/sensors/image.h" namespace drake { namespace systems { namespace sensors { RgbdSensorDiscrete::RgbdSensorDiscrete(std::unique_ptr<RgbdSensor> camera, double period, bool render_label_image) : camera_(camera.get()), period_(period) { const auto& color_camera_info = camera->color_camera_info(); const auto& depth_camera_info = camera->depth_camera_info(); DiagramBuilder<double> builder; builder.AddSystem(std::move(camera)); query_object_input_port_ = builder.ExportInput(camera_->query_object_input_port(), "geometry_query"); // Color image. const Value<ImageRgba8U> image_color(color_camera_info.width(), color_camera_info.height()); const auto* const zoh_color = builder.AddSystem<ZeroOrderHold>(period_, image_color); builder.Connect(camera_->color_image_output_port(), zoh_color->get_input_port()); color_image_output_port_ = builder.ExportOutput(zoh_color->get_output_port(), "color_image"); // Depth images. const Value<ImageDepth32F> image_depth_32F(depth_camera_info.width(), depth_camera_info.height()); const auto* const zoh_depth_32F = builder.AddSystem<ZeroOrderHold>(period_, image_depth_32F); builder.Connect(camera_->depth_image_32F_output_port(), zoh_depth_32F->get_input_port()); depth_image_32F_output_port_ = builder.ExportOutput(zoh_depth_32F->get_output_port(), "depth_image_32f"); // Depth images. const Value<ImageDepth16U> image_depth_16U(depth_camera_info.width(), depth_camera_info.height()); const auto* const zoh_depth_16U = builder.AddSystem<ZeroOrderHold>(period_, image_depth_16U); builder.Connect(camera_->depth_image_16U_output_port(), zoh_depth_16U->get_input_port()); depth_image_16U_output_port_ = builder.ExportOutput(zoh_depth_16U->get_output_port(), "depth_image_16u"); // Label image. if (render_label_image) { const Value<ImageLabel16I> image_label(color_camera_info.width(), color_camera_info.height()); const auto* const zoh_label = builder.AddSystem<ZeroOrderHold>(period_, image_label); builder.Connect(camera_->label_image_output_port(), zoh_label->get_input_port()); label_image_output_port_ = builder.ExportOutput(zoh_label->get_output_port(), "label_image"); } const auto* const zoh_body_pose = builder.AddSystem<ZeroOrderHold>(period_, Value<math::RigidTransformd>{}); builder.Connect(camera_->body_pose_in_world_output_port(), zoh_body_pose->get_input_port()); body_pose_in_world_output_port_ = builder.ExportOutput( zoh_body_pose->get_output_port(), "body_pose_in_world"); const auto* const zoh_image_time = builder.AddSystem<ZeroOrderHold>(period_, 1); builder.Connect(camera_->image_time_output_port(), zoh_image_time->get_input_port()); image_time_output_port_ = builder.ExportOutput(zoh_body_pose->get_output_port(), "image_time"); builder.BuildInto(this); } } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/image_to_lcm_image_array_t.cc
#include "drake/systems/sensors/image_to_lcm_image_array_t.h" #include <stdexcept> #include <zlib.h> #include "drake/lcmt_image.hpp" #include "drake/lcmt_image_array.hpp" #include "drake/systems/sensors/lcm_image_traits.h" using std::string; namespace drake { namespace systems { namespace sensors { namespace { const int64_t kSecToMillisec = 1000000; // Overwrites the msg's compression_method, size, and data. template <PixelType kPixelType> void Compress(const Image<kPixelType>& image, lcmt_image* msg) { msg->compression_method = lcmt_image::COMPRESSION_METHOD_ZLIB; const int source_size = image.width() * image.height() * image.kPixelSize; // The destination buf_size must be slightly larger than the source size. // http://refspecs.linuxbase.org/LSB_3.0.0/LSB-PDA/LSB-PDA/zlib-compress2-1.html std::vector<uint8_t>& dest = msg->data; size_t dest_size = source_size * 1.001 + 12; dest.resize(dest_size); auto compress_status = compress2( dest.data(), &dest_size, reinterpret_cast<const Bytef*>(image.at(0, 0)), source_size, Z_BEST_SPEED); DRAKE_DEMAND(compress_status == Z_OK); DRAKE_DEMAND(dest_size <= dest.size()); dest.resize(dest_size); msg->size = dest_size; } // Overwrites the msg's compression_method, size, and data. template <PixelType kPixelType> void Pack(const Image<kPixelType>& image, lcmt_image* msg) { msg->compression_method = lcmt_image::COMPRESSION_METHOD_NOT_COMPRESSED; const int size = image.width() * image.height() * image.kPixelSize; msg->data.resize(size); msg->size = size; memcpy(&msg->data[0], image.at(0, 0), size); } // Overwrites everything in msg except its header. template <PixelType kPixelType> void PackImageToLcmImageT(const Image<kPixelType>& image, lcmt_image* msg, bool do_compress) { msg->width = image.width(); msg->height = image.height(); msg->row_stride = image.kPixelSize * msg->width; msg->bigendian = false; msg->pixel_format = LcmPixelTraits<ImageTraits<kPixelType>::kPixelFormat>::kPixelFormat; msg->channel_type = LcmImageTraits<kPixelType>::kChannelType; if (do_compress) { Compress(image, msg); } else { Pack(image, msg); } } // Overwrites everything in msg except its header. void PackImageToLcmImageT(const AbstractValue& untyped_image, PixelType pixel_type, lcmt_image* msg, bool do_compress) { switch (pixel_type) { case PixelType::kRgb8U: { const auto& image_value = untyped_image.get_value<Image<PixelType::kRgb8U>>(); PackImageToLcmImageT(image_value, msg, do_compress); break; } case PixelType::kBgr8U: { const auto& image_value = untyped_image.get_value<Image<PixelType::kBgr8U>>(); PackImageToLcmImageT(image_value, msg, do_compress); break; } case PixelType::kRgba8U: { const auto& image_value = untyped_image.get_value<Image<PixelType::kRgba8U>>(); PackImageToLcmImageT(image_value, msg, do_compress); break; } case PixelType::kBgra8U: { const auto& image_value = untyped_image.get_value<Image<PixelType::kBgra8U>>(); PackImageToLcmImageT(image_value, msg, do_compress); break; } case PixelType::kGrey8U: { const auto& image_value = untyped_image.get_value<Image<PixelType::kGrey8U>>(); PackImageToLcmImageT(image_value, msg, do_compress); break; } case PixelType::kDepth16U: { const auto& image_value = untyped_image.get_value<Image<PixelType::kDepth16U>>(); PackImageToLcmImageT(image_value, msg, do_compress); break; } case PixelType::kDepth32F: { const auto& image_value = untyped_image.get_value<Image<PixelType::kDepth32F>>(); PackImageToLcmImageT(image_value, msg, do_compress); break; } case PixelType::kLabel16I: { const auto& image_value = untyped_image.get_value<Image<PixelType::kLabel16I>>(); PackImageToLcmImageT(image_value, msg, do_compress); break; } } } } // namespace ImageToLcmImageArrayT::ImageToLcmImageArrayT(bool do_compress) : do_compress_(do_compress) { image_array_t_msg_output_port_index_ = DeclareAbstractOutputPort(kUseDefaultName, &ImageToLcmImageArrayT::CalcImageArray) .get_index(); } ImageToLcmImageArrayT::ImageToLcmImageArrayT(const string& color_frame_name, const string& depth_frame_name, const string& label_frame_name, bool do_compress) : do_compress_(do_compress) { color_image_input_port_index_ = DeclareImageInputPort<PixelType::kRgba8U>(color_frame_name).get_index(); depth_image_input_port_index_ = DeclareImageInputPort<PixelType::kDepth32F>(depth_frame_name).get_index(); label_image_input_port_index_ = DeclareImageInputPort<PixelType::kLabel16I>(label_frame_name).get_index(); image_array_t_msg_output_port_index_ = DeclareAbstractOutputPort(kUseDefaultName, &ImageToLcmImageArrayT::CalcImageArray) .get_index(); } const InputPort<double>& ImageToLcmImageArrayT::color_image_input_port() const { DRAKE_DEMAND(color_image_input_port_index_ >= 0); return this->get_input_port(color_image_input_port_index_); } const InputPort<double>& ImageToLcmImageArrayT::depth_image_input_port() const { DRAKE_DEMAND(depth_image_input_port_index_ >= 0); return this->get_input_port(depth_image_input_port_index_); } const InputPort<double>& ImageToLcmImageArrayT::label_image_input_port() const { DRAKE_DEMAND(label_image_input_port_index_ >= 0); return this->get_input_port(label_image_input_port_index_); } const OutputPort<double>& ImageToLcmImageArrayT::image_array_t_msg_output_port() const { return System<double>::get_output_port(image_array_t_msg_output_port_index_); } void ImageToLcmImageArrayT::CalcImageArray( const systems::Context<double>& context, lcmt_image_array* msg) const { // A best practice for filling in LCM messages is to first value-initialize // the entire message to its defaults ("*msg = {}") before setting any new // values. That way, if we happen to skip over any fields, they will be // zeroed out instead of leaving behind garbage from whatever the msg memory // happened to contain beforehand. // // In our case though, image data is typically high-bandwidth, so we will // carefully work to reuse our message vectors' storage instead of clearing // it on every call. (The headers are small, though, so we'll still clear // them.) const int64_t utime = static_cast<int64_t>(context.get_time() * kSecToMillisec); msg->header = {}; msg->header.utime = utime; const int num_inputs = num_input_ports(); msg->num_images = num_inputs; msg->images.resize(num_inputs); for (int i = 0; i < num_inputs; i++) { const std::string& name = this->get_input_port(i).get_name(); const PixelType& type = input_port_pixel_type_[i]; const auto& value = this->get_input_port(i).template Eval<AbstractValue>(context); lcmt_image& packed = msg->images.at(i); packed.header = {}; packed.header.utime = utime; packed.header.frame_name = name; PackImageToLcmImageT(value, type, &packed, do_compress_); } } } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/rotary_encoders.h
#pragma once #include <memory> #include <vector> #include "drake/common/drake_copyable.h" #include "drake/common/eigen_types.h" #include "drake/systems/framework/vector_system.h" namespace drake { namespace systems { namespace sensors { /// Simple model to capture the quantization and calibration offset effects /// of a rotary encoder. Consider combining this with a ZeroOrderHold system /// to capture the sampled-data effects. /// /// The inputs to this system are assumed to be in radians, and the outputs of /// the system are also in radians. /// /// @system /// name: RotaryEncoders /// input_ports: /// - u0 /// output_ports: /// - y0 /// @endsystem /// /// @ingroup sensor_systems template <typename T> class RotaryEncoders final : public VectorSystem<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(RotaryEncoders) /// Quantization-only constructor. Specifies one ticks_per_revolution count /// for every element of the input port. explicit RotaryEncoders(const std::vector<int>& ticks_per_revolution); /// Selector-only constructor. Provides arguments to select particular /// indices from the input signal to use in the output. Since /// ticks_per_revolution is not being set, the outputs will NOT be quantized. /// @param input_port_size Dimension of the expected input signal /// @param input_vector_indices List of indices RotaryEncoders(int input_port_size, const std::vector<int>& input_vector_indices); /// Quantization and Selector constructor. RotaryEncoders(int input_port_size, const std::vector<int>& input_vector_indices, const std::vector<int>& ticks_per_revolution); /// Scalar-converting copy constructor. See @ref system_scalar_conversion. template <typename U> explicit RotaryEncoders(const RotaryEncoders<U>&); /// Set the calibration offset parameters. void set_calibration_offsets( Context<T>* context, const Eigen::Ref<VectorX<T>>& calibration_offsets) const; /// Retrieve the calibration offset parameters. const VectorX<T>& get_calibration_offsets(const Context<T>& context) const; private: // Allow different specializations to access each other's private data. template <typename> friend class RotaryEncoders; // Outputs the transformed signal. void DoCalcVectorOutput( const Context<T>& context, const Eigen::VectorBlock<const VectorX<T>>& input, const Eigen::VectorBlock<const VectorX<T>>& state, Eigen::VectorBlock<VectorX<T>>* output) const override; const int num_encoders_{0}; // Dimension of the output port. const std::vector<int> indices_; // Selects from the input port. const std::vector<int> ticks_per_revolution_; // For quantization. }; } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/image.h
#pragma once #include <limits> #include <utility> #include <variant> #include <vector> #include "drake/common/drake_assert.h" #include "drake/common/drake_copyable.h" #include "drake/common/drake_throw.h" #include "drake/common/reset_after_move.h" #include "drake/systems/sensors/pixel_types.h" namespace drake { namespace systems { namespace sensors { // Forward declaration of Image class. template <PixelType kPixelType> class Image; /// The type for RGB image where the each channel has the type of uint8_t. using ImageRgb8U = Image<PixelType::kRgb8U>; /// The type for BGR image where the each channel has the type of uint8_t. using ImageBgr8U = Image<PixelType::kBgr8U>; /// The type for RGBA image where the each channel has the type of uint8_t. using ImageRgba8U = Image<PixelType::kRgba8U>; /// The type for BGRA image where the each channel has the type of uint8_t. using ImageBgra8U = Image<PixelType::kBgra8U>; /// The type for depth image where the channel has the type of float. using ImageDepth32F = Image<PixelType::kDepth32F>; /// The type for depth image where the channel has the type of uint16_t. using ImageDepth16U = Image<PixelType::kDepth16U>; /// The type for label image where the channel has the type of int16_t. using ImageLabel16I = Image<PixelType::kLabel16I>; /// The type for greyscale image where the channel has the type of uint8_t. using ImageGrey8U = Image<PixelType::kGrey8U>; /// A sum type of all built-in images types. using ImageAny = std::variant< // Keep this list alpha-sorted: // clang-format off ImageBgr8U, ImageBgra8U, ImageDepth16U, ImageDepth32F, ImageGrey8U, ImageRgb8U, ImageRgba8U, ImageLabel16I>; // clang-format on /// Simple data format for Image. For the complex calculation with the image, /// consider converting this to other libaries' Matrix data format, i.e., /// MatrixX in Eigen, Mat in OpenCV, and so on. /// /// The origin of image coordinate system is on the left-upper corner. /// /// @tparam kPixelType The pixel type enum that denotes the pixel format and the /// data type of a channel. /// TODO(zachfang): move most of the function definitions in this class to the /// .cc file. template <PixelType kPixelType> class Image { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Image) /// This is used by generic helpers such as drake::Value to deduce a non-type /// template argument. using NonTypeTemplateParameter = std::integral_constant<PixelType, kPixelType>; /// An alias for ImageTraits that contains the data type for a channel, /// the number of channels and the pixel format in it. using Traits = ImageTraits<kPixelType>; /// The data type for a channel. using T = typename Traits::ChannelType; /// The number of channels in a pixel. static constexpr int kNumChannels = Traits::kNumChannels; /// The size of a pixel in bytes. static constexpr int kPixelSize = kNumChannels * sizeof(T); /// The format for pixels. static constexpr PixelFormat kPixelFormat = Traits::kPixelFormat; /// Constructs a zero-sized image. Image() = default; /// Image size only constructor. Specifies a width and height for the image. /// The width and height can be either both zero or both strictly positive. /// All the channel values in all the pixels are initialized with zero. Image(int width, int height) : Image(width, height, 0) {} /// Image size and initial value constructor. Specifies a /// width, height and an initial value for all the channels in all the pixels. /// The width and height can be either both zero or both strictly positive. Image(int width, int height, T initial_value) : width_(width), height_(height), data_(width * height * kNumChannels, initial_value) { DRAKE_THROW_UNLESS((width >= 0) && (height >= 0)); DRAKE_THROW_UNLESS((width == 0) == (height == 0)); } /// Returns the size of width for the image int width() const { return width_; } /// Returns the size of height for the image int height() const { return height_; } /// Returns the result of the number of pixels in a image by the number of /// channels in a pixel int size() const { return width_ * height_ * kNumChannels; } /// Changes the sizes of the width and height for the image. The new width /// and height can be either both zero or both strictly positive. All the /// values in the pixels become zero after resize. void resize(int width, int height) { DRAKE_THROW_UNLESS((width >= 0) && (height >= 0)); DRAKE_THROW_UNLESS((width == 0) == (height == 0)); data_.resize(width * height * kNumChannels); std::fill(data_.begin(), data_.end(), 0); width_ = width; height_ = height; } /// Access to the pixel located at (x, y) in image coordinate system where x /// is the variable for horizontal direction and y is one for vertical /// direction. To access to the each channel value in the pixel (x, y), /// you can do: /// /// ImageRgbaU8 image(640, 480, 255); /// uint8_t red = image.at(x, y)[0]; /// uint8_t green = image.at(x, y)[1]; /// uint8_t blue = image.at(x, y)[2]; /// uint8_t alpha = image.at(x, y)[3]; T* at(int x, int y) { DRAKE_ASSERT(x >= 0 && x < width_); DRAKE_ASSERT(y >= 0 && y < height_); return data_.data() + (x + y * width_) * kNumChannels; } /// Const version of at() method. See the document for the non-const version /// for the detail. const T* at(int x, int y) const { DRAKE_ASSERT(x >= 0 && x < width_); DRAKE_ASSERT(y >= 0 && y < height_); return data_.data() + (x + y * width_) * kNumChannels; } /// Compares whether two images are exactly the same. bool operator==(const Image& other) const { return width_ == other.width_ && height_ == other.height_ && data_ == other.data_; } private: reset_after_move<int> width_; reset_after_move<int> height_; std::vector<T> data_; }; /// Converts a single channel 32-bit float depth image with depths in meters to /// a single channel 16-bit unsigned int depth image with depths in millimeters. /// /// Note that pixels that are not kTooFar in the input image may saturate to be /// kTooFar in the output image due to the smaller representable range. void ConvertDepth32FTo16U(const ImageDepth32F& input, ImageDepth16U* output); /// Converts a single channel 16-bit unsigned int depth image with depths in /// millimeters to a single channel 32-bit float depth image with depths in /// meters. void ConvertDepth16UTo32F(const ImageDepth16U& input, ImageDepth32F* output); } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/image_to_lcm_image_array_t.h
#pragma once #include <string> #include <vector> #include "drake/common/drake_copyable.h" #include "drake/lcmt_image_array.hpp" #include "drake/systems/framework/leaf_system.h" #include "drake/systems/sensors/image.h" #include "drake/systems/sensors/pixel_types.h" namespace drake { namespace systems { namespace sensors { // TODO(jwnimmer-tri) Throughout this filename, classname, and method names, the // the "_t" or "T" suffix is superfluous and should be removed. /// An ImageToLcmImageArrayT takes as input an ImageRgba8U, ImageDepth32F and /// ImageLabel16I. This system outputs an AbstractValue containing a /// `Value<lcmt_image_array>` LCM message that defines an array of images /// (lcmt_image). This message can then be sent to other processes that /// sbscribe it using LcmPublisherSystem. Note that you should NOT assume any /// particular order of those images stored in lcmt_image_array, /// instead check the semantic of those images with /// lcmt_image::pixel_format before using them. /// /// @system /// name: ImageToLcmImageArrayT /// input_ports: /// - (user assigned port name) /// - ... /// - (user assigned port name) /// output_ports: /// - y0 /// @endsystem /// /// @note The output message's header field `seq` is always zero. class ImageToLcmImageArrayT : public systems::LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ImageToLcmImageArrayT) /// Constructs an empty system with no input ports. /// After construction, use DeclareImageInputPort() to add inputs. explicit ImageToLcmImageArrayT(bool do_compress = false); /// An %ImageToLcmImageArrayT constructor. Declares three input ports -- /// one color image, one depth image, and one label image. /// /// @param color_frame_name The frame name used for color image. /// @param depth_frame_name The frame name used for depth image. /// @param label_frame_name The frame name used for label image. /// @param do_compress When true, zlib compression will be performed. The /// default is false. ImageToLcmImageArrayT(const std::string& color_frame_name, const std::string& depth_frame_name, const std::string& label_frame_name, bool do_compress = false); /// Returns the input port containing a color image. /// Note: Only valid if the color/depth/label constructor is used. const InputPort<double>& color_image_input_port() const; /// Returns the input port containing a depth image. /// Note: Only valid if the color/depth/label constructor is used. const InputPort<double>& depth_image_input_port() const; /// Returns the input port containing a label image. /// Note: Only valid if the color/depth/label constructor is used. const InputPort<double>& label_image_input_port() const; /// Returns the abstract valued output port that contains a /// `Value<lcmt_image_array>`. const OutputPort<double>& image_array_t_msg_output_port() const; template <PixelType kPixelType> const InputPort<double>& DeclareImageInputPort(const std::string& name) { input_port_pixel_type_.push_back(kPixelType); return this->DeclareAbstractInputPort(name, Value<Image<kPixelType>>()); } private: void CalcImageArray(const systems::Context<double>& context, lcmt_image_array* msg) const; int color_image_input_port_index_{-1}; int depth_image_input_port_index_{-1}; int label_image_input_port_index_{-1}; int image_array_t_msg_output_port_index_{-1}; std::vector<PixelType> input_port_pixel_type_{}; const bool do_compress_; }; } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/pixel_types.h
#pragma once #include <cstdint> #include <limits> #include <string> #include "drake/common/fmt.h" #include "drake/common/hash.h" #include "drake/common/symbolic/expression.h" namespace drake { namespace systems { namespace sensors { /// The enum class to be used for describing pixel type in Image class. /// The naming rule for the enum members is: /// k + (pixel format) + (bit per a channel) + (data type for channels). /// For the type for channels, one of the following capital letters is used. /// /// - I: int /// - U: unsigned int /// - F: float enum class PixelType { /// The pixel format used by ImageRgb8U. kRgb8U, /// The pixel format used by ImageBgr8U. kBgr8U, /// The pixel format used by ImageRgba8U. kRgba8U, /// The pixel format used by ImageBgra8U. kBgra8U, /// The pixel format used by ImageGrey8U. kGrey8U, /// The pixel format used by ImageDepth16U. kDepth16U, /// The pixel format used by ImageDepth32F. kDepth32F, /// The pixel format used by ImageLabel16I. kLabel16I, }; std::string to_string(PixelType); /// The enum class to be used to express semantic meaning of pixels. /// This also expresses the order of channels in a pixel if the pixel has /// multiple channels. enum class PixelFormat { /// The pixel format used for all the RGB images. kRgb, /// The pixel format used for all the BGR images. kBgr, /// The pixel format used for all the RGBA images. kRgba, /// The pixel format used for all the BGRA images. kBgra, /// The pixel format used for all the greyscale images. kGrey, /// The pixel format used for all the depth images. kDepth, /// The pixel format used for all the labe images. kLabel, }; std::string to_string(PixelFormat); /// The enum class to be used to express channel type. enum class PixelScalar { /// uint8_t k8U, /// int16_t k16I, /// uint16_t k16U, /// float (32-bit) k32F, }; std::string to_string(PixelScalar); /// Traits class for Image, specialized by PixelType. /// /// All traits specialization should offer at least these two constants: /// - kNumChannels: The number of channels. /// - kPixelFormat: The meaning and/or layout of the channels. /// /// Specializations for kDepth... should also provide the following constants: /// - kTooClose: The depth value when the min sensing range is exceeded. /// - kTooFar: The depth value when the max sensing range is exceeded. /// /// The kTooClose values <a href="http://www.ros.org/reps/rep-0117.html">differ /// from ROS</a>, which uses negative infinity in this scenario. Drake uses /// zero because it results in less devastating bugs when users fail to check /// for the lower limit being hit, because using negative infinity does not /// prevent users from writing bad code, because uint16_t does not offer /// negative infinity and using 65535 for "too near" could be confusing, and /// because several cameras natively use zero for this case. template <PixelType> struct ImageTraits; template <> struct ImageTraits<PixelType::kRgb8U> { typedef uint8_t ChannelType; static constexpr int kNumChannels = 3; static constexpr PixelScalar kPixelScalar = PixelScalar::k8U; static constexpr PixelFormat kPixelFormat = PixelFormat::kRgb; }; template <> struct ImageTraits<PixelType::kBgr8U> { typedef uint8_t ChannelType; static constexpr int kNumChannels = 3; static constexpr PixelScalar kPixelScalar = PixelScalar::k8U; static constexpr PixelFormat kPixelFormat = PixelFormat::kBgr; }; template <> struct ImageTraits<PixelType::kRgba8U> { typedef uint8_t ChannelType; static constexpr int kNumChannels = 4; static constexpr PixelScalar kPixelScalar = PixelScalar::k8U; static constexpr PixelFormat kPixelFormat = PixelFormat::kRgba; }; template <> struct ImageTraits<PixelType::kBgra8U> { typedef uint8_t ChannelType; static constexpr int kNumChannels = 4; static constexpr PixelScalar kPixelScalar = PixelScalar::k8U; static constexpr PixelFormat kPixelFormat = PixelFormat::kBgra; }; template <> struct ImageTraits<PixelType::kDepth32F> { typedef float ChannelType; static constexpr int kNumChannels = 1; static constexpr PixelScalar kPixelScalar = PixelScalar::k32F; static constexpr PixelFormat kPixelFormat = PixelFormat::kDepth; static constexpr ChannelType kTooClose = 0.0f; static constexpr ChannelType kTooFar = std::numeric_limits<ChannelType>::infinity(); }; template <> struct ImageTraits<PixelType::kDepth16U> { typedef uint16_t ChannelType; static constexpr int kNumChannels = 1; static constexpr PixelScalar kPixelScalar = PixelScalar::k16U; static constexpr PixelFormat kPixelFormat = PixelFormat::kDepth; static constexpr ChannelType kTooClose = 0; static constexpr ChannelType kTooFar = std::numeric_limits<ChannelType>::max(); }; template <> struct ImageTraits<PixelType::kLabel16I> { typedef int16_t ChannelType; static constexpr int kNumChannels = 1; static constexpr PixelScalar kPixelScalar = PixelScalar::k16I; static constexpr PixelFormat kPixelFormat = PixelFormat::kLabel; }; template <> struct ImageTraits<PixelType::kGrey8U> { typedef uint8_t ChannelType; static constexpr int kNumChannels = 1; static constexpr PixelScalar kPixelScalar = PixelScalar::k8U; static constexpr PixelFormat kPixelFormat = PixelFormat::kGrey; }; } // namespace sensors } // namespace systems } // namespace drake // Enable the pixel type enumeration to be used as a map key. namespace std { template <> struct hash<drake::systems::sensors::PixelType> : public drake::DefaultHash {}; } // namespace std DRAKE_FORMATTER_AS(, drake::systems::sensors, PixelType, x, drake::systems::sensors::to_string(x)) DRAKE_FORMATTER_AS(, drake::systems::sensors, PixelFormat, x, drake::systems::sensors::to_string(x)) DRAKE_FORMATTER_AS(, drake::systems::sensors, PixelScalar, x, drake::systems::sensors::to_string(x))
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/lcm_image_array_to_images.h
#pragma once #include <string> #include "drake/common/drake_copyable.h" #include "drake/systems/framework/leaf_system.h" #include "drake/systems/sensors/image.h" namespace drake { namespace systems { namespace sensors { /// An LcmImageArrayToImages takes as input an AbstractValue containing a /// `Value<lcmt_image_array>` LCM message that defines an array /// of images (lcmt_image). The system has output ports for one color image as /// an ImageRgba8U and one depth image as ImageDepth32F (intended to be /// similar to the API of RgbdCamera, though without the label image port). /// /// @system /// name: LcmImageArrayToImages /// input_ports: /// - image_array_t /// output_ports: /// - color_image /// - depth_image /// - label_image /// @endsystem class LcmImageArrayToImages : public LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LcmImageArrayToImages) LcmImageArrayToImages(); // TODO(jwnimmer-tri) The "_t" or "T" suffix on this method name is // superfluous and should be removed. /// Returns the abstract valued input port that expects a /// `Value<lcmt_image_array>`. const InputPort<double>& image_array_t_input_port() const { return this->get_input_port(image_array_t_input_port_index_); } /// Returns the abstract valued output port that contains a RGBA image of /// the type ImageRgba8U. The image will be empty if no color image was /// received in the most recent message (so, for example, sending color and /// depth in different messages will not produce useful results). const OutputPort<double>& color_image_output_port() const { return this->get_output_port(color_image_output_port_index_); } /// Returns the abstract valued output port that contains an ImageDepth32F. /// The image will be empty if no color image was received in the most /// recent message (so, for example, sending color and depth in different /// messages will not produce useful results). const OutputPort<double>& depth_image_output_port() const { return this->get_output_port(depth_image_output_port_index_); } /// Returns the abstract valued output port that contains an ImageLabel16I. /// The image will be empty if no label image was received in the most /// recent message (so, for example, sending color and label in different /// messages will not produce useful results). const OutputPort<double>& label_image_output_port() const { return this->get_output_port(label_image_output_port_index_); } private: void CalcColorImage(const Context<double>& context, ImageRgba8U* color_image) const; void CalcDepthImage(const Context<double>& context, ImageDepth32F* depth_image) const; void CalcLabelImage(const Context<double>& context, ImageLabel16I* label_image) const; const InputPortIndex image_array_t_input_port_index_; const OutputPortIndex color_image_output_port_index_; const OutputPortIndex depth_image_output_port_index_; const OutputPortIndex label_image_output_port_index_; }; } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/rgbd_sensor_discrete.h
#pragma once #include <memory> #include "drake/common/drake_copyable.h" #include "drake/systems/framework/diagram.h" #include "drake/systems/sensors/rgbd_sensor.h" namespace drake { namespace systems { namespace sensors { #ifndef DRAKE_DOXYGEN_CXX class RgbdSensor; #endif /** Wraps a continuous RgbdSensor with a zero-order hold to create a discrete sensor. @system name: RgbdSensorDiscrete input_ports: - geometry_query output_ports: - color_image - depth_image_32f - depth_image_16u - label_image - body_pose_in_world - image_time @endsystem See also RgbdSensorAsync for a slightly different discrete sensor model. @note Be mindful that the discrete dynamics of a zero-order hold mean that all three image types (color, depth, label) are rendered at the given `period`, even if nothing ends up using the images on the output ports; this might be computationally wasteful. If you only need color and depth, be sure to pass `render_label_image = false` to the constructor. If you only need one image type, eschew this system in favor of adding your own zero-order hold on just the one RgbdSensor output port that you need. @ingroup sensor_systems */ class RgbdSensorDiscrete final : public Diagram<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(RgbdSensorDiscrete); static constexpr double kDefaultPeriod = 1.0 / 30; /** Constructs a diagram containing a (non-registered) RgbdSensor that will update at a given rate. @param sensor The continuous sensor used to generate periodic images. @param period Update period (sec). @param render_label_image If true, renders label image (which requires additional overhead). If false, `label_image_output_port` will raise an error if called. */ RgbdSensorDiscrete(std::unique_ptr<RgbdSensor> sensor, double period = kDefaultPeriod, bool render_label_image = true); /** Returns a reference to the underlying RgbdSensor object. */ const RgbdSensor& sensor() const { return *camera_; } /** Returns the update period for the discrete camera. */ double period() const { return period_; } /** @see RgbdSensor::query_object_input_port(). */ const InputPort<double>& query_object_input_port() const { return get_input_port(query_object_input_port_); } /** @see RgbdSensor::color_image_output_port(). */ const systems::OutputPort<double>& color_image_output_port() const { return get_output_port(color_image_output_port_); } /** @see RgbdSensor::depth_image_32F_output_port(). */ const systems::OutputPort<double>& depth_image_32F_output_port() const { return get_output_port(depth_image_32F_output_port_); } /** @see RgbdSensor::depth_image_16U_output_port(). */ const systems::OutputPort<double>& depth_image_16U_output_port() const { return get_output_port(depth_image_16U_output_port_); } /** @see RgbdSensor::label_image_output_port(). */ const systems::OutputPort<double>& label_image_output_port() const { return get_output_port(label_image_output_port_); } /** @see RgbdSensor::body_pose_in_world_output_port(). */ const OutputPort<double>& body_pose_in_world_output_port() const { return get_output_port(body_pose_in_world_output_port_); } /** Returns the vector-valued output port (with size == 1) which reports the simulation time when the image outputs were captured, in seconds (i.e., the time of the most recent zero-order hold discrete update). */ const OutputPort<double>& image_time_output_port() const { return get_output_port(image_time_output_port_); } private: RgbdSensor* const camera_{}; const double period_{}; int query_object_input_port_{-1}; int color_image_output_port_{-1}; int depth_image_32F_output_port_{-1}; int depth_image_16U_output_port_{-1}; int label_image_output_port_{-1}; int body_pose_in_world_output_port_{-1}; int image_time_output_port_{-1}; }; } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/camera_info.h
#pragma once #include <Eigen/Dense> #include "drake/common/drake_copyable.h" namespace drake { namespace systems { namespace sensors { // TODO(kunimatsu-tri) Add camera distortion parameters and other parameters as // needed. // TODO(SeanCurtis-TRI) Deprecate the name CameraInfo in favor of Intrinsics. /** Simple class for characterizing the Drake camera model. The camera model is based on the [pinhole _model_](http://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html), which is related to but distinct from an actual [pinhole _camera_](https://en.wikipedia.org/wiki/Pinhole_camera). The former is a mathematical model for producing images, the latter is a physical object. The camera info members are directly tied to the underlying model's mathematical parameters. In order to understand the model parameters, we will provide a discussion of how cameras are treated in Drake with some common terminology (liberally borrowed from computer vision). <h3>Pinhole camera model</h3> (To get an exact definition of the terms used here, please refer to the glossary below.) Intuitively, a camera produces images of an observed environment. The pinhole model serves as a camera for a virtually modeled environment. Its parameters are those required to determine where in the resultant image a virtual object appears. In essence, the parameters of the camera model define a mapping from points in 3D space to a point on the image (2D space). The full discussion of this mapping can be found in the [OpenCV documentation](https://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html). Here, we'll highlight one or two points as it relates to this struct. The mapping from 3D to 2D is decomposed into two sets of properties: extrinsic and intrinsic. The extrinsic properties define the pose of the camera in the environment -- specifically, given the camera frame `C`, it defines `X_WC`. Once a point `Q` is measured and expressed in the camera's frame (i.e., `p_CQ_C`), the intrinsic matrix projects it into the 2D image. %CameraInfo does _not_ concern itself with the extrinsic properties (other classes are responsible for that -- see RgbdSensor). %CameraInfo defines the parameters of the intrinsic projection. The projection can be captured by the camera or intrinsic matrix which essentially maps points in the camera frame C to the image plane. The camera looks along the positive `Cz` axis, and the `Cy` axis points down. The projection matrix is called `A` in the OpenCV documentation, but typically called `K` in computer vision literature: │ f_x 0 c_x │ K = │ 0 f_y c_y │, i.e., │ 0 0 1 │ - This matrix maps a point in the camera frame C to the projective space of the image (via homogeneous coordinates). The resulting image coordinate `(u, v)` is extracted by dividing out the homogeneous scale factor. - (c_x, c_y) defines the principal point. - (f_x, f_y) defines the model focal length. In other words, for point Q in the world frame, its projected position in the 2D image `(u_Q, v_Q)` is calculated as: │ u_Q │ s│ v_Q │ = K ⋅ X_CW ⋅ p_WQ │ 1 │ Note: The expression on the right will generally produce a homogeneous coordinate vector of the form `(s * u_Q, s * v_Q, s)`. The texture coordinate is defined as the first two measures when the *third* measure is 1. The magic of homogeneous coordinates allows us to simply factor out `s`. @anchor camera_axes_in_image <h3>Alignment of the camera frame with the image</h3> When looking at the resulting image and reasoning about the camera that produced it, one can say that Cz points into the image, Cx is parallel with the image rows, pointing to the right, and Cy is parallel with the image columns, pointing down leading to language such as: "X-right", "Y-down", and "Z-forward". <h3>Glossary</h3> These terms are important to the discussion. Some refer to real world concepts and some to the model. The application domain of the term will be indicated and, where necessary, ambiguities will be resolved. The terms are ordered alphabetically for ease of reference. - __aperture__: the opening in a camera through which light passes. The origin of the camera frame `Co` is located at the aperture's center. - in a physical camera it may contain a lens and the size of the camera affects optical artifacts such as depth of field. - in the pinhole model, there is no lens and the aperture is a single point. - __focal length__: a camera property that determines the field of view angle and the scale of objects in the image (large focal length --> small field of view angle). - In a physical camera, it is the distance (in meters) between the center of the lens and the plane at which all incoming, parallel light rays converge (assuming a radially symmetric lens). - in the pinhole model, `(f_x, f_y)` is described as "focal length", but the units are in pixels and the interpretation is different. The relationship between `(f_x, f_y)` and the physical focal length `F` is `f_i = F * s_i`, where `(s_x, s_y)` are the number of pixels per meter in the x- and y-directions (of the image). Both values described as "focal length" have analogous effects on field of view and scale of objects in the image. - __frame__: (Also "pose") an origin point and a space-spanning basis in 2D/3D, as in @ref multibody_frames_and_bodies. - Incidentally, the word "frame" is also used in conjunction with a single image in a video (such as a "video frame"). Drake doesn't use this sense in discussing cameras (unless explicitly noted). - __image__: an array of measurements such that the measured values have spatial relationships based on where they are in the array. - __image frame__: the 2D frame embedded in 3D space spanning the image plane. The image frame's x- and y-axes are parallel with `Cx` and `Cy`, respectively. Coordinates are expressed as the pair `(u, v)` and the camera's image lies on the plane spanned by the frame's basis. The _center_ of the pixel in the first row and first column is at `(u=0, v=0)`. - __image plane__: a plane in 3D which is perpendicular to the camera's viewing direction. Conceptually, the image lies on this plane. - In a physical pinhole camera, the aperture is between the image plane and the environment being imaged. - In the pinhole model, the image plane lies between the environment and aperture (i.e., in the positive Cz direction from Co). - __imager__: a sensor whose measurements are reported in images. - __principal point__: The projection of the camera origin, `Co`, on the image plane. Its value is measured from the image's origin in pixels. - __sensor__: a measurement device. - __viewing direction__: the direction the camera is facing. Defined as being parallel with Cz. */ class CameraInfo final { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(CameraInfo) /** Constructor that directly sets the image size, principal point, and focal lengths. @param width The image width in pixels, must be positive. @param height The image height in pixels, must be positive. @param focal_x The _model_ "focal length" x in pixels (see above), must be positive and finite. @param focal_y The _model_ "focal length" y in pixels (see above), must be positive and finite. @param center_x The x coordinate of the principal point in pixels (see above), must lie in the range 0 < center_x < width. @param center_y The y coordinate of the principal point in pixels (see above), must lie in the range 0 < center_y < height. @throws std::exception if the provided values don't satisfy the listed requirements. */ CameraInfo(int width, int height, double focal_x, double focal_y, double center_x, double center_y); /** Constructs this instance by extracting focal_x, focal_y, center_x, and center_y from the provided intrinsic_matrix. @param width The image width in pixels, must be positive. @param height The image height in pixels, must be positive. @param intrinsic_matrix The intrinsic matrix (K) as documented above. Where K is defined to be non-zero, the values must be finite and the focal length values must be positive. @throws std::exception if intrinsic_matrix is not of the form indicated above for the pinhole camera model (representing an affine / homogeneous transform) or the non-zero values don't meet the documented requirements. */ CameraInfo(int width, int height, const Eigen::Matrix3d& intrinsic_matrix); /** Constructs this instance from image size and vertical field of view. We assume the principal point is in the center of the image; `(center x, center_y)` is equal to `(width / 2.0 - 0.5, height / 2.0 - 0.5)`. We also assume the focal lengths `focal_x` and `focal_y` are identical (modeling a radially symmetric lens). The value is derived from field of view and image size as: focal_x = focal_y = height * 0.5 / tan(0.5 * fov_y) @param width The image width in pixels, must be positive. @param height The image height in pixels, must be positive. @param fov_y The vertical field of view in radians, must be positive and finite. @throws std::exception if the provided values don't satisfy the listed requirements. */ CameraInfo(int width, int height, double fov_y); /** Returns the width of the image in pixels. */ int width() const { return width_; } /** Returns the height of the image in pixels. */ int height() const { return height_; } /** Returns the focal length x in pixels. */ double focal_x() const { return intrinsic_matrix_(0, 0); } /** Returns the focal length y in pixels. */ double focal_y() const { return intrinsic_matrix_(1, 1); } /** Returns the field of view in the x-direction (in radians). */ double fov_x() const { return 2 * std::atan(width_ / (2 * focal_x())); } /** Returns the field of view in the y-direction (in radians). */ double fov_y() const { return 2 * std::atan(height_ / (2 * focal_y())); } // TODO(eric.cousineau): Deprecate "center_{x,y}" and use // "principal_point_{x,y}" or "pp{x,y}". /** Returns the principal point's x coordinate in pixels. */ double center_x() const { return intrinsic_matrix_(0, 2); } /** Returns the principal point's y coordinate in pixels. */ double center_y() const { return intrinsic_matrix_(1, 2); } /** Returns the camera intrinsic matrix, K. */ const Eigen::Matrix3d& intrinsic_matrix() const { return intrinsic_matrix_; } private: int width_{}; int height_{}; // Camera intrinsic parameter matrix. For the detail, see // http://docs.opencv.org/2.4/modules/calib3d/doc/ // camera_calibration_and_3d_reconstruction.html Eigen::Matrix3d intrinsic_matrix_; }; } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/image_io.h
#pragma once #include <cstdint> #include <filesystem> #include <optional> #include <variant> #include <vector> #include "drake/common/diagnostic_policy.h" #include "drake/common/drake_copyable.h" #include "drake/common/name_value.h" #include "drake/systems/sensors/image.h" #include "drake/systems/sensors/image_file_format.h" namespace drake { namespace systems { namespace sensors { /** Utility functions for reading and writing images, from/to either files or memory buffers. The only file formats supported are JPEG, PNG, and TIFF. The only format that supports floating-point scalars (e.g., ImageDepth32F) is TIFF. Trying to load or save a floating-point image from/to a PNG or JPEG file will throw an exception. */ class ImageIo { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ImageIo); /** Some characteristics of an image file. Note that Drake's Image<> class can only express `depth == 1`. */ struct Metadata { /** Passes this object to an Archive. Refer to @ref yaml_serialization "YAML Serialization" for background. */ template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(format)); a->Visit(DRAKE_NVP(width)); a->Visit(DRAKE_NVP(height)); a->Visit(DRAKE_NVP(depth)); a->Visit(DRAKE_NVP(channels)); a->Visit(DRAKE_NVP(scalar)); } ImageFileFormat format{ImageFileFormat::kJpeg}; int width{}; int height{}; int depth{}; int channels{}; PixelScalar scalar{PixelScalar::k8U}; }; /** When loading from memory, this struct denotes a span of raw bytes as input. */ struct ByteSpan { /** Pointer to the first byte of the span. */ const void* data{}; /** Total number of bytes in the span. */ size_t size{}; }; /** Default constructor. */ ImageIo() = default; /** Returns the metadata of the given image file, or nullopt if the metadata cannot be determined or is unsupported. The filename extension has no bearing on the result; only the actual file contents determine the file format. */ std::optional<Metadata> LoadMetadata( const std::filesystem::path& path) const { return LoadMetadataImpl(&path); } /** Returns the metadata of the given image buffer, or nullopt if the metadata cannot be determined or is unsupported. */ std::optional<Metadata> LoadMetadata(ByteSpan buffer) const { return LoadMetadataImpl(buffer); } /** Loads and returns an image from disk. @param format (Optionally) establishes the required image file format. When set, images that are a different file format will throw an exception. When not set, the filename extension has no bearing on the result; only the actual file contents determine the file format. @throws std::exception for any kind of error loading the image file. */ ImageAny Load(const std::filesystem::path& path, std::optional<ImageFileFormat> format = std::nullopt) const { return LoadImpl(&path, format); } /** Loads and returns an image from a memory buffer. @param format (Optionally) establishes the required image file format. When set, images that are a different file format will throw an exception. @throws std::exception for any kind of error loading the image data. */ ImageAny Load(ByteSpan buffer, std::optional<ImageFileFormat> format = std::nullopt) const { return LoadImpl(buffer, format); } /** Loads and outputs an image from disk. The filename extension has no bearing on the result; only the actual file contents determine the file format. @param[out] image The output image (which will be overwritten). @throws std::exception for any kind of error loading the image file. @throws std::exception if the loaded image does not match the kPixelType. @exclude_from_pydrake_mkdoc{This overload is not bound in pydrake.} */ template <PixelType kPixelType> void Load(const std::filesystem::path& path, Image<kPixelType>* image) const { LoadImpl(&path, std::nullopt, image); } /** Loads and outputs an image from disk. @param format Establishes the required image file format; images that are a different file format will throw an exception. @param[out] image The output image (which will be overwritten). @throws std::exception for any kind of error loading the image file. @throws std::exception if the loaded image does not match the kPixelType. @exclude_from_pydrake_mkdoc{This overload is not bound in pydrake.} */ template <PixelType kPixelType> void Load(const std::filesystem::path& path, ImageFileFormat format, Image<kPixelType>* image) const { LoadImpl(&path, format, image); } /** Loads and outputs an image from a memory buffer. @param[out] image The output image (which will be overwritten). @throws std::exception for any kind of error loading the image data. @throws std::exception if the loaded image does not match the kPixelType. @exclude_from_pydrake_mkdoc{This overload is not bound in pydrake.} */ template <PixelType kPixelType> void Load(ByteSpan buffer, Image<kPixelType>* image) const { LoadImpl(buffer, std::nullopt, image); } /** Loads and outputs an image from a memory buffer. @param format Establishes the required image file format; images that are a different file format will throw an exception. @param[out] image The output image (which will be overwritten). @throws std::exception for any kind of error loading the image data. @throws std::exception if the loaded image does not match the kPixelType. @exclude_from_pydrake_mkdoc{This overload is not bound in pydrake.} */ template <PixelType kPixelType> void Load(ByteSpan buffer, ImageFileFormat format, Image<kPixelType>* image) const { LoadImpl(buffer, format, image); } /** Saves an image to disk. @param format (Optionally) chooses the image file format. When not set, the filename extension will determine the format and the extension must be a supported choice (i.e., `.jpg`, `.jpeg`, `.png`, `.tif`, or `.tiff`). @throws std::exception for any kind of error saving the image file. */ template <PixelType kPixelType> void Save(const Image<kPixelType>& image, const std::filesystem::path& path, std::optional<ImageFileFormat> format = std::nullopt) const { SaveImpl(&image, format, &path); } /** Saves an image to a new memory buffer, returning the buffer. @throws std::exception for any kind of error saving the image data. */ template <PixelType kPixelType> std::vector<uint8_t> Save(const Image<kPixelType>& image, ImageFileFormat format) const { std::vector<uint8_t> result; SaveImpl(&image, format, &result); return result; } /** Saves an image to an existing memory buffer. @param[out] buffer The output buffer (which will be overwritten). @throws std::exception for any kind of error saving the image data. @exclude_from_pydrake_mkdoc{This overload is not bound in pydrake.} */ template <PixelType kPixelType> void Save(const Image<kPixelType>& image, ImageFileFormat format, std::vector<uint8_t>* buffer) const { SaveImpl(&image, format, buffer); } private: // ImageAnyConstPtr is like ImageAny but with `const Image<kPixelType>*` // passed by const pointer instead of a `Image<kPixelType>` (by value). template <typename...> struct variant_add_const_pointer; template <typename... Types> struct variant_add_const_pointer<std::variant<Types...>> { using type = std::variant<std::add_pointer_t<std::add_const_t<Types>>...>; }; using ImageAnyConstPtr = variant_add_const_pointer<ImageAny>::type; // ImageAnyMutablePtr is like ImageAny but with `Image<kPixelType>*` // passed by mutable pointer instead of `Image<kPixelType>` (by value). template <typename...> struct variant_add_pointer; template <typename... Types> struct variant_add_pointer<std::variant<Types...>> { using type = std::variant<std::add_pointer_t<Types>...>; }; using ImageAnyMutablePtr = variant_add_pointer<ImageAny>::type; // File input is either a filename or a read-only memory buffer. using InputAny = std::variant<const std::filesystem::path*, ByteSpan>; // File output is either a filename or a growable memory buffer. using OutputAny = std::variant<const std::filesystem::path*, std::vector<uint8_t>*>; // Implementation functions for the public API. std::optional<Metadata> LoadMetadataImpl(InputAny input_any) const; ImageAny LoadImpl(InputAny input_any, std::optional<ImageFileFormat> format) const; void LoadImpl(InputAny input_any, std::optional<ImageFileFormat> format, ImageAnyMutablePtr image_any) const; void SaveImpl(ImageAnyConstPtr image_any, std::optional<ImageFileFormat> format, OutputAny output_any) const; // Helpers. struct LoaderTools; LoaderTools MakeLoaderTools(InputAny input_any, std::optional<ImageFileFormat> format) const; void FlushDiagnostics(const LoaderTools& tools) const; // TODO(jwnimmer-tri) Expose this so that Drake-internal callers can customize // their error handling. drake::internal::DiagnosticPolicy diagnostic_; }; } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/beam_model_params.cc
#include "drake/systems/sensors/beam_model_params.h" namespace drake { namespace systems { namespace sensors { const int BeamModelParamsIndices::kNumCoordinates; const int BeamModelParamsIndices::kLambdaShort; const int BeamModelParamsIndices::kSigmaHit; const int BeamModelParamsIndices::kProbabilityShort; const int BeamModelParamsIndices::kProbabilityMiss; const int BeamModelParamsIndices::kProbabilityUniform; const std::vector<std::string>& BeamModelParamsIndices::GetCoordinateNames() { static const drake::never_destroyed<std::vector<std::string>> coordinates( std::vector<std::string>{ "lambda_short", "sigma_hit", "probability_short", "probability_miss", "probability_uniform", }); return coordinates.access(); } } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/camera_info.cc
#include "drake/systems/sensors/camera_info.h" #include <cmath> #include <sstream> #include <string> #include "drake/common/drake_assert.h" #include "drake/common/fmt_eigen.h" namespace drake { namespace systems { namespace sensors { namespace { constexpr char kPrefix[] = "\n "; template <typename T> void FormatNVP(const char* name, T value, std::stringstream* s) { (*s) << kPrefix << name << " (" << value << ")"; } void CheckPositive(const char* name, int value, std::stringstream* s) { if (value <= 0) { FormatNVP(name, value, s); (*s) << " should be positive."; } } void CheckBetweenZeroAndMax(const char* name, double value, int max, std::stringstream* s) { if (value <= 0 || value >= static_cast<double>(max)) { FormatNVP(name, value, s); (*s) << " should lie in the range (0, " << max << ")."; } } void CheckPositiveFinite(const char* name, double value, std::stringstream* s) { if (value <= 0 || !std::isfinite(value)) { FormatNVP(name, value, s); (*s) << " should be a positive, finite number."; } } } // namespace CameraInfo::CameraInfo(int width, int height, double focal_x, double focal_y, double center_x, double center_y) : CameraInfo(width, height, // clang-format off (Eigen::Matrix3d() << focal_x, 0.0, center_x, 0.0, focal_y, center_y, 0.0, 0.0, 1.0).finished() // clang-format on ) {} CameraInfo::CameraInfo(int width, int height, const Eigen::Matrix3d& intrinsic_matrix) : width_(width), height_(height), intrinsic_matrix_(intrinsic_matrix) { std::stringstream errors; CheckPositive("Width", width, &errors); CheckPositive("Height", height, &errors); const Eigen::Matrix3d& K = intrinsic_matrix; CheckPositiveFinite("Focal X", K(0, 0), &errors); CheckPositiveFinite("Focal Y", K(1, 1), &errors); CheckBetweenZeroAndMax("Center X", K(0, 2), width, &errors); CheckBetweenZeroAndMax("Center Y", K(1, 2), height, &errors); // Off-diagonal terms should be zero and homogeneous row should be [0, 0, 1]. // TODO(eric.cousineau): Relax this with a tolerance? if (K(0, 1) != 0 || K(1, 0) != 0 || K(2, 0) != 0 || K(2, 1) != 0 || K(2, 2) != 1) { errors << kPrefix << "The camera's intrinsic matrix is malformed:\n" << fmt::to_string(fmt_eigen(K)); } const std::string error_message = errors.str(); if (!error_message.empty()) { throw std::runtime_error("Invalid camera configuration: " + error_message); } } CameraInfo::CameraInfo(int width, int height, double vertical_fov_rad) : CameraInfo(width, height, // BR height * 0.5 / std::tan(0.5 * vertical_fov_rad), height * 0.5 / std::tan(0.5 * vertical_fov_rad), width * 0.5 - 0.5, height * 0.5 - 0.5) {} // TODO(SeanCurtis-TRI): The shift of the principal point by (-0.5, -0.5) is // overly opaque. The primary explanation comes from pixel addressing // conventions used in various APIs (see // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_fragment_coord_conventions.txt // However, we don't want to look like this class is coupled with OpenGL. How // do we articulate this math in a way that *doesn't* depend on OpenGL? See // https://github.com/SeanCurtis-TRI/drake/pull/5#pullrequestreview-264447958. } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/beam_model.h
#pragma once #include "drake/common/drake_copyable.h" #include "drake/systems/framework/leaf_system.h" #include "drake/systems/sensors/beam_model_params.h" namespace drake { namespace systems { namespace sensors { // TODO(russt): Add support for symbolic. /// Implements the "Beam Models of Range Finders" from section 6.3 of /// Probabilistic Robotics (2006), by Thrun, Burgard, and Fox /// /// This system takes a depth measurement signal as input, and outputs a noisy /// measurement version of that signal, with some probability of returning the /// true measurement with Gaussian noise, but also with some probability of /// occlusions (short returns), of missed detections (returning the max depth), /// and of returning just a (uniform) random measurement. /// /// Four additional input ports (each of the same dimension as the depth /// signal) are provided for the random inputs: One for determining which of /// the events occurred (true + noise, short return, max return, or uniform /// return), and one each for modeling the distribution of short true but noisy /// returns, short returns, and uniform returns). /// /// We deviate from the textbook model in one respect: both here and in the /// textbook, the distribution over short returns and the distribution over /// getting a noisy version of the true return (aka a "hit") are truncated. The /// short returns are from an exponential distribution but truncated to be less /// than the input depth, and "hits" are drawn from a Gaussian centered at the /// input depth but truncated at the maximum range of the sensor. In the book, /// these distributions are normalized so that the total probability of getting /// a short return and/or hit stays constant (independent of the input depth). /// Here we do not normalize, so that the probability of getting a short return /// decreases as the input depth is smaller (there is a modeled obstacle closer /// to the robot), and the tails of the "hit" distribution simply cause more max /// returns as the input depth gets closer to the max range. This was done both /// because it is arguably a better model and because it keeps the code much /// simpler (to allow AutoDiff and Symbolic) given the modeling framework we /// have here that builds the output out of simple (non-truncated) random /// variable inputs. /// /// @system /// name: BeamModel /// input_ports: /// - depth /// - event /// - hit /// - short /// - uniform /// output_ports: /// - depth /// @endsystem /// /// It is convenient to use `systems::AddRandomInputs()` to supply all the /// random input signals: /// @code /// DiagramBuilder<double> builder; /// auto beam_model = builder.AddSystem<BeamModel>(1, 5.0); /// builder.ExportInput(beam_model->get_depth_input_port(), "depth"); /// builder.ExportOutput(beam_model->get_output_port(0), "depth"); /// AddRandomInputs(0.01, &builder); /// auto diagram = builder.Build(); /// @endcode /// /// @tparam_nonsymbolic_scalar /// @ingroup sensor_systems template <typename T> class BeamModel final : public LeafSystem<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(BeamModel) BeamModel(int num_depth_readings, double max_range); /// Scalar-converting copy constructor. See @ref system_scalar_conversion. template <typename U> explicit BeamModel(const BeamModel<U>&); const InputPort<T>& get_depth_input_port() const { return this->get_input_port(0); } const InputPort<T>& get_event_random_input_port() const { return this->get_input_port(1); } const InputPort<T>& get_hit_random_input_port() const { return this->get_input_port(2); } const InputPort<T>& get_short_random_input_port() const { return this->get_input_port(3); } const InputPort<T>& get_uniform_random_input_port() const { return this->get_input_port(4); } BeamModelParams<T>& get_mutable_parameters(Context<T>* context) const; double max_range() const { return max_range_; } private: void CalcOutput(const Context<T>& context, BasicVector<T>* output) const; const double max_range_{1.0}; }; } // namespace sensors // Explicitly disable symbolic::Expression (for now). namespace scalar_conversion { template <> struct Traits<sensors::BeamModel> : public NonSymbolicTraits {}; } // namespace scalar_conversion } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/rgbd_sensor.h
#pragma once #include "drake/common/drake_copyable.h" #include "drake/geometry/geometry_ids.h" #include "drake/geometry/query_object.h" #include "drake/geometry/render/render_camera.h" #include "drake/math/rigid_transform.h" #include "drake/systems/framework/leaf_system.h" #include "drake/systems/sensors/camera_info.h" #include "drake/systems/sensors/image.h" namespace drake { namespace systems { namespace sensors { /** A meta-sensor that houses RGB, depth, and label cameras, producing their corresponding images based on the contents of the geometry::SceneGraph. @system name: RgbdSensor input_ports: - geometry_query output_ports: - color_image - depth_image_32f - depth_image_16u - label_image - body_pose_in_world - image_time @endsystem This system models a continuous sensor, where the output ports reflect the instantaneous images observed by the sensor. In contrast, a discrete (sample and hold) sensor model might be a more suitable match for a real-world camera; for that case, see RgbdSensorDiscrete or RgbdSensorAsync. The following text uses terminology and conventions from CameraInfo. Please review its documentation. This class uses the following frames: - W - world frame - C - color camera frame, used for both color and label cameras to guarantee perfect registration between color and label images. - D - depth camera frame - B - sensor body frame. Approximately, the frame of the "physical" sensor that contains the color, depth, and label cameras. The contained cameras are rigidly fixed to B and X_WB is what is used to pose the sensor in the world (or, alternatively, X_PB where P is some parent frame for which X_WP is known). By default, frames B, C, and D are coincident and aligned. These can be changed using the `camera_poses` constructor parameter. Frames C and D are always rigidly affixed to the sensor body frame B. As documented in the @ref camera_axes_in_image "CameraInfo documentation", the color and depth cameras "look" in the positive Cz and Dz directions, respectively with the positive Cy and Dy directions pointing to the bottom of the image. If R_BC and R_BD are the identity rotation, we can apply the same reasoning to the body frame: look in the +Bz direction with the +By direction pointing down in the image. Only if the depth or color frames are re-oriented relative to the body does further reasoning need to be applied. Output port image formats: - color_image: Four channels, each channel uint8_t, in the following order: red, green, blue, and alpha. - depth_image_32f: One channel, float, representing the Z value in `D` in *meters*. The values 0 and infinity are reserved for out-of-range depth returns (too close or too far, respectively, as defined by @ref geometry::render::DepthRenderCamera "DepthRenderCamera"). - depth_image_16u: One channel, uint16_t, representing the Z value in `D` in *millimeters*. The values 0 and 65535 are reserved for out-of-range depth returns (too close or too far, respectively, as defined by @ref geometry::render::DepthRenderCamera "DepthRenderCamera"). Additionally, 65535 will also be returned if the depth measurement exceeds the representation range of uint16_t. Thus, the maximum valid depth return is 65534mm. - label_image: One channel, int16_t, whose value is a unique @ref geometry::render::RenderLabel "RenderLabel" value aligned with the color camera frame. See @ref geometry::render::RenderLabel "RenderLabel" for discussion of interpreting rendered labels. @note These depth sensor measurements differ from those of range data used by laser range finders (like DepthSensor), where the depth value represents the distance from the sensor origin to the object's surface. @ingroup sensor_systems */ class RgbdSensor final : public LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(RgbdSensor) /** Constructs an %RgbdSensor with fully specified render camera models for both color/label and depth cameras. @pydrake_mkdoc_identifier{individual_intrinsics} */ RgbdSensor(geometry::FrameId parent_id, const math::RigidTransformd& X_PB, geometry::render::ColorRenderCamera color_camera, geometry::render::DepthRenderCamera depth_camera); /** Constructs an %RgbdSensor with fully specified render camera models for both the depth camera. The color camera in inferred from the `depth_camera`; it shares the same geometry::render::RenderCameraCore and is configured to show the window based on the value of `show_color_window`. @pydrake_mkdoc_identifier{combined_intrinsics} */ RgbdSensor(geometry::FrameId parent_id, const math::RigidTransformd& X_PB, const geometry::render::DepthRenderCamera& depth_camera, bool show_color_window = false); ~RgbdSensor() = default; // TODO(eric.cousineau): Expose which renderer color / depth uses? // TODO(SeanCurtis-TRI): Deprecate this in favor of the color render camera. /** Returns the intrinsics properties of the color camera model. */ const CameraInfo& color_camera_info() const { return color_camera_.core().intrinsics(); } // TODO(SeanCurtis-TRI): Deprecate this in favor of the depth render camera. /** Returns the intrinsics properties of the depth camera model. */ const CameraInfo& depth_camera_info() const { return depth_camera_.core().intrinsics(); } /** Returns the render camera for color/label renderings. */ const geometry::render::ColorRenderCamera& color_render_camera() const { return color_camera_; } /** Returns the render camera for depth renderings. */ const geometry::render::DepthRenderCamera& depth_render_camera() const { return depth_camera_; } /** Returns `X_BC`. */ const math::RigidTransformd& X_BC() const { return color_camera_.core().sensor_pose_in_camera_body(); } /** Returns `X_BD`. */ const math::RigidTransformd& X_BD() const { return depth_camera_.core().sensor_pose_in_camera_body(); } /** Returns the id of the frame to which the body is affixed. */ geometry::FrameId parent_frame_id() const { return parent_frame_id_; } /** Returns the geometry::QueryObject<double>-valued input port. */ const InputPort<double>& query_object_input_port() const; /** Returns the abstract-valued output port that contains an ImageRgba8U. */ const OutputPort<double>& color_image_output_port() const; /** Returns the abstract-valued output port that contains an ImageDepth32F. */ const OutputPort<double>& depth_image_32F_output_port() const; /** Returns the abstract-valued output port that contains an ImageDepth16U. */ const OutputPort<double>& depth_image_16U_output_port() const; /** Returns the abstract-valued output port that contains an ImageLabel16I. */ const OutputPort<double>& label_image_output_port() const; /** Returns the abstract-valued output port (containing a RigidTransform) which reports the pose of the body in the world frame (X_WB). */ const OutputPort<double>& body_pose_in_world_output_port() const; /** Returns the vector-valued output port (with size == 1) that reports the current simulation time, in seconds. This is provided for consistency with RgbdSensorDiscrete and RgbdSensorAsync (where the image time is not always the current time). */ const OutputPort<double>& image_time_output_port() const; private: // The calculator methods for the four output ports. void CalcColorImage(const Context<double>& context, ImageRgba8U* color_image) const; void CalcDepthImage32F(const Context<double>& context, ImageDepth32F* depth_image) const; void CalcDepthImage16U(const Context<double>& context, ImageDepth16U* depth_image) const; void CalcLabelImage(const Context<double>& context, ImageLabel16I* label_image) const; void CalcX_WB(const Context<double>& context, math::RigidTransformd* X_WB) const; void CalcImageTime(const Context<double>&, BasicVector<double>*) const; // Extract the query object from the given context (via the appropriate input // port. const geometry::QueryObject<double>& get_query_object( const Context<double>& context) const { return query_object_input_port().Eval<geometry::QueryObject<double>>( context); } const InputPort<double>* query_object_input_port_{}; const OutputPort<double>* color_image_port_{}; const OutputPort<double>* depth_image_32F_port_{}; const OutputPort<double>* depth_image_16U_port_{}; const OutputPort<double>* label_image_port_{}; const OutputPort<double>* body_pose_in_world_output_port_{}; const OutputPort<double>* image_time_output_port_{}; // The identifier for the parent frame `P`. const geometry::FrameId parent_frame_id_; // The camera specifications for color/label and depth. const geometry::render::ColorRenderCamera color_camera_; const geometry::render::DepthRenderCamera depth_camera_; // The position of the camera's B frame relative to its parent frame P. const math::RigidTransformd X_PB_; }; } // namespace sensors } // namespace systems } // namespace drake // This exists for backwards compatibility reasons. The discrete sensor class // was previously defined within this file. #include "drake/systems/sensors/rgbd_sensor_discrete.h"
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/gyroscope.cc
#include "drake/systems/sensors/gyroscope.h" #include "drake/multibody/math/spatial_algebra.h" namespace drake { namespace systems { namespace sensors { using math::RigidTransform; using multibody::SpatialVelocity; template <typename T> Gyroscope<T>::Gyroscope(const multibody::RigidBody<T>& body, const RigidTransform<double>& X_BS) : Gyroscope(body.index(), X_BS) {} template <typename T> Gyroscope<T>::Gyroscope(const multibody::BodyIndex& body_index, const RigidTransform<double>& X_BS) : LeafSystem<T>(SystemTypeTag<Gyroscope>{}), body_index_(body_index), X_BS_(X_BS) { // Declare measurement output port. measurement_output_port_ = &this->DeclareVectorOutputPort( "measurement", 3, &Gyroscope<T>::CalcOutput); body_poses_input_port_ = &this->DeclareAbstractInputPort( "body_poses", Value<std::vector<RigidTransform<T>>>()); body_velocities_input_port_ = &this->DeclareAbstractInputPort( "body_spatial_velocities", Value<std::vector<SpatialVelocity<T>>>()); } template <typename T> void Gyroscope<T>::CalcOutput(const Context<T>& context, BasicVector<T>* output) const { const auto& X_WB = get_body_poses_input_port().template Eval<std::vector<RigidTransform<T>>>( context)[body_index_]; const auto& V_WB = get_body_velocities_input_port() .template Eval<std::vector<SpatialVelocity<T>>>(context)[body_index_]; // Calculate rotation from world to gyroscope: R_SW = R_SB * R_BW. const auto R_SB = X_BS_.rotation().matrix().template cast<T>().transpose(); const auto R_BW = X_WB.rotation().matrix().transpose(); const auto R_SW = R_SB * R_BW; // Re-express in local frame and return. output->SetFromVector(R_SW * V_WB.rotational()); } template <typename T> const Gyroscope<T>& Gyroscope<T>::AddToDiagram( const multibody::RigidBody<T>& body, const RigidTransform<double>& X_BS, const multibody::MultibodyPlant<T>& plant, DiagramBuilder<T>* builder) { const auto& gyroscope = *builder->template AddSystem<Gyroscope<T>>(body, X_BS); builder->Connect(plant.get_body_poses_output_port(), gyroscope.get_body_poses_input_port()); builder->Connect(plant.get_body_spatial_velocities_output_port(), gyroscope.get_body_velocities_input_port()); return gyroscope; } template <typename T> template <typename U> Gyroscope<T>::Gyroscope(const Gyroscope<U>& other) : Gyroscope(other.body_index(), other.pose()) {} DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::sensors::Gyroscope) } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/sensors/image_file_format.h
#pragma once #include <string> #include "drake/common/fmt.h" namespace drake { namespace systems { namespace sensors { /** The image file formats known to Drake. */ enum class ImageFileFormat { /** mime-type: image/jpeg. */ kJpeg, /** mime-type: image/png. */ kPng, /** mime-type: image/tiff. */ kTiff, }; std::string to_string(ImageFileFormat); } // namespace sensors } // namespace systems } // namespace drake DRAKE_FORMATTER_AS(, drake::systems::sensors, ImageFileFormat, x, drake::systems::sensors::to_string(x))
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/gen/beam_model_params.h
#pragma once #include "drake/systems/sensors/beam_model_params.h" // clang-format off // NOLINTNEXTLINE #warning "DRAKE_DEPRECATED: This include path is deprecated and will be removed on or after 2024-09-01. Remove the /gen/ part of your code's include statement." // clang-format on
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test_utilities/BUILD.bazel
load("//tools/lint:lint.bzl", "add_lint_tests") load( "//tools/skylark:drake_cc.bzl", "drake_cc_library", "drake_cc_package_library", ) package(default_visibility = ["//visibility:public"]) drake_cc_package_library( name = "test_utilities", testonly = 1, visibility = ["//visibility:public"], deps = [ ":image_compare", ], ) drake_cc_library( name = "image_compare", testonly = 1, srcs = ["image_compare.cc"], hdrs = ["image_compare.h"], deps = [ "//systems/sensors:image", "@gtest//:without_main", "@vtk_internal//:vtkCommonCore", "@vtk_internal//:vtkIOImage", ], ) add_lint_tests()
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test_utilities/image_compare.h
#pragma once #include <filesystem> #include <ostream> #include <gtest/gtest.h> #include "drake/systems/sensors/image.h" namespace drake { namespace systems { namespace sensors { /** Adds googletest support for printing EXPECT_EQ(Image, Image) failures. Small images print all pixel data. Large images only print a summary. */ template <PixelType kPixelType> void PrintTo(const Image<kPixelType>& image, std::ostream* os); /** Loads the PNG or TIFF image from `filename` into the `image` output. */ template <PixelType kPixelType> ::testing::AssertionResult LoadImage(const std::filesystem::path& filename, Image<kPixelType>* image); // TODO(jwnimmer-tri) Add a helper function to stash an image into the // $TEST_UNDECLARED_OUTPUTS_DIR for offline inspection. } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test_utilities/image_compare.cc
#include "drake/systems/sensors/test_utilities/image_compare.h" #include <string> // To ease build system upkeep, we annotate VTK includes with their deps. #include <vtkImageExport.h> // vtkIOImage #include <vtkNew.h> // vtkCommonCore #include <vtkPNGReader.h> // vtkIOImage #include <vtkSmartPointer.h> // vtkCommonCore #include <vtkTIFFReader.h> // vtkIOImage namespace drake { namespace systems { namespace sensors { namespace fs = std::filesystem; using ::testing::AssertionFailure; using ::testing::AssertionResult; using ::testing::AssertionSuccess; template <PixelType kPixelType> void PrintTo(const Image<kPixelType>& image, std::ostream* os) { const int width = image.width(); const int height = image.height(); fmt::print(*os, "Image<k{}>(width={}, height={})", kPixelType, width, height); const int size = width * height; // When there are no pixels, don't bother printing the "Channel ..." titles. // If there are way too many pixels (more than fit on one screen), omit all // pixel data, leaving only the summary of the size. if (size == 0 || size > 1000) { return; } using T = typename Image<kPixelType>::T; using Promoted = std::conditional_t<std::is_integral_v<T>, int, T>; constexpr int num_channels = Image<kPixelType>::kNumChannels; for (int c = 0; c < num_channels; ++c) { *os << "\n"; const T* const base = image.at(0, 0) + c; using Stride = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>; Eigen::Map<const MatrixX<T>, 0, Stride> eigen( base, height, width, Stride(num_channels, width * num_channels)); if (num_channels > 1) { fmt::print(*os, "Channel {}:\n", c); } fmt::print(*os, "{}", fmt_eigen(eigen.template cast<Promoted>())); } } template <PixelType kPixelType> AssertionResult LoadImage(const fs::path& filename, Image<kPixelType>* image) { if (!fs::exists(filename)) { return AssertionFailure() << "File not found: " << filename; } vtkSmartPointer<vtkImageReader2> reader; switch (kPixelType) { case PixelType::kRgba8U: case PixelType::kGrey8U: case PixelType::kDepth16U: case PixelType::kLabel16I: reader = vtkSmartPointer<vtkPNGReader>::New(); break; case PixelType::kDepth32F: reader = vtkSmartPointer<vtkTIFFReader>::New(); break; default: // TODO(jwnimmer-tri) Add support for more pixel types. return AssertionFailure() << "Called with unsupported PixelType"; } reader->SetFileName(filename.string().c_str()); vtkNew<vtkImageExport> exporter; exporter->ImageLowerLeftOff(); exporter->SetInputConnection(reader->GetOutputPort()); exporter->Update(); const int* const dims = exporter->GetDataDimensions(); const int width = dims[0]; const int height = dims[1]; const int depth = dims[2]; const int channels = exporter->GetDataNumberOfScalarComponents(); if (depth != 1) { // Drake's Image<> class only supports a shape of (width, height). It can't // denote a 3D image (width, height, depth). return AssertionFailure() << "Found wrong depth=" << depth; } if (channels != ImageTraits<kPixelType>::kNumChannels) { return AssertionFailure() << "Found wrong channels=" << channels; } image->resize(width, height); exporter->Export(image->at(0, 0)); return AssertionSuccess(); } // Explicit template instantiations. // clang-format off static constexpr auto kInstantiations __attribute__((used)) = std::make_tuple( &PrintTo<PixelType::kRgb8U>, &PrintTo<PixelType::kBgr8U>, &PrintTo<PixelType::kRgba8U>, &PrintTo<PixelType::kBgra8U>, &PrintTo<PixelType::kGrey8U>, &PrintTo<PixelType::kDepth16U>, &PrintTo<PixelType::kDepth32F>, &PrintTo<PixelType::kLabel16I>, &LoadImage<PixelType::kRgb8U>, &LoadImage<PixelType::kBgr8U>, &LoadImage<PixelType::kRgba8U>, &LoadImage<PixelType::kBgra8U>, &LoadImage<PixelType::kGrey8U>, &LoadImage<PixelType::kDepth16U>, &LoadImage<PixelType::kDepth32F>, &LoadImage<PixelType::kLabel16I> ); // clang-format on } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/beam_model_test.cc
#include "drake/systems/sensors/beam_model.h" #include <gtest/gtest.h> #include "drake/common/proto/call_python.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/diagram.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/framework/test_utilities/scalar_conversion.h" #include "drake/systems/primitives/constant_vector_source.h" #include "drake/systems/primitives/random_source.h" #include "drake/systems/primitives/vector_log_sink.h" #include "drake/systems/sensors/beam_model_params.h" namespace drake { namespace systems { namespace sensors { namespace { GTEST_TEST(BeamModelTest, TestInputPorts) { const int kNumReadings = 10; const double kMaxRange = 5.0; BeamModel<double> model(kNumReadings, kMaxRange); EXPECT_EQ(model.get_depth_input_port().size(), kNumReadings); EXPECT_FALSE(model.get_depth_input_port().is_random()); EXPECT_EQ(model.get_event_random_input_port().size(), kNumReadings); EXPECT_EQ(model.get_event_random_input_port().get_random_type().value(), RandomDistribution::kUniform); EXPECT_EQ(model.get_hit_random_input_port().size(), kNumReadings); EXPECT_EQ(model.get_hit_random_input_port().get_random_type().value(), RandomDistribution::kGaussian); EXPECT_EQ(model.get_short_random_input_port().size(), kNumReadings); EXPECT_EQ(model.get_short_random_input_port().get_random_type().value(), RandomDistribution::kExponential); EXPECT_EQ(model.get_uniform_random_input_port().size(), kNumReadings); EXPECT_EQ(model.get_uniform_random_input_port().get_random_type().value(), RandomDistribution::kUniform); } // Compare random samples to an analytic form of the probability density // function. GTEST_TEST(BeamModelTest, TestProbabilityDensity) { systems::DiagramBuilder<double> builder; const double kDepthInput = 3.0; const double kMaxRange = 5.0; auto beam_model = builder.AddSystem<BeamModel>(1, kMaxRange); auto constant_depth = builder.AddSystem<ConstantVectorSource>(Vector1d(kDepthInput)); builder.Connect(constant_depth->get_output_port(), beam_model->get_depth_input_port()); auto w_event = builder.AddSystem<RandomSource<double>>( RandomDistribution::kUniform, 1, 0.0025); builder.Connect(w_event->get_output_port(0), beam_model->get_event_random_input_port()); auto w_hit = builder.AddSystem<RandomSource<double>>( RandomDistribution::kGaussian, 1, 0.0025); builder.Connect(w_hit->get_output_port(0), beam_model->get_hit_random_input_port()); auto w_short = builder.AddSystem<RandomSource<double>>( RandomDistribution::kExponential, 1, 0.0025); builder.Connect(w_short->get_output_port(0), beam_model->get_short_random_input_port()); auto w_uniform = builder.AddSystem<RandomSource<double>>( RandomDistribution::kUniform, 1, 0.0025); builder.Connect(w_uniform->get_output_port(0), beam_model->get_uniform_random_input_port()); auto logger = LogVectorOutput(beam_model->get_output_port(0), &builder); auto diagram = builder.Build(); systems::Simulator<double> simulator(*diagram); // Zero all initial state. for (int i = 0; i < simulator.get_context().num_discrete_state_groups(); i++) { BasicVector<double>& state = simulator.get_mutable_context().get_mutable_discrete_state(0); for (int j = 0; j < state.size(); j++) { state.SetAtIndex(j, 0.0); } } auto& params = beam_model->get_mutable_parameters(&diagram->GetMutableSubsystemContext( *beam_model, &simulator.get_mutable_context())); // Set some testable beam model parameters. params.set_lambda_short(2.0); params.set_sigma_hit(0.25); params.set_probability_short(0.2); params.set_probability_miss(0.05); params.set_probability_uniform(0.05); double probability_hit = 1.0 - params.probability_uniform() - params.probability_miss() - params.probability_short(); // Truncated tail of the exponential adds to "hit". probability_hit += std::exp(-params.lambda_short() * kDepthInput); auto probability_density_function = [&](double z) { DRAKE_DEMAND(z >= 0.0 && z < kMaxRange); // Doesn't capture the delta // function (with height p_miss) // at kMaxRange. const double p_short = (z <= kDepthInput) ? params.lambda_short() * std::exp(-params.lambda_short() * z) : 0.0; const double sigma_sq = params.sigma_hit() * params.sigma_hit(); return params.probability_uniform() / kMaxRange + params.probability_short() * p_short + probability_hit * std::exp(-0.5 * (z - kDepthInput) * (z - kDepthInput) / sigma_sq) / std::sqrt(2 * M_PI * sigma_sq); }; simulator.Initialize(); simulator.AdvanceTo(50); const auto& x = logger->FindLog(simulator.get_context()).data(); const int N = x.size(); // All values are in [0.0, kMaxRange] EXPECT_TRUE((x.array() >= 0.0 && x.array() <= kMaxRange).all()); // Python visual debugging: const Eigen::VectorXd depth = Eigen::VectorXd::LinSpaced(1000, 0.0, kMaxRange - 1e-6); Eigen::VectorXd pdf(depth.size()); for (int i = 0; i < static_cast<int>(depth.size()); i++) { pdf[i] = probability_density_function(depth[i]); } using common::CallPython; CallPython("figure", 1); CallPython("clf"); CallPython("plot", depth, pdf); CallPython("xlabel", "depth (m)"); CallPython("ylabel", "probability density"); const double h = 0.2; // Evaluate all subintervals [a,a+h] in [0,kMaxRange). for (double a = 0.0; a < kMaxRange; a += h) { // Counts the number of samples in (a,a+h). const double count = (x.array() >= a && x.array() < a + h - 1e-8) .template cast<double>() .matrix() .sum(); EXPECT_NEAR(count / N, probability_density_function(a + h / 2) * h, 1.5e-2); CallPython("plot", a + h / 2, count / N / h, "r."); } // Check the max returns. // Cumulative distribution function of the standard normal distribution. auto Phi = [](double z) { return 0.5 * std::erfc(-z / std::sqrt(2.0)); }; const double p_max = params.probability_miss() + probability_hit * Phi(-kDepthInput / params.sigma_hit()) // "hit" would have returned < 0.0. + probability_hit * Phi((kDepthInput - kMaxRange) / params.sigma_hit()); // "hit" would have returned > kMaxRange. EXPECT_NEAR( (x.array() == kMaxRange).template cast<double>().matrix().sum() / N, p_max, 3e-3); } GTEST_TEST(BeamModelTest, ScalarConversion) { const int kNumReadings = 10; const double kMaxRange = 5.0; BeamModel<double> model(kNumReadings, kMaxRange); EXPECT_TRUE(is_autodiffxd_convertible(model)); // N.B. Thus far conversion to symbolic is not supported. Update this test to // EXPECT_TRUE when supported. EXPECT_FALSE(is_symbolic_convertible(model)); } // This test should track the @code example in the header to make sure it // compiles and runs. GTEST_TEST(BeamModelTest, AddRandomInputsExample) { DiagramBuilder<double> builder; auto beam_model = builder.AddSystem<BeamModel>(1, 5.0); builder.ExportInput(beam_model->get_depth_input_port(), "depth"); builder.ExportOutput(beam_model->get_output_port(0), "depth"); AddRandomInputs(0.01, &builder); auto diagram = builder.Build(); } } // namespace } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/image_io_internal_test.cc
#include "drake/systems/sensors/image_io_internal.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/find_resource.h" namespace drake { namespace systems { namespace sensors { namespace internal { namespace { namespace fs = std::filesystem; GTEST_TEST(ImageIoInternalTest, FileFormatFromExtension) { // Simple cases. EXPECT_EQ(FileFormatFromExtension("foo.jpeg"), ImageFileFormat::kJpeg); EXPECT_EQ(FileFormatFromExtension("foo.jpg"), ImageFileFormat::kJpeg); EXPECT_EQ(FileFormatFromExtension("foo.png"), ImageFileFormat::kPng); EXPECT_EQ(FileFormatFromExtension("foo.tiff"), ImageFileFormat::kTiff); EXPECT_EQ(FileFormatFromExtension("foo.tif"), ImageFileFormat::kTiff); // Capitalization doesn't matter. EXPECT_EQ(FileFormatFromExtension("foo.Jpeg"), ImageFileFormat::kJpeg); EXPECT_EQ(FileFormatFromExtension("foo.JPG"), ImageFileFormat::kJpeg); EXPECT_EQ(FileFormatFromExtension("foo.Png"), ImageFileFormat::kPng); EXPECT_EQ(FileFormatFromExtension("foo.TIFF"), ImageFileFormat::kTiff); EXPECT_EQ(FileFormatFromExtension("foo.tiF"), ImageFileFormat::kTiff); // Full paths are okay. EXPECT_EQ(FileFormatFromExtension("/path/foo.jpeg"), ImageFileFormat::kJpeg); EXPECT_EQ(FileFormatFromExtension("/path/foo.jpg"), ImageFileFormat::kJpeg); EXPECT_EQ(FileFormatFromExtension("/path/foo.png"), ImageFileFormat::kPng); EXPECT_EQ(FileFormatFromExtension("/path/foo.tiff"), ImageFileFormat::kTiff); EXPECT_EQ(FileFormatFromExtension("/path/foo.tif"), ImageFileFormat::kTiff); // Unknown extensions. EXPECT_EQ(FileFormatFromExtension("other.txt"), std::nullopt); EXPECT_EQ(FileFormatFromExtension("png"), std::nullopt); EXPECT_EQ(FileFormatFromExtension("/png/other.txt"), std::nullopt); EXPECT_EQ(FileFormatFromExtension("/foo.png/other.txt"), std::nullopt); } GTEST_TEST(ImageIoInternalTest, GuessFileFormatFromBuffer) { std::array<uint8_t, 2> header; const ImageIo::ByteSpan span{header.data(), header.size()}; // Valid headers. header = {0xff, 0xd8}; EXPECT_EQ(GuessFileFormat(span), ImageFileFormat::kJpeg); header = {0x89, 0x50}; EXPECT_EQ(GuessFileFormat(span), ImageFileFormat::kPng); header = {0x49, 0x49}; EXPECT_EQ(GuessFileFormat(span), ImageFileFormat::kTiff); header = {0x4d, 0x4d}; EXPECT_EQ(GuessFileFormat(span), ImageFileFormat::kTiff); // Invalid headers. header = {}; EXPECT_EQ(GuessFileFormat(span), std::nullopt); EXPECT_EQ(GuessFileFormat(ImageIo::ByteSpan{}), std::nullopt); } GTEST_TEST(ImageIoInternalTest, GuessFileFormatFromFile) { const fs::path jpg_file = FindResourceOrThrow("drake/systems/sensors/test/jpeg_test.jpg"); const fs::path png_file = FindResourceOrThrow("drake/systems/sensors/test/png_color_test.png"); const fs::path tif_file = FindResourceOrThrow("drake/systems/sensors/test/tiff_32f_test.tif"); // Valid headers. EXPECT_EQ(GuessFileFormat(&jpg_file), ImageFileFormat::kJpeg); EXPECT_EQ(GuessFileFormat(&png_file), ImageFileFormat::kPng); EXPECT_EQ(GuessFileFormat(&tif_file), ImageFileFormat::kTiff); // Invalid headers. const fs::path zero = "/dev/zero"; const fs::path null = "/dev/null"; const fs::path none = "/no/such/file"; EXPECT_EQ(GuessFileFormat(&zero), std::nullopt); EXPECT_EQ(GuessFileFormat(&null), std::nullopt); EXPECT_EQ(GuessFileFormat(&none), std::nullopt); } GTEST_TEST(ImageIoInternalTest, NeedsBgrSwizzle) { // This is a trivial constexpr function, so it's sufficient to make sure it's // actually `constexpr` with a spot-check. We rely on code review to ensure // the switch cases are correct. constexpr bool swizzle_bgr = NeedsBgrSwizzle<PixelType::kBgr8U>(); EXPECT_TRUE(swizzle_bgr); } GTEST_TEST(ImageIoInternalTest, GetVtkScalarType) { // This is a trivial constexpr function, so it's sufficient to make sure it's // actually `constexpr` with a spot-check. We rely on code review to ensure // the switch cases are correct. constexpr int result = GetVtkScalarType<PixelType::kRgb8U>(); EXPECT_EQ(result, VTK_TYPE_UINT8); } GTEST_TEST(ImageIoInternalTest, GetDrakeScalarType) { // This is a trivial constexpr function, so it's sufficient to make sure it's // actually `constexpr` with a spot-check. We rely on code review to ensure // the switch cases are correct. constexpr std::optional<PixelScalar> result = GetDrakeScalarType(VTK_TYPE_UINT8); EXPECT_EQ(result, PixelScalar::k8U); } GTEST_TEST(ImageIoInternalTest, CopyAndFlipRaw) { // Choose a distinct value for every argument. constexpr int width = 5; constexpr int height = 2; constexpr int source_channels = 3; constexpr int dest_channels = 4; constexpr uint8_t dest_pad = 99; // Fill the source with incrementing numbers. // clang-format off constexpr int source_size = width * height * source_channels; const std::array<uint8_t, source_size> source = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12, 13,14,15, // NOLINT 16,17,18, 19,20,21, 22,23,24, 25,26,27, 28,29,30, // NOLINT }; // clang-format on // Prepare an output buffer. constexpr int dest_size = width * height * dest_channels; std::array<uint8_t, dest_size> dest; // Check without swizzling. CopyAndFlipRaw<uint8_t, source_channels, /* swizzle = */ false, dest_channels, dest_pad>(source.data(), dest.data(), width, height); // clang-format off EXPECT_THAT(dest, testing::ElementsAre( 16,17,18,99, 19,20,21,99, 22,23,24,99, 25,26,27,99, 28,29,30,99, // NOLINT 1, 2, 3,99, 4, 5, 6,99, 7, 8, 9,99, 10,11,12,99, 13,14,15,99 // NOLINT )); // NOLINT // clang-format on // Check with swizzling. CopyAndFlipRaw<uint8_t, source_channels, /* swizzle = */ true, dest_channels, dest_pad>(source.data(), dest.data(), width, height); // clang-format off EXPECT_THAT(dest, testing::ElementsAre( 18,17,16,99, 21,20,19,99, 24,23,22,99, 27,26,25,99, 30,29,28,99, // NOLINT 3, 2, 1,99, 6, 5, 4,99, 9, 8, 7,99, 12,11,10,99, 15,14,13,99 // NOLINT )); // NOLINT // clang-format on // Copy it again, with swizzling and dropping alpha. std::array<uint8_t, source_size> source_again; CopyAndFlipRaw<uint8_t, /* source_channels = */ dest_channels, /* swizzle = */ true, /* dest_channels = */ source_channels>( dest.data(), source_again.data(), width, height); // clang-format off EXPECT_THAT(source_again, testing::ElementsAre( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12, 13,14,15, // NOLINT 16,17,18, 19,20,21, 22,23,24, 25,26,27, 28,29,30 // NOLINT )); // NOLINT // clang-format on } } // namespace } // namespace internal } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/image_writer_free_functions_test.cc
#include <filesystem> #include <string> #include <gtest/gtest.h> #include "drake/common/temp_directory.h" #include "drake/systems/sensors/image_writer.h" #include "drake/systems/sensors/test_utilities/image_compare.h" namespace drake { namespace systems { namespace sensors { namespace fs = std::filesystem; namespace { class SaveImageTest : public ::testing::Test { public: void SetUp() override { const std::string name = testing::UnitTest::GetInstance()->current_test_info()->name(); filename_ = (fs::path(temp_directory()) / fmt::format("{}.png", name)).string(); } template <PixelType kPixelType> void CheckReadback(const Image<kPixelType>& expected) { Image<kPixelType> readback; ASSERT_TRUE(LoadImage(filename_, &readback)); EXPECT_EQ(readback, expected); } protected: std::string filename_; }; // Saves a simple 4x1 image consisting of: [red][green][blue][white]. TEST_F(SaveImageTest, SaveToPng_Color) { Image<PixelType::kRgba8U> image(4, 1); auto set_color = [&image](int x, int y, uint8_t r, uint8_t g, uint8_t b) { image.at(x, y)[0] = r; image.at(x, y)[1] = g; image.at(x, y)[2] = b; image.at(x, y)[3] = 255; }; set_color(0, 0, 255, 0, 0); set_color(1, 0, 0, 255, 0); set_color(2, 0, 0, 0, 255); set_color(3, 0, 255, 255, 255); EXPECT_NO_THROW(SaveToPng(image, filename_)); CheckReadback(image); } // Saves a simple 4x1 image consisting of: 0, 0.25, 0.5, 0.75 TEST_F(SaveImageTest, SaveToTiff_Depth) { Image<PixelType::kDepth32F> image(4, 1); *image.at(0, 0) = 0.0f; *image.at(1, 0) = 0.25f; *image.at(2, 0) = 0.5f; *image.at(3, 0) = 1.0f; EXPECT_NO_THROW(SaveToTiff(image, filename_)); CheckReadback(image); } // Saves a simple 4x1 image consisting of: 0, 100, 200, 300. // Note: value > 255 to make sure that values aren't being truncated/wrapped // to 8-bit values. TEST_F(SaveImageTest, SaveToPng_Label) { Image<PixelType::kLabel16I> image(4, 1); *image.at(0, 0) = 0; *image.at(1, 0) = 100; *image.at(2, 0) = 200; *image.at(3, 0) = 300; EXPECT_NO_THROW(SaveToPng(image, filename_)); CheckReadback(image); } // Saves a simple 4x1 image consisting of: 0, 100, 200, 300. // Note: value > 255 to make sure that values aren't being truncated/wrapped // to 8-bit values. TEST_F(SaveImageTest, SaveToPng_Depth16) { Image<PixelType::kDepth16U> image(4, 1); *image.at(0, 0) = 0; *image.at(1, 0) = 100; *image.at(2, 0) = 200; *image.at(3, 0) = 300; EXPECT_NO_THROW(SaveToPng(image, filename_)); CheckReadback(image); } // Saves a simple 4x1 image consisting of: 1, 2, 3, 4. TEST_F(SaveImageTest, SaveToPng_Grey) { Image<PixelType::kGrey8U> image(4, 1); *image.at(0, 0) = 1; *image.at(1, 0) = 2; *image.at(2, 0) = 3; *image.at(3, 0) = 4; EXPECT_NO_THROW(SaveToPng(image, filename_)); CheckReadback(image); } } // namespace } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/camera_config_test.cc
#include "drake/systems/sensors/camera_config.h" #include <vector> #include <fmt/format.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/eigen_types.h" #include "drake/common/schema/transform.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/yaml/yaml_io.h" #include "drake/geometry/render_gl/render_engine_gl_params.h" #include "drake/geometry/render_gltf_client/render_engine_gltf_client_params.h" #include "drake/geometry/render_vtk/render_engine_vtk_params.h" #include "drake/geometry/rgba.h" #include "drake/systems/sensors/camera_info.h" namespace drake { namespace geometry { // Some quick and dirty comparison operators so we can use gtest matchers with // the render engine parameter types. bool operator==(const RenderEngineVtkParams& p1, const RenderEngineVtkParams& p2) { return yaml::SaveYamlString(p1) == yaml::SaveYamlString(p2); } bool operator==(const RenderEngineGlParams& p1, const RenderEngineGlParams& p2) { return yaml::SaveYamlString(p1) == yaml::SaveYamlString(p2); } bool operator==(const RenderEngineGltfClientParams& p1, const RenderEngineGltfClientParams& p2) { return yaml::SaveYamlString(p1) == yaml::SaveYamlString(p2); } } // namespace geometry namespace systems { namespace sensors { namespace { using Eigen::Vector3d; using geometry::RenderEngineGlParams; using geometry::RenderEngineGltfClientParams; using geometry::RenderEngineVtkParams; using geometry::Rgba; using geometry::render::ColorRenderCamera; using geometry::render::DepthRenderCamera; using geometry::render::RenderCameraCore; using math::RigidTransformd; using schema::Transform; using yaml::LoadYamlString; using yaml::SaveYamlString; // Confirms that a default-constructed camera config has valid values. GTEST_TEST(CameraConfigTest, DefaultValues) { CameraConfig config; ASSERT_NO_THROW(config.ValidateOrThrow()); // The default background color is documented as matching the color in // RenderEngineVtkParams. Confirm they match. If either changes, this test // will fail and we'll have to decide what to do about it. Rgba vtk_background; vtk_background.set(RenderEngineVtkParams().default_clear_color); EXPECT_EQ(config.background, vtk_background); } // Tests the principal point logic. GTEST_TEST(CameraConfigTest, PrincipalPoint) { const CameraConfig kDefault; { // If we never set the principal point, it always remains centered on // the image (even as we change image size). The computed center should // always match the center computed by CameraInfo. // Two arbitrary image sizes to confirm that it respects image size. We'll // use an arbitrary focal length value that doesn't affect the outcome. constexpr double kFovY = 1.5; { int w = 328, h = 488; CameraConfig c{.width = w, .height = h}; const Vector2<double> center = c.principal_point(); CameraInfo intrinsics(c.width, c.height, kFovY); EXPECT_EQ(center.x(), intrinsics.center_x()); EXPECT_EQ(center.y(), intrinsics.center_y()); } { int w = 207, h = 833; CameraConfig c{.width = w, .height = h}; const Vector2<double> center = c.principal_point(); CameraInfo intrinsics(c.width, c.height, kFovY); EXPECT_EQ(center.x(), intrinsics.center_x()); EXPECT_EQ(center.y(), intrinsics.center_y()); } } // Confirm that the x- and y-components of the principal point are independent // and, after setting them, they no longer change w.r.t. image size. { // Center x. CameraConfig c; c.center_x = 17; EXPECT_EQ(*c.center_x, 17); const Vector2<double> center1 = c.principal_point(); EXPECT_EQ(center1.x(), 17); // The y-position of the principal point hasn't moved. EXPECT_NEAR(center1.y(), c.height / 2, 0.5); // Doesn't change when the width changes. c.width = 180; const Vector2<double> center2 = c.principal_point(); EXPECT_EQ(center2.x(), 17); EXPECT_EQ(center2.y(), center1.y()); } { // Center y. CameraConfig c; c.center_y = 19; EXPECT_EQ(*c.center_y, 19); const Vector2<double> center1 = c.principal_point(); // The x-position of the principal point hasn't moved. EXPECT_NEAR(center1.x(), c.width / 2, 0.5); EXPECT_EQ(center1.y(), 19); // Doesn't change when the height changes. c.height = 123; const Vector2<double> center2 = c.principal_point(); EXPECT_EQ(center2.x(), center1.x()); EXPECT_EQ(center2.y(), 19); } } // Simply confirm that the FocalLength has the appropriate semantics of defining // one or both values (and does proper validation). GTEST_TEST(CameraConfigTest, CameraConfigFocalLength) { constexpr double kFocalX = 250; constexpr double kFocalY = 250; { // Just specifying focal x reports that value for x and y. const CameraConfig::FocalLength focal{.x = kFocalX}; EXPECT_EQ(focal.focal_x(), kFocalX); EXPECT_EQ(focal.focal_y(), kFocalX); } { // Just specifying focal y reports that value for x and y. const CameraConfig::FocalLength focal{.y = kFocalX}; EXPECT_EQ(focal.focal_x(), kFocalX); EXPECT_EQ(focal.focal_y(), kFocalX); } { // Specifying both gets propagated. const CameraConfig::FocalLength focal{.x = kFocalX, .y = kFocalY}; EXPECT_EQ(focal.focal_x(), kFocalX); EXPECT_EQ(focal.focal_y(), kFocalY); } { // Specifying no values throws (and both focal_x an focal_y validate). const CameraConfig::FocalLength null_focal; DRAKE_EXPECT_THROWS_MESSAGE(null_focal.focal_x(), ".*you must define .* for FocalLength."); DRAKE_EXPECT_THROWS_MESSAGE(null_focal.focal_y(), ".*you must define .* for FocalLength."); } } GTEST_TEST(CameraConfigTest, CameraConfigFovDegrees) { constexpr int kWidth = 640; constexpr int kHeight = 480; constexpr double kFocalX = 250; constexpr double kFocalY = 250; const CameraInfo intrinsics(kWidth, kHeight, kFocalX, kFocalY, kWidth * 0.5, kHeight * 0.5); const double kFovXDeg = intrinsics.fov_x() * 180 / M_PI; const double kFovYDeg = intrinsics.fov_y() * 180 / M_PI; { // Just specifying fov x (a) computes the right focal length and (b) the // same value for x and y. const CameraConfig::FovDegrees fov{.x = kFovXDeg}; EXPECT_DOUBLE_EQ(fov.focal_x(kWidth, kHeight), kFocalX); EXPECT_DOUBLE_EQ(fov.focal_y(kWidth, kHeight), kFocalX); } { // Just specifying fov y (a) computes the right focal length and (b) the // same value for x and y. const CameraConfig::FovDegrees fov{.y = kFovYDeg}; EXPECT_DOUBLE_EQ(fov.focal_x(kWidth, kHeight), kFocalY); EXPECT_DOUBLE_EQ(fov.focal_y(kWidth, kHeight), kFocalY); } { // Specifying both right focal length for each direction independently. const CameraConfig::FovDegrees fov{.x = kFovXDeg, .y = kFovYDeg}; EXPECT_DOUBLE_EQ(fov.focal_x(kWidth, kHeight), kFocalX); EXPECT_DOUBLE_EQ(fov.focal_y(kWidth, kHeight), kFocalY); } { // Specifying no values throws (and both focal_x an focal_y validate). CameraConfig::FovDegrees null_fov; DRAKE_EXPECT_THROWS_MESSAGE(null_fov.focal_x(kWidth, kHeight), ".*you must define .* for FovDegrees."); DRAKE_EXPECT_THROWS_MESSAGE(null_fov.focal_y(kWidth, kHeight), ".*you must define .* for FovDegrees."); } } // Tests the focal length semantics. GTEST_TEST(CameraConfigTest, FocalLength) { { // Both values match by default. CameraConfig c; EXPECT_EQ(c.focal_x(), c.focal_y()); } { // Both change independently when assigning an FocalLength value. CameraConfig c; const double old_focal = c.focal_x(); const double new_focal_x = old_focal + 10; const double new_focal_y = old_focal - 10; c.focal = CameraConfig::FocalLength{new_focal_x, new_focal_y}; EXPECT_EQ(c.focal_x(), new_focal_x); EXPECT_EQ(c.focal_y(), new_focal_y); } { // Both change independently when assigning a FovDegrees value. We'll // create field of view angles from target focal lengths, and make sure we // get back the expected focal lengths. CameraConfig c; const double target_focal_x = 250; const double target_focal_y = 275; // We'll use CameraInfo to convert focal lengths into fovs; the center point // doesn't contribute to this calculation.) const CameraInfo intrinsics(c.width, c.height, target_focal_x, target_focal_y, 0.5 * c.width, 0.5 * c.height); const double fov_x_rad = intrinsics.fov_x(); const double fov_y_rad = intrinsics.fov_y(); c.focal = CameraConfig::FovDegrees{fov_x_rad * 180 / M_PI, fov_y_rad * 180 / M_PI}; EXPECT_DOUBLE_EQ(c.focal_x(), target_focal_x); EXPECT_DOUBLE_EQ(c.focal_y(), target_focal_y); } } // Confirm that serialization happens the right way: // background: // rgba: [r, g, b, a] // We don't have to worry about malformed specifications, that is handled by // the Rgba's logic and tests. We just need to make sure we're invoking it // correctly. GTEST_TEST(CameraConfigTest, SerializeBackgroundRgba) { CameraConfig config; config.background = Rgba(0.1, 0.2, 0.3, 0.4); // Serialize so that only background gets written by providing default. const std::string yaml = SaveYamlString<CameraConfig>(config, {}, CameraConfig()); EXPECT_EQ(yaml, "background:\n rgba: [0.1, 0.2, 0.3, 0.4]\n"); } GTEST_TEST(CameraConfigTest, SerializationDefaultRoundTrip) { const CameraConfig original; const std::string yaml = SaveYamlString<CameraConfig>(original); EXPECT_NO_THROW(LoadYamlString<CameraConfig>(yaml)) << "with yaml:\n" << yaml; } // Various tests to support the documented examples in the documentation. The // number of each parsed config should correspond to the number in the docs for // the renderer_class field. GTEST_TEST(CameraConfigTest, DeserializingRendererClass) { auto parse = [](const char* yaml) -> CameraConfig { return LoadYamlString<CameraConfig>(yaml, {}, CameraConfig()); }; const CameraConfig config_1 = parse("renderer_class: RenderEngineVtk"); EXPECT_THAT(config_1.renderer_class, testing::VariantWith<std::string>("RenderEngineVtk")); const CameraConfig config_2 = parse("renderer_class: !RenderEngineVtkParams {}"); EXPECT_THAT( config_2.renderer_class, testing::VariantWith<RenderEngineVtkParams>(RenderEngineVtkParams{})); const CameraConfig config_3 = parse(R"""( renderer_class: !RenderEngineVtkParams default_clear_color: [0, 0, 0])"""); EXPECT_THAT(config_3.renderer_class, testing::VariantWith<RenderEngineVtkParams>( RenderEngineVtkParams{.default_clear_color = {0, 0, 0}})); const CameraConfig config_4 = parse(R"""( renderer_class: !RenderEngineGlParams default_clear_color: rgba: [0, 0, 0, 1])"""); EXPECT_THAT(config_4.renderer_class, testing::VariantWith<RenderEngineGlParams>( RenderEngineGlParams{.default_clear_color = Rgba(0, 0, 0)})); const CameraConfig config_5 = parse(R"""( renderer_class: !RenderEngineGltfClientParams base_url: http://10.10.10.1 render_endpoint: server verbose: true cleanup: false)"""); EXPECT_THAT(config_5.renderer_class, testing::VariantWith<RenderEngineGltfClientParams>( RenderEngineGltfClientParams{.base_url = "http://10.10.10.1", .render_endpoint = "server", .verbose = true, .cleanup = false})); const CameraConfig config_6 = parse("renderer_class: \"\""); EXPECT_THAT(config_6.renderer_class, testing::VariantWith<std::string>("")); } // Helper functions for validating a render camera. void CoreIsValid(const RenderCameraCore& core, const CameraConfig& config, const RigidTransformd& X_BS) { EXPECT_EQ(core.renderer_name(), config.renderer_name); EXPECT_EQ(core.intrinsics().width(), config.width); EXPECT_EQ(core.intrinsics().height(), config.height); EXPECT_EQ(core.intrinsics().focal_x(), config.focal_x()); EXPECT_EQ(core.intrinsics().focal_y(), config.focal_y()); EXPECT_EQ(core.intrinsics().center_x(), *config.center_x); EXPECT_EQ(core.intrinsics().center_y(), *config.center_y); EXPECT_EQ(core.clipping().near(), config.clipping_near); EXPECT_EQ(core.clipping().far(), config.clipping_far); EXPECT_TRUE(core.sensor_pose_in_camera_body().IsExactlyEqualTo(X_BS)); } void ColorIsValid(const ColorRenderCamera& camera, const CameraConfig& config) { EXPECT_EQ(camera.show_window(), config.show_rgb); // X_BS = I by convention for CameraConfig. CoreIsValid(camera.core(), config, {}); } void DepthIsValid(const DepthRenderCamera& camera, const CameraConfig& config) { EXPECT_EQ(camera.depth_range().min_depth(), config.z_near); EXPECT_EQ(camera.depth_range().max_depth(), config.z_far); CoreIsValid(camera.core(), config, config.X_BD.GetDeterministicValue()); } // Tests the logic for creating the pair of cameras. Generally, it confirms // that valid config values propagate through. GTEST_TEST(CameraConfigTest, MakeCameras) { // These values are *supposed* to be different from the default values except // for X_PB, fps, rgb, depth, and do_compress. None of those contribute // to the test result. CameraConfig config{.width = 320, .height = 240, .focal = CameraConfig::FocalLength{470.0, 480.0}, .center_x = 237, .center_y = 233, .clipping_near = 0.075, .clipping_far = 17.5, .z_near = 0.15, .z_far = 4.75, .X_PB = {}, .X_BD = Transform{RigidTransformd{Vector3d::UnitX()}}, .renderer_name = "test_renderer", .background = Rgba(0.1, 0.2, 0.3, 0.4), .name = "test_camera", .fps = 17, .rgb = false, .depth = true, .label = true, .show_rgb = true}; // Check that all the values have propagated. const auto [color, depth] = config.MakeCameras(); SCOPED_TRACE("Fully specified values"); ColorIsValid(color, config); DepthIsValid(depth, config); } // CameraConfig explicitly validates several things: // - X_BD.base_frame is empty, // - X_BC.base_frame is empty, // - name is not empty, // - renderer_name is not empty, // - renderer_class is one of the documented set of supported strings, and // - fps is a positive, finite value. // It relies on Drake's geometry::render artifacts to validate the other // restricted values. Finally, validation should be part of serialization. // // This test confirms CameraConfigs *specific* validation responsibilities, // and provides smoke tests that indicate that the other fields are validated // and that Serialize validates. GTEST_TEST(CameraConfigTest, Validation) { const CameraConfig kDefault; // Reality check that the default configuration is valid. EXPECT_NO_THROW(kDefault.ValidateOrThrow()); { CameraConfig config; config.X_BD.base_frame = "error"; DRAKE_EXPECT_THROWS_MESSAGE( config.ValidateOrThrow(), ".*X_BD must not specify a base frame. 'error' found."); } { CameraConfig config; config.X_BC.base_frame = "error"; DRAKE_EXPECT_THROWS_MESSAGE( config.ValidateOrThrow(), ".*X_BC must not specify a base frame. 'error' found."); } // We require a non-empty name. DRAKE_EXPECT_THROWS_MESSAGE(CameraConfig{.name = ""}.ValidateOrThrow(), ".* name cannot be empty."); // We require a non-empty renderer-name. DRAKE_EXPECT_THROWS_MESSAGE( CameraConfig{.renderer_name = ""}.ValidateOrThrow(), ".*renderer_name cannot be empty."); // Good renderer_class strings don't throw (we already know that default // doesn't throw). EXPECT_NO_THROW( CameraConfig{.renderer_class = "RenderEngineVtk"}.ValidateOrThrow()); EXPECT_NO_THROW( CameraConfig{.renderer_class = "RenderEngineGl"}.ValidateOrThrow()); // Bad renderer_class strings throw -- proof the field is being validated. DRAKE_EXPECT_THROWS_MESSAGE( CameraConfig{.renderer_class = "BadName"}.ValidateOrThrow(), ".*the given renderer_class value.*"); // Non-positive, non-finite values all throw. DRAKE_EXPECT_THROWS_MESSAGE(CameraConfig{.fps = 0}.ValidateOrThrow(), ".*FPS.*"); DRAKE_EXPECT_THROWS_MESSAGE(CameraConfig{.fps = -11}.ValidateOrThrow(), ".*FPS.*"); DRAKE_EXPECT_THROWS_MESSAGE( CameraConfig{.fps = std::numeric_limits<double>::infinity()} .ValidateOrThrow(), ".*FPS.*"); DRAKE_EXPECT_THROWS_MESSAGE( CameraConfig{.fps = std::numeric_limits<double>::quiet_NaN()} .ValidateOrThrow(), ".*FPS.*"); // Indicator that geometry::render is being exercised to validate other // values. EXPECT_THROW(CameraConfig{.width = -5}.ValidateOrThrow(), std::exception); // An invalid configuration should throw when serializing. DRAKE_EXPECT_THROWS_MESSAGE(SaveYamlString(CameraConfig{.name = ""}), ".*name cannot be empty."); // An invalid sub-struct should throw when serializing. DRAKE_EXPECT_THROWS_MESSAGE( SaveYamlString(CameraConfig{.focal = CameraConfig::FovDegrees{}}), ".*must define at least x or y.*"); // However, if rgb = depth = label = false, then the configuration is by // definition valid, even with otherwise bad values elsewhere. CameraConfig config_no_render{.rgb = false, .depth = false, .label = false}; config_no_render.focal = CameraConfig::FovDegrees{}; EXPECT_NO_THROW(config_no_render.ValidateOrThrow()); EXPECT_NO_THROW(SaveYamlString(config_no_render)); } } // namespace } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/image_file_format_test.cc
#include "drake/systems/sensors/image_file_format.h" #include <gtest/gtest.h> namespace drake { namespace systems { namespace sensors { // Checks for fmt capability. A spot-check of just one enum value is sufficient. GTEST_TEST(ImageFileFormatTest, ToString) { EXPECT_EQ(fmt::to_string(ImageFileFormat::kPng), "png"); } } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/image_io_test_params.h
#pragma once #include <ostream> #include <gtest/gtest.h> #include "drake/systems/sensors/image.h" #include "drake/systems/sensors/image_file_format.h" // To ease build system upkeep, we annotate VTK includes with their deps. #include <vtkImageData.h> // vtkCommonDataModel #include <vtkNew.h> // vtkCommonCore #include <vtkType.h> // vtkCommonCore namespace drake { namespace systems { namespace sensors { /* Provides a grouping for value-parameterized test params. */ struct ImageIoTestParams { ImageFileFormat format{ImageFileFormat::kJpeg}; /* Whether to use files or memory buffers. */ bool write_to_file{false}; /* Whether to use uint16_t (instead of the natural type). */ bool force_16u{false}; /* Whether to use a single-channel image (instead of color). When the scalar type is not 8U, then grayscale is already the default. */ bool force_gray{false}; /* Whether to use an alpha-channel. */ bool alpha{false}; /* Returns the PixelScalar intended for the current params. */ PixelScalar pixel_scalar() const { return force_16u ? PixelScalar::k16U : (format == ImageFileFormat::kTiff) ? PixelScalar::k32F : PixelScalar::k8U; } /* Returns the VTK scalar type intended for the current params. */ int vtk_scalar() const { return force_16u ? VTK_TYPE_UINT16 : (format == ImageFileFormat::kTiff) ? VTK_TYPE_FLOAT32 : VTK_TYPE_UINT8; } /* The width for Create...Image(). */ int width() const { return 3; } /* The height for Create...Image(). */ int height() const { return 2; } /* The depth for Create...Image(). This will always be 1. */ int depth() const { return 1; } /* The channels for Create...Image(). */ int channels() const { const bool is_byte_channel = pixel_scalar() == PixelScalar::k8U; if (force_gray) { DRAKE_DEMAND(is_byte_channel); return 1; } if (alpha) { DRAKE_DEMAND(is_byte_channel); return 4; } return is_byte_channel ? 3 : 1; } /* The product of width * height * depth * channels. */ int total_storage() const { return width() * height() * depth() * channels(); } /* Creates a sample image in memory. The image data will be filled with incrementing numbers, starting from 1 for the first datum. */ vtkNew<vtkImageData> CreateIotaVtkImage() const; /* Creates a sample image in memory. The image data will be filled with incrementing numbers, starting from 1 for the first datum. */ ImageAny CreateIotaDrakeImage() const; /* Given pointers to the pixel data buffer for two images, checks whether the round-trip Save() and Load() ended up with a correctly-loaded image. @pre the pixel data buffers have the right scalar type and total storage. */ void CompareImageBuffer(const void* original, const void* readback) const; friend std::ostream& operator<<(std::ostream& os, const ImageIoTestParams& self) { os << fmt::format("[format = {}; write_to_file = {}; force_16u = {}]", self.format, self.write_to_file, self.force_16u); return os; } }; inline auto GetAllImageIoTestParams() { using Params = ImageIoTestParams; constexpr ImageFileFormat kJpeg = ImageFileFormat::kJpeg; constexpr ImageFileFormat kPng = ImageFileFormat::kPng; constexpr ImageFileFormat kTiff = ImageFileFormat::kTiff; return testing::Values( // VTK JPEG only supports 8-bit channels, so no 16u here. Params{.format = kJpeg, .write_to_file = true}, Params{.format = kJpeg, .write_to_file = false}, // VTK PNG supports grayscale, an alpha channel, and 16-bit channels. Params{.format = kPng, .write_to_file = true}, Params{.format = kPng, .write_to_file = false}, Params{.format = kPng, .write_to_file = true, .force_gray = true}, Params{.format = kPng, .write_to_file = false, .force_gray = true}, Params{.format = kPng, .write_to_file = true, .alpha = true}, Params{.format = kPng, .write_to_file = false, .alpha = true}, Params{.format = kPng, .write_to_file = true, .force_16u = true}, Params{.format = kPng, .write_to_file = false, .force_16u = true}, // VTK TIFF doesn't support writing to memory. Params{.format = kTiff, .write_to_file = true}, Params{.format = kTiff, .write_to_file = true, .force_16u = true}); } } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/camera_config_functions_test.cc
#include "drake/systems/sensors/camera_config_functions.h" #include <string> #include <utility> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/yaml/yaml_io.h" #include "drake/geometry/render_gl/factory.h" #include "drake/geometry/render_gltf_client/factory.h" #include "drake/geometry/render_vtk/factory.h" #include "drake/lcm/drake_lcm.h" #include "drake/systems/lcm/lcm_publisher_system.h" #include "drake/systems/sensors/image_to_lcm_image_array_t.h" #include "drake/systems/sensors/rgbd_sensor_async.h" #include "drake/systems/sensors/sim_rgbd_sensor.h" namespace drake { namespace systems { namespace sensors { namespace { using drake::geometry::FrameId; using drake::geometry::RenderEngineGlParams; using drake::geometry::RenderEngineGltfClientParams; using drake::geometry::RenderEngineVtkParams; using drake::geometry::Rgba; using drake::geometry::SceneGraph; using drake::geometry::render::ColorRenderCamera; using drake::geometry::render::DepthRenderCamera; using drake::lcm::DrakeLcm; using drake::lcm::DrakeLcmInterface; using drake::math::RigidTransformd; using drake::multibody::AddMultibodyPlantSceneGraph; using drake::multibody::FixedOffsetFrame; using drake::multibody::MultibodyPlant; using drake::schema::Transform; using drake::systems::DiagramBuilder; using drake::systems::lcm::LcmBuses; using drake::systems::lcm::LcmPublisherSystem; using drake::systems::sensors::ImageToLcmImageArrayT; using drake::systems::sensors::RgbdSensor; using drake::yaml::SaveYamlString; using Eigen::Vector3d; /* Simply makes a config where none of the values are defaulted. */ CameraConfig MakeConfig() { // These values are *supposed* to be different from the default values. CameraConfig config{.width = 320, .height = 240, .focal = CameraConfig::FocalLength{.x = 470.0}, .center_x = 237, .center_y = 233, .clipping_near = 0.075, .clipping_far = 17.5, .z_near = 0.15, .z_far = 4.75, .X_PB = Transform{RigidTransformd{Vector3d::UnitX()}}, .X_BC = Transform{RigidTransformd{Vector3d::UnitX()}}, .X_BD = Transform{RigidTransformd{Vector3d::UnitX()}}, .renderer_name = "test_renderer", .renderer_class = "RenderEngineGltfClient", .background = Rgba(0.25, 0.5, 0.75), .name = "test_camera", .fps = 17, .capture_offset = 0.001, .output_delay = 0.002, .rgb = false, .depth = true, .label = true, .show_rgb = true, .do_compress = false, .lcm_bus = "test_lcm_bus"}; // drake::scheme::Transform cannot be constructed with a base frame. config.X_PB.base_frame = "test_frame"; return config; } /* A reality check that MakeConfig() produces a config that is *completely* different from the default. */ GTEST_TEST(CameraConfigTest, NonDefault) { const std::string full_data = SaveYamlString(MakeConfig()); const std::string differential_data = SaveYamlString<CameraConfig>(MakeConfig(), {}, CameraConfig{}); EXPECT_EQ(full_data, differential_data); } class CameraConfigFunctionsTest : public ::testing::Test { protected: void SetUp() override { // We're not simulating -- so creating a continuous plant is fine. std::tie(plant_, scene_graph_) = AddMultibodyPlantSceneGraph(&builder_, 0); // Populate builder with sufficient stuff. const auto& body = plant_->AddRigidBody("test_body"); body_frame_id_ = plant_->GetBodyFrameIdOrThrow(body.index()); plant_->AddFrame(std::make_unique<FixedOffsetFrame<double>>( "test_frame", body, RigidTransformd())); } DiagramBuilder<double> builder_; MultibodyPlant<double>* plant_{}; SceneGraph<double>* scene_graph_{}; FrameId body_frame_id_; }; /* If the CameraConfig has none of the image types, i.e., rgb, depth, and label, set to true, no systems should be instantiated. */ TEST_F(CameraConfigFunctionsTest, EarlyExit) { CameraConfig config; // Regardless of what the default config is, we'll guarantee that we're not // requesting rgb, depth, or label publication. config.rgb = config.depth = config.label = false; const int system_count = static_cast<int>(builder_.GetSystems().size()); ApplyCameraConfig(config, &builder_); // We haven't added anything to the builder. EXPECT_EQ(builder_.GetSystems().size(), system_count); } /* The tests below require that the default CameraConfig renders at least one image. This test puts a guard on that property. */ GTEST_TEST(CameraConfigFunctionsTestAux, DefaultConfigRenders) { const CameraConfig config; EXPECT_TRUE(config.rgb || config.depth || config.label); } /* If base frame is not defined for X_PB, the sensor must be posed relative to the world. */ TEST_F(CameraConfigFunctionsTest, ParentBaseFrameDefaultToWorld) { CameraConfig config; config.X_PB.base_frame = std::nullopt; ApplyCameraConfig(config, &builder_); const auto& sensor = builder_.GetDowncastSubsystemByName<RgbdSensor>( "rgbd_sensor_preview_camera"); EXPECT_EQ(sensor.parent_frame_id(), scene_graph_->world_frame_id()); } /* If base frame *is* given in X_PB, the sensor must be posed relative to that frame. */ TEST_F(CameraConfigFunctionsTest, ParentBaseFrameSpecified) { CameraConfig config; config.X_PB.base_frame = "test_frame"; ApplyCameraConfig(config, &builder_); const auto& sensor = builder_.GetDowncastSubsystemByName<RgbdSensor>( "rgbd_sensor_preview_camera"); // Although we've declared it to be relative to a *frame*, there is no // geometry::FrameId associated with the frame. So, instead, RgbdSensor // references the body to which the named frame is affixed. EXPECT_EQ(sensor.parent_frame_id(), body_frame_id_); // We don't test that the camera is posed relative to the *body* frame // correctly because that is covered by the tests for `SimRgbdSensor`. } /* If base frame is given in X_PB, but does not name an existing frame, we throw. */ TEST_F(CameraConfigFunctionsTest, InvalidParentBaseFrame) { CameraConfig config; config.X_PB.base_frame = "invalid_frame"; DRAKE_EXPECT_THROWS_MESSAGE(ApplyCameraConfig(config, &builder_), ".*invalid_frame.*"); } /* Confirms that renderer_name is handled correctly. - If a render engine is named that hasn't been previously created, a new engine is added and the sensor is assigned to it. - If a previously existing engine is named, no new engine is created and the existing engine is shared. - The error case where the same name is used with a different class is dealt with in RendererNameReuse. - The provided renderer_name and config.name is piped into the sensor. This is independent of image type, so, we'll use rgb. */ TEST_F(CameraConfigFunctionsTest, RendererClassBasic) { ASSERT_EQ(scene_graph_->RendererCount(), 0); CameraConfig config; ApplyCameraConfig(config, &builder_); ASSERT_EQ(scene_graph_->RendererCount(), 1); const auto& sensor1 = builder_.GetDowncastSubsystemByName<RgbdSensor>( "rgbd_sensor_preview_camera"); EXPECT_EQ(sensor1.color_render_camera().core().renderer_name(), config.renderer_name); EXPECT_EQ(sensor1.depth_render_camera().core().renderer_name(), config.renderer_name); // Now add second camera which uses the same name. size_t previous_system_count = builder_.GetSystems().size(); config.name = config.name + "_the_other_one"; EXPECT_NO_THROW(ApplyCameraConfig(config, &builder_)); // No new render engine added. ASSERT_EQ(scene_graph_->RendererCount(), 1); // New RgbdSensor added. EXPECT_GT(builder_.GetSystems().size(), previous_system_count); previous_system_count = builder_.GetSystems().size(); const auto& sensor2 = builder_.GetDowncastSubsystemByName<RgbdSensor>( "rgbd_sensor_preview_camera_the_other_one"); EXPECT_EQ(sensor2.color_render_camera().core().renderer_name(), config.renderer_name); EXPECT_EQ(sensor2.depth_render_camera().core().renderer_name(), config.renderer_name); // Third camera uses a unique name creates a unique render engine. config.name = "just_for_test"; config.renderer_name = "just_for_test"; EXPECT_NO_THROW(ApplyCameraConfig(config, &builder_)); ASSERT_EQ(scene_graph_->RendererCount(), 2); // New RgbdSensor added. EXPECT_GT(builder_.GetSystems().size(), previous_system_count); const auto& sensor3 = builder_.GetDowncastSubsystemByName<RgbdSensor>( "rgbd_sensor_just_for_test"); EXPECT_EQ(sensor3.color_render_camera().core().renderer_name(), config.renderer_name); EXPECT_EQ(sensor3.depth_render_camera().core().renderer_name(), config.renderer_name); } /* Exercises the various ways to specify the various RenderEngine classes - via class name or parameters. Simply a regression test to make sure the spellings work. */ TEST_F(CameraConfigFunctionsTest, RendererClassVariant) { int renderer_count = 0; // Add VTK by name. { const CameraConfig config{.renderer_name = "vtk_name", .renderer_class = "RenderEngineVtk"}; ApplyCameraConfig(config, &builder_); EXPECT_EQ(scene_graph_->RendererCount(), ++renderer_count); EXPECT_THAT(scene_graph_->GetRendererTypeName(config.renderer_name), testing::EndsWith("RenderEngineVtk")); } // Add VTK by parameters. { const CameraConfig config{.renderer_name = "vtk_params", .renderer_class = RenderEngineVtkParams{}}; ApplyCameraConfig(config, &builder_); EXPECT_EQ(scene_graph_->RendererCount(), ++renderer_count); EXPECT_THAT(scene_graph_->GetRendererTypeName(config.renderer_name), testing::EndsWith("RenderEngineVtk")); } // Add glTF client by name. { const CameraConfig config{.renderer_name = "gltf_client_name", .renderer_class = "RenderEngineGltfClient"}; ApplyCameraConfig(config, &builder_); EXPECT_EQ(scene_graph_->RendererCount(), ++renderer_count); EXPECT_THAT(scene_graph_->GetRendererTypeName(config.renderer_name), testing::EndsWith("RenderEngineGltfClient")); } // Add glTF client by parameters. { const CameraConfig config{.renderer_name = "gltf_client_params", .renderer_class = RenderEngineGltfClientParams{}}; ApplyCameraConfig(config, &builder_); EXPECT_EQ(scene_graph_->RendererCount(), ++renderer_count); EXPECT_THAT(scene_graph_->GetRendererTypeName(config.renderer_name), testing::EndsWith("RenderEngineGltfClient")); } if (geometry::kHasRenderEngineGl) { // Add GL by name. { const CameraConfig config{.renderer_name = "gl_name", .renderer_class = "RenderEngineGl"}; ApplyCameraConfig(config, &builder_); EXPECT_EQ(scene_graph_->RendererCount(), ++renderer_count); EXPECT_THAT(scene_graph_->GetRendererTypeName(config.renderer_name), testing::EndsWith("RenderEngineGl")); } // Add GL by parameters. { const CameraConfig config{.renderer_name = "gl_params", .renderer_class = RenderEngineGlParams{}}; ApplyCameraConfig(config, &builder_); EXPECT_EQ(scene_graph_->RendererCount(), ++renderer_count); EXPECT_THAT(scene_graph_->GetRendererTypeName(config.renderer_name), testing::EndsWith("RenderEngineGl")); } } } /* Confirms the logic for when a renderer name is successfully used several times. - If a name is reused and the class is specified via parameters, the parameterized spec must come first. */ TEST_F(CameraConfigFunctionsTest, RendererNameReuse) { int renderer_count = 0; auto perform_test = [this, &renderer_count](const auto& parameters, const std::string& name) { CameraConfig config{.renderer_name = name + "_renderer", .renderer_class = parameters, .name = name + "_initial_params_succeeds"}; ApplyCameraConfig(config, &builder_); EXPECT_EQ(scene_graph_->RendererCount(), ++renderer_count); EXPECT_THAT(scene_graph_->GetRendererTypeName(config.renderer_name), testing::EndsWith(name)); // Another camera config using parameters should throw. config.name = name + "_second_params_throws"; DRAKE_EXPECT_THROWS_MESSAGE( ApplyCameraConfig(config, &builder_), ".*Only the first instance of the named renderer can use parameters."); // However, camera config using the same class name is happy. config.name = name + "_class_name_succeeds"; config.renderer_class = name; EXPECT_NO_THROW(ApplyCameraConfig(config, &builder_)); EXPECT_EQ(scene_graph_->RendererCount(), renderer_count); // Using an empty class name means "don't care", so is also happy. config.name = name + "_emtpy_class_name_succeeds"; config.renderer_class = ""; EXPECT_NO_THROW(ApplyCameraConfig(config, &builder_)); EXPECT_EQ(scene_graph_->RendererCount(), renderer_count); // Camera config using the name of a different class is angry. config.name = name + "_wrong_class_name_throws"; config.renderer_class = name == "RenderEngineVtk" ? "RenderEngineGltfClient" : "RenderEngineVtk"; DRAKE_EXPECT_THROWS_MESSAGE( ApplyCameraConfig(config, &builder_), ".*The name is already used with a different type.*."); }; { SCOPED_TRACE("Vtk"); perform_test(RenderEngineVtkParams(), "RenderEngineVtk"); } { SCOPED_TRACE("GltfClient"); perform_test(RenderEngineGltfClientParams(), "RenderEngineGltfClient"); } if (geometry::kHasRenderEngineGl) { SCOPED_TRACE("Gl"); perform_test(RenderEngineGlParams(), "RenderEngineGl"); } } // TODO(SeanCurtis-TRI): We'd like to verify that the .background value is used // when RenderEngineVtk or RenderEngineGl are specified by class name. However, // we don't have any straightforward way to introspect a SceneGraph model // RenderEngine. We can get one from a QueryObject, but that's quite cumbersome. // Solving this problem also empowers solving the problem where we detect that // a set of engine parameters matches the parameters of a previously // instantiated engine, allowing us to relax our "parameters must come only on // the first shared renderer name" rule. // Confirms that all of the parameters in CameraConfig are present in the final // configuration. This excludes the following parameters: // - renderer_name (tested above) // - X_PB.base_frame (tested above) // - rgb, depth, and label (tested above) // - background (short of rendering, there's no easy way to observe this. But // it will be immediately obvious to users who specify this value if it // doesn't propagate.) // - do_compress (there's simply no easy way to observe this.) // TODO(SeanCurtis-TRI): Actually render an image and confirm that, when // compressed, the message size is smaller than for the uncompressed image // and the background color is as expected. TEST_F(CameraConfigFunctionsTest, AllParametersCount) { CameraConfig config = MakeConfig(); // We just need one image type so that we get a sensor; confirm that our // "not default" config file has at least one image enabled. ASSERT_EQ(config.depth || config.rgb || config.label, true); // We want a non-async camera. config.output_delay = 0.0; // Prepare the LCM dictionary, based on the bus name from MakeConfig(). LcmBuses lcm_buses; DRAKE_DEMAND(config.lcm_bus != "default"); DrakeLcm non_default_lcm; lcm_buses.Add(config.lcm_bus, &non_default_lcm); // Add the camera and then read back its properties to confirm. ApplyCameraConfig(config, &builder_, &lcm_buses); const auto& sensor = builder_.GetDowncastSubsystemByName<RgbdSensor>( "rgbd_sensor_test_camera"); const ColorRenderCamera& color = sensor.color_render_camera(); const DepthRenderCamera& depth = sensor.depth_render_camera(); // Camera intrinsics. EXPECT_EQ(color.core().intrinsics().width(), config.width); EXPECT_EQ(depth.core().intrinsics().width(), config.width); EXPECT_EQ(color.core().intrinsics().height(), config.height); EXPECT_EQ(depth.core().intrinsics().height(), config.height); EXPECT_EQ(color.core().intrinsics().focal_x(), config.focal_x()); EXPECT_EQ(depth.core().intrinsics().focal_x(), config.focal_x()); EXPECT_EQ(color.core().intrinsics().focal_y(), config.focal_y()); EXPECT_EQ(depth.core().intrinsics().focal_y(), config.focal_y()); EXPECT_EQ(color.core().intrinsics().center_x(), *config.center_x); EXPECT_EQ(depth.core().intrinsics().center_x(), *config.center_x); EXPECT_EQ(color.core().intrinsics().center_y(), *config.center_y); EXPECT_EQ(depth.core().intrinsics().center_y(), *config.center_y); // Clipping. EXPECT_EQ(color.core().clipping().near(), config.clipping_near); EXPECT_EQ(depth.core().clipping().near(), config.clipping_near); EXPECT_EQ(color.core().clipping().far(), config.clipping_far); EXPECT_EQ(depth.core().clipping().far(), config.clipping_far); // Depth. EXPECT_EQ(depth.depth_range().min_depth(), config.z_near); EXPECT_EQ(depth.depth_range().max_depth(), config.z_far); // Show window. EXPECT_EQ(color.show_window(), config.show_rgb); // Name. EXPECT_THAT(sensor.get_name(), ::testing::HasSubstr(config.name)); // Render engine name. EXPECT_EQ(color.core().renderer_name(), config.renderer_name); EXPECT_EQ(depth.core().renderer_name(), config.renderer_name); // Publishing rate. const auto& publisher = builder_.GetDowncastSubsystemByName<LcmPublisherSystem>( "LcmPublisherSystem(DRAKE_RGBD_CAMERA_IMAGES_test_camera)"); EXPECT_DOUBLE_EQ(publisher.get_publish_period(), 1.0 / config.fps); EXPECT_DOUBLE_EQ(publisher.get_publish_offset(), config.capture_offset); // Publishing destination. const DrakeLcmInterface& actual_lcm = const_cast<LcmPublisherSystem&>(publisher).lcm(); EXPECT_TRUE(&actual_lcm == &non_default_lcm); } // Confirms that the async camera settings are all properly obeyed. TEST_F(CameraConfigFunctionsTest, AsyncCamera) { CameraConfig config; config.name = "test_camera"; config.fps = 10.0; config.capture_offset = 0.002; config.output_delay = 0.03; ApplyCameraConfig(config, &builder_); const auto& sensor = builder_.GetDowncastSubsystemByName<RgbdSensorAsync>( "rgbd_sensor_test_camera"); EXPECT_EQ(sensor.fps(), config.fps); EXPECT_EQ(sensor.capture_offset(), config.capture_offset); EXPECT_EQ(sensor.output_delay(), config.output_delay); const auto& publisher = builder_.GetDowncastSubsystemByName<LcmPublisherSystem>( "LcmPublisherSystem(DRAKE_RGBD_CAMERA_IMAGES_test_camera)"); EXPECT_EQ(publisher.get_publish_period(), 1.0 / config.fps); EXPECT_NEAR(publisher.get_publish_offset(), config.capture_offset + config.output_delay, // TODO(jwnimmer-tri) Once the implementation doesn't need a fudge // factor anymore, we should expect exact equality here. 1e-4); } // The user can pass a plant and scene_graph explicitly. TEST_F(CameraConfigFunctionsTest, SubsystemPointers) { // We'll prove that the arguments are obeyed by using non-standard names, // and checking that nothing throws. plant_->set_name("Is it secret?"); scene_graph_->set_name("Is it safe?"); EXPECT_NO_THROW( ApplyCameraConfig(CameraConfig{}, &builder_, {}, plant_, scene_graph_)); } // Confirms that if only rgb is specified, only rgb is published. TEST_F(CameraConfigFunctionsTest, PublishingRgb) { CameraConfig config = MakeConfig(); config.lcm_bus = "default"; config.rgb = true; config.depth = false; config.label = false; ApplyCameraConfig(config, &builder_); // Check image ports. const auto& images = builder_.GetDowncastSubsystemByName<ImageToLcmImageArrayT>( "image_to_lcm_test_camera"); EXPECT_THROW(images.GetInputPort("label"), std::exception); EXPECT_THROW(images.GetInputPort("depth"), std::exception); EXPECT_NO_THROW(images.GetInputPort("rgb")); } // Confirms that if only depth is specified, only depth is published. TEST_F(CameraConfigFunctionsTest, PublishingDepth) { CameraConfig config = MakeConfig(); config.lcm_bus = "default"; config.rgb = false; config.depth = true; config.label = false; ApplyCameraConfig(config, &builder_); // Check image ports. const auto& images = builder_.GetDowncastSubsystemByName<ImageToLcmImageArrayT>( "image_to_lcm_test_camera"); EXPECT_THROW(images.GetInputPort("label"), std::exception); EXPECT_NO_THROW(images.GetInputPort("depth")); EXPECT_THROW(images.GetInputPort("rgb"), std::exception); } // Confirms that if only label is specified, only label is published. TEST_F(CameraConfigFunctionsTest, PublishingLabel) { CameraConfig config = MakeConfig(); config.lcm_bus = "default"; config.rgb = false; config.depth = false; config.label = true; ApplyCameraConfig(config, &builder_); // Check image ports. const auto& images = builder_.GetDowncastSubsystemByName<ImageToLcmImageArrayT>( "image_to_lcm_test_camera"); EXPECT_NO_THROW(images.GetInputPort("label")); EXPECT_THROW(images.GetInputPort("depth"), std::exception); EXPECT_THROW(images.GetInputPort("rgb"), std::exception); } // Confirms that if all the image types are specified, all are published. TEST_F(CameraConfigFunctionsTest, PublishingRgbDepthAndLabel) { CameraConfig config = MakeConfig(); config.lcm_bus = "default"; config.rgb = true; config.depth = true; config.label = true; ApplyCameraConfig(config, &builder_); // Rgb and depth ports. const auto& images = builder_.GetDowncastSubsystemByName<ImageToLcmImageArrayT>( "image_to_lcm_test_camera"); EXPECT_NO_THROW(images.GetInputPort("label")); EXPECT_NO_THROW(images.GetInputPort("depth")); EXPECT_NO_THROW(images.GetInputPort("rgb")); } // ApplyCameraConfig doesn't have its own validation logic, but it is // responsible for invoking validation logic. Smoke test to show that validation // is happening -- a bad config causes the function to throw. TEST_F(CameraConfigFunctionsTest, Validation) { CameraConfig config = MakeConfig(); config.fps = -10; EXPECT_THROW(ApplyCameraConfig(config, &builder_), std::exception); } // When the user requests a non-standard LCM bus, it is an error to omit an // LcmBuses object from the argument list. TEST_F(CameraConfigFunctionsTest, BadLcmBus) { CameraConfig config; config.lcm_bus = "special_request"; DRAKE_EXPECT_THROWS_MESSAGE(ApplyCameraConfig(config, &builder_), ".*non-default.*special_request.*"); } // The user can opt-out of LCM, in which case only the camera system is added. // LcmBuses object from the argument list. TEST_F(CameraConfigFunctionsTest, NullLcmBus) { LcmBuses lcm_buses; DrakeLcm default_lcm(LcmBuses::kLcmUrlMemqNull); lcm_buses.Add("default", &default_lcm); // Add the camera (only). const CameraConfig config; ApplyCameraConfig(config, &builder_, &lcm_buses); // Check that no LCM-related objects are created. for (const auto* system : builder_.GetSystems()) { const std::string& name = system->get_name(); // Allow the MbP basics. if (name == "plant" || name == "scene_graph") { continue; } // Allow the camera itself. if (name == "rgbd_sensor_preview_camera") { continue; } GTEST_FAIL() << name << " should not exist in the diagram"; } } // Confirms that the render engine implementation follows the requested type // (when supported). We already know that the config gets validated, so we // don't need to test cases where an invalid renderer_class value is passed. // However, we do have to worry about requesting RenderEngineGl when it isn't // available. TEST_F(CameraConfigFunctionsTest, RenderEngineRequest) { // Unspecified class produces RenderEngineVtk. const CameraConfig default_config{.renderer_name = "default"}; ASSERT_FALSE(scene_graph_->HasRenderer(default_config.renderer_name)); ApplyCameraConfig(default_config, &builder_); ASSERT_EQ(NiceTypeName::RemoveNamespaces(scene_graph_->GetRendererTypeName( default_config.renderer_name)), "RenderEngineVtk"); // Explicitly specifying *new* VTK class produces VTK render engine. const CameraConfig vtk_config{.renderer_name = "vtk_renderer", .renderer_class = "RenderEngineVtk"}; ASSERT_FALSE(scene_graph_->HasRenderer(vtk_config.renderer_name)); ApplyCameraConfig(vtk_config, &builder_); ASSERT_EQ(NiceTypeName::RemoveNamespaces( scene_graph_->GetRendererTypeName(vtk_config.renderer_name)), "RenderEngineVtk"); // Specifying the same config again should not produce a new render engine. int current_renderer_count = scene_graph_->RendererCount(); ApplyCameraConfig(vtk_config, &builder_); EXPECT_EQ(current_renderer_count, scene_graph_->RendererCount()); // Using an existing name but the wrong render engine type throws. DRAKE_EXPECT_THROWS_MESSAGE( ApplyCameraConfig( CameraConfig{.renderer_name = default_config.renderer_name, .renderer_class = "RenderEngineGl"}, &builder_), ".*The name is already used with a different type.+"); // Now explicitly request a new RenderEngineGl -- whether it throws depends // on whether GL is available. const CameraConfig gl_config{.renderer_name = "gl_renderer", .renderer_class = "RenderEngineGl"}; if (geometry::kHasRenderEngineGl) { ASSERT_FALSE(scene_graph_->HasRenderer(gl_config.renderer_name)); ApplyCameraConfig(gl_config, &builder_); ASSERT_EQ(NiceTypeName::RemoveNamespaces( scene_graph_->GetRendererTypeName(gl_config.renderer_name)), "RenderEngineGl"); } else { DRAKE_EXPECT_THROWS_MESSAGE(ApplyCameraConfig(gl_config, &builder_), ".*'RenderEngineGl' is not supported.*"); } } } // namespace } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/image_io_test.cc
#include "drake/systems/sensors/image_io.h" #include <fstream> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/eigen_types.h" #include "drake/common/find_resource.h" #include "drake/common/never_destroyed.h" #include "drake/common/temp_directory.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/systems/sensors/test/image_io_test_params.h" #include "drake/systems/sensors/test_utilities/image_compare.h" namespace drake { namespace systems { namespace sensors { namespace internal { namespace { namespace fs = std::filesystem; fs::path GetTempPath(std::string_view filename) { static const never_destroyed<std::string> dir{temp_directory()}; return fs::path(dir.access()) / filename; } class ImageIoParameterizedTest : public testing::TestWithParam<ImageIoTestParams> { public: ImageIoParameterizedTest() = default; }; // Runs Save() and Load() back to back. This provides a simple sanity check. TEST_P(ImageIoParameterizedTest, RoundTrip) { const ImageIoTestParams& param = GetParam(); const ImageFileFormat format = param.format; const bool write_to_file = param.write_to_file; // Create a sample image. const ImageAny original = param.CreateIotaDrakeImage(); const int total_storage = param.total_storage(); // Call Save() then Load() back to back. ImageAny readback; if (write_to_file) { fs::path path = GetTempPath(fmt::format("RoundTrip_{}.image", format)); std::visit( [&](const auto& image) { ImageIo{}.Save(image, path, format); }, original); readback = ImageIo{}.Load(path, format); } else { const std::vector<uint8_t> buffer = std::visit( [&](const auto& image) { return ImageIo{}.Save(image, format); }, original); const ImageIo::ByteSpan span{buffer.data(), buffer.size()}; readback = ImageIo{}.Load(span, format); } // The PixelType must remain intact across the Save + Load. ASSERT_EQ(original.index(), readback.index()); // The number of pixels must remain intact across the Save + Load. const int readback_size = std::visit( [&](const auto& image) { return image.size(); }, readback); ASSERT_EQ(readback_size, total_storage); // Compare the full pixel array for the two images. const void* const original_buffer = std::visit( [&](const auto& image) { const void* buffer = image.at(0, 0); return buffer; }, original); const void* const readback_buffer = std::visit( [&](const auto& image) { const void* buffer = image.at(0, 0); return buffer; }, readback); param.CompareImageBuffer(original_buffer, readback_buffer); } // Sanity check that Load() can fill in an image pointer. TEST_P(ImageIoParameterizedTest, RoundTripPreAllocated) { const ImageIoTestParams& param = GetParam(); if (!param.write_to_file) { // Not much is gained from running this test case on both memory buffers as // well as files. Simplify our life by skipping the memory buffer cases. return; } const ImageFileFormat format = param.format; // Create a sample image. const ImageAny original = param.CreateIotaDrakeImage(); // Call Save(). const fs::path path = GetTempPath(fmt::format("RoundTripPreAllocated_{}.image", format)); std::visit( [&](const auto& image) { ImageIo{}.Save(image, path, format); }, original); // Pre-allocate the readback image (filled with zeros). ImageAny readback = std::visit( [&](const auto& image) { using SomeImage = decltype(image); return ImageAny{SomeImage{}}; }, original); DRAKE_DEMAND(original.index() == readback.index()); // Call Load(); std::visit( [&](auto& image) { ImageIo{}.Load(path, format, &image); }, readback); // The PixelType should have remained intact. EXPECT_EQ(original.index(), readback.index()); // The readback should have non-zero contents. std::visit( [&](auto& image) { const int readback_width = image.width(); const int readback_height = image.height(); const int readback_size = image.size(); EXPECT_EQ(readback_width, param.width()); EXPECT_EQ(readback_height, param.height()); if (readback_size > 0) { EXPECT_NE(image.at(0, 0)[readback_size - 1], 0); } }, readback); } INSTANTIATE_TEST_SUITE_P(All, ImageIoParameterizedTest, GetAllImageIoTestParams()); // We can save to an output memory buffer, or a buffer return value. GTEST_TEST(ImageIoTest, SaveToOutputArgumentMatchesReturnValue) { const auto format = ImageFileFormat::kPng; const ImageRgba8U image(1, 1); std::vector<uint8_t> save_output; ImageIo{}.Save(image, format, &save_output); EXPECT_EQ(save_output, ImageIo{}.Save(image, format)); } // Saving without an ImageFileFormat uses the extension to infer the format. GTEST_TEST(ImageIoTest, SaveToFileInfersFormat) { const ImageRgba8U image(1, 1); fs::path path; ImageFileFormat expected; expected = ImageFileFormat::kPng; path = GetTempPath("SaveToFileInfersFormat.png"); ImageIo{}.Save(image, path); EXPECT_EQ(ImageIo{}.LoadMetadata(path).value().format, expected); expected = ImageFileFormat::kJpeg; path = GetTempPath("SaveToFileInfersFormat.jpg"); ImageIo{}.Save(image, path); EXPECT_EQ(ImageIo{}.LoadMetadata(path).value().format, expected); } // Saving without an ImageFileFormat fails when there is no extension. GTEST_TEST(ImageIoTest, SaveToFileNoExensionNoFormatError) { const ImageRgba8U image(1, 1); const fs::path path = GetTempPath("SaveToFileNoExensionNoFormatError"); DRAKE_EXPECT_THROWS_MESSAGE(ImageIo{}.Save(image, path), ".*path does not imply.*"); } // We can load metadata from a memory buffer. GTEST_TEST(ImageIoTest, LoadMetdataBuffer) { std::vector<uint8_t> saved; ImageIo{}.Save(ImageRgba8U(3, 2), ImageFileFormat::kPng, &saved); const ImageIo::ByteSpan buffer{saved.data(), saved.size()}; const std::optional<ImageIo::Metadata> meta = ImageIo{}.LoadMetadata(buffer); ASSERT_TRUE(meta.has_value()); EXPECT_EQ(meta->format, ImageFileFormat::kPng); EXPECT_EQ(meta->width, 3); EXPECT_EQ(meta->height, 2); } // Loading from a missing path fails. GTEST_TEST(ImageIoTest, LoadNoSuchFileError) { const fs::path path = GetTempPath("LoadNoSuchFileError.png"); EXPECT_EQ(ImageIo{}.LoadMetadata(path), std::nullopt); DRAKE_EXPECT_THROWS_MESSAGE(ImageIo{}.Load(path), ".*LoadNoSuchFileError.*open.*"); } // Loading a non-image file fails. GTEST_TEST(ImageIoTest, LoadNotAnImageError) { const fs::path path = GetTempPath("LoadNotAnImageError.png"); { std::ofstream out(path); out << "Hello\n"; } EXPECT_EQ(ImageIo{}.LoadMetadata(path), std::nullopt); DRAKE_EXPECT_THROWS_MESSAGE(ImageIo{}.Load(path), ".*LoadNotAnImageError.*header.*"); } // Loading into the wrong pre-allocated Image scalar type fails. GTEST_TEST(ImageIoTest, LoadWrongPrealloatedScalarError) { const std::vector<uint8_t> saved = ImageIo{}.Save(ImageDepth16U(1, 1), ImageFileFormat::kPng); const ImageIo::ByteSpan buffer{saved.data(), saved.size()}; ImageRgba8U color; DRAKE_EXPECT_THROWS_MESSAGE(ImageIo{}.Load(buffer, &color), ".*scalar=16U into scalar=8U.*"); } // Loading into the wrong pre-allocated Image number of channels fails. GTEST_TEST(ImageIoTest, LoadWrongPrealloatedNumChannelsError) { const std::vector<uint8_t> saved = ImageIo{}.Save(ImageGrey8U(1, 1), ImageFileFormat::kPng); const ImageIo::ByteSpan buffer{saved.data(), saved.size()}; ImageRgb8U rgb; DRAKE_EXPECT_THROWS_MESSAGE(ImageIo{}.Load(buffer, &rgb), ".*channels=1.*channels=3.*"); } // Loading an RGB image with 16-bit channels is not supported, because there is // no Image<> template defined to meet that case. GTEST_TEST(ImageIoTest, LoadUnsupportedChannelScalarError) { const fs::path path{ FindResourceOrThrow("drake/systems/sensors/test/png_color16_test.png")}; DRAKE_EXPECT_THROWS_MESSAGE(ImageIo{}.Load(path, ImageFileFormat::kPng), ".*template instantiation.*"); } GTEST_TEST(ImageIoTest, LoadUnsupportedColorTiffError) { const fs::path path{ FindResourceOrThrow("drake/systems/sensors/test/tiff_rgb32f_test.tif")}; DRAKE_EXPECT_THROWS_MESSAGE(ImageIo{}.Load(path, ImageFileFormat::kTiff), ".*template instantiation.*"); ImageRgba8U color; DRAKE_EXPECT_THROWS_MESSAGE(ImageIo{}.Load(path, &color), ".*scalar=32F into scalar=8U.*"); } // For legacy reasons, we allow type-punning from unsigned 16-bit image data // into Drake's signed 16-bit image channel. We intend to eventually deprecate // and remove this (by fixing our label images to use unsigned numbers) but for // now we need to ensure this capability remains intact. GTEST_TEST(ImageIoTest, Load16UDataAs16I) { const auto format = ImageFileFormat::kPng; const ImageDepth16U depth(1, 1, uint16_t{22}); const std::vector<uint8_t> saved = ImageIo{}.Save(depth, format); const ImageIo::ByteSpan buffer{saved.data(), saved.size()}; ImageLabel16I label; ImageIo{}.Load(buffer, format, &label); ASSERT_EQ(label.width(), 1); ASSERT_EQ(label.height(), 1); ASSERT_EQ(label.at(0, 0)[0], 22); } // Loading can automatically drop an unwanted alpha channel. GTEST_TEST(ImageIoTest, LoadDropAlpha) { const auto format = ImageFileFormat::kPng; const ImageRgba8U rgba(3, 2, uint8_t{22}); const std::vector<uint8_t> saved = ImageIo{}.Save(rgba, format); const ImageIo::ByteSpan buffer{saved.data(), saved.size()}; ImageRgb8U rgb; ImageIo{}.Load(buffer, format, &rgb); ASSERT_EQ(rgb.width(), 3); ASSERT_EQ(rgb.height(), 2); EXPECT_EQ(rgb.at(0, 0)[0], 22); } // Loading can automatically add a alpha channel. GTEST_TEST(ImageIoTest, LoadAddAlpha) { const auto format = ImageFileFormat::kPng; const ImageRgb8U rgb(3, 2, uint8_t{22}); const std::vector<uint8_t> saved = ImageIo{}.Save(rgb, format); const ImageIo::ByteSpan buffer{saved.data(), saved.size()}; ImageRgba8U rgba; ImageIo{}.Load(buffer, format, &rgba); ASSERT_EQ(rgba.width(), 3); ASSERT_EQ(rgba.height(), 2); EXPECT_EQ(rgba.at(0, 0)[0], 22); EXPECT_EQ(rgba.at(0, 0)[3], 0xff); } } // namespace } // namespace internal } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/image_writer_test.cc
#include "drake/systems/sensors/image_writer.h" #include <unistd.h> #include <filesystem> #include <fstream> #include <set> #include <string> #include <gtest/gtest.h> #include "drake/common/drake_copyable.h" #include "drake/common/temp_directory.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/systems/framework/event_collection.h" #include "drake/systems/sensors/test_utilities/image_compare.h" namespace drake { namespace systems { namespace sensors { namespace fs = std::filesystem; // Friend class to get access to ImageWriter private functions for testing. class ImageWriterTester { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ImageWriterTester) explicit ImageWriterTester(const ImageWriter& writer) : writer_(writer) {} std::string DirectoryFromFormat(const std::string& format, const std::string& port_name, PixelType pixel_type) const { return writer_.DirectoryFromFormat(format, port_name, pixel_type); } static bool IsDirectoryValid(const std::string& file_path) { return ImageWriter::ValidateDirectory(file_path) == ImageWriter::FolderState::kValid; } static bool DirectoryIsMissing(const std::string& file_path) { return ImageWriter::ValidateDirectory(file_path) == ImageWriter::FolderState::kMissing; } static bool DirectoryIsFile(const std::string& file_path) { return ImageWriter::ValidateDirectory(file_path) == ImageWriter::FolderState::kIsFile; } static bool DirectoryIsUnwritable(const std::string& file_path) { return ImageWriter::ValidateDirectory(file_path) == ImageWriter::FolderState::kUnwritable; } std::string MakeFileName(const std::string& format, PixelType pixel_type, double time, const std::string& port_name, int count) const { return writer_.MakeFileName(format, pixel_type, time, port_name, count); } const std::string& port_format(int port_index) const { return writer_.port_info_[port_index].format; } int port_count(int port_index) const { return writer_.port_info_[port_index].count; } const std::string& label(PixelType pixel_type) const { return writer_.labels_.at(pixel_type); } const std::string& extension(PixelType pixel_type) const { return writer_.extensions_.at(pixel_type); } private: const ImageWriter& writer_; }; namespace { // Utility functions for creating test, reference images template <PixelType kPixelType> static Image<kPixelType> test_image() { throw std::logic_error("No default implementation"); } template <> Image<PixelType::kRgba8U> test_image() { // Creates a simple 4x1 image consisting of: [red][green][blue][white]. Image<PixelType::kRgba8U> color_image(4, 1); auto set_color = [&color_image](int x, int y, uint8_t r, uint8_t g, uint8_t b) { color_image.at(x, y)[0] = r; color_image.at(x, y)[1] = g; color_image.at(x, y)[2] = b; color_image.at(x, y)[3] = 255; }; set_color(0, 0, 255, 0, 0); set_color(1, 0, 0, 255, 0); set_color(2, 0, 0, 0, 255); set_color(3, 0, 255, 255, 255); return color_image; } template <> Image<PixelType::kDepth32F> test_image() { // Creates a simple 4x1 image consisting of: 0, 0.25, 0.5, 0.75 Image<PixelType::kDepth32F> depth_image(4, 1); *depth_image.at(0, 0) = 0.0f; *depth_image.at(1, 0) = 0.25f; *depth_image.at(2, 0) = 0.5f; *depth_image.at(3, 0) = 1.0f; return depth_image; } template <> Image<PixelType::kLabel16I> test_image() { // Creates a simple 4x1 image consisting of: 0, 100, 200, 300. Image<PixelType::kLabel16I> label_image(4, 1); *label_image.at(0, 0) = 0; *label_image.at(1, 0) = 100; *label_image.at(2, 0) = 200; // Note: value > 255 to make sure that values aren't being truncated/wrapped // to 8-bit values. *label_image.at(3, 0) = 300; return label_image; } template <> Image<PixelType::kDepth16U> test_image() { // Creates a simple 4x1 image consisting of: 0, 100, 200, 300. Image<PixelType::kDepth16U> depth_image(4, 1); *depth_image.at(0, 0) = 0; *depth_image.at(1, 0) = 100; *depth_image.at(2, 0) = 200; // Note: value > 255 to make sure that values aren't being truncated/wrapped // to 8-bit values. *depth_image.at(3, 0) = 300; return depth_image; } template <> Image<PixelType::kGrey8U> test_image() { // Creates a simple 4x1 image consisting of: 1, 2, 3, 4. Image<PixelType::kGrey8U> grey_imageimage(4, 1); *grey_imageimage.at(0, 0) = 1; *grey_imageimage.at(1, 0) = 2; *grey_imageimage.at(2, 0) = 3; *grey_imageimage.at(3, 0) = 4; return grey_imageimage; } // Class for testing actual I/O work. This helps manage generated files by // facilitating temporary file names and registering additional names so that // they can be cleaned up at the conclusion of the tests. class ImageWriterTest : public ::testing::Test { public: static void SetUpTestCase() { ASSERT_TRUE(ImageWriterTester::IsDirectoryValid(temp_dir())); } static void TearDownTestCase() { for (const auto& file_name : files_) { if (fs::exists({file_name})) { // We'll consider a failure to delete a temporary file as a test // failure. unlink(file_name.c_str()); EXPECT_FALSE(fs::exists({file_name})) << "Failed to delete temporary test file: " << file_name; } } } // This assumes that the temp_directory() API will *always* return the same // name during the execution of this test. static std::string temp_dir() { return temp_directory(); } // Returns a unique temporary image name - every requested name will be // examined at tear down for deletion. When it comes to writing images, all // names should come from here. static std::string temp_name() { fs::path temp_path; do { temp_path = temp_dir(); temp_path.append("image_writer_test_" + std::to_string(++img_count_) + ".png"); } while (fs::exists(temp_path)); files_.insert(temp_path.string()); return temp_path.string(); } // Arbitrary files that are generated can be added to the set of files that // require clean up. This should be invoked for _every_ file generated in this // test suite. static void add_file_for_cleanup(const std::string& file_name) { files_.insert(file_name); } template <PixelType kPixelType> static void TestWritingImageOnPort() { ImageWriter writer; ImageWriterTester tester(writer); // Values for port declaration. const double period = 1 / 10.0; // 10 Hz. const double start_time = 0.25; const std::string port_name = "port"; fs::path path(temp_dir()); path.append("{image_type}_{time_usec}"); Image<kPixelType> image = test_image<kPixelType>(); const auto& port = writer.DeclareImageInputPort<kPixelType>( port_name, path.string(), period, start_time); auto events = writer.AllocateCompositeEventCollection(); auto context = writer.AllocateContext(); port.FixValue(context.get(), image); context->SetTime(0.); writer.CalcNextUpdateTime(*context, events.get()); const std::string expected_name = tester.MakeFileName( tester.port_format(port.get_index()), kPixelType, context->get_time(), port_name, tester.port_count(port.get_index())); fs::path expected_file(expected_name); EXPECT_FALSE(fs::exists(expected_file)); const EventStatus status = writer.Publish(*context, events->get_publish_events()); EXPECT_TRUE(status.succeeded()); EXPECT_TRUE(fs::exists(expected_file)); EXPECT_EQ(1, tester.port_count(port.get_index())); add_file_for_cleanup(expected_file.string()); Image<kPixelType> readback; ASSERT_TRUE(LoadImage(expected_name, &readback)); EXPECT_EQ(readback, image); } private: // NOTE: These are static so that they are shared across the entire test // suite. This allows all tests to have non-conflicting names *and* get // cleaned up when the test suite shuts down. // This presumes the tests in a single test case do *not* run in parallel. static int img_count_; // Files that may need to be cleaned up. It _must_ include every file that has // been created by these tests but *may* include purely speculative file // names. static std::set<std::string> files_; }; int ImageWriterTest::img_count_{-1}; std::set<std::string> ImageWriterTest::files_; // ImageWriter contains a number of mappings between pixel type and work strings // (extensions and image_type values for format args, this confirms that they // are mapped correctly. TEST_F(ImageWriterTest, ImageToStringMaps) { ImageWriter writer; ImageWriterTester tester(writer); EXPECT_EQ("color", tester.label(PixelType::kRgba8U)); EXPECT_EQ("label", tester.label(PixelType::kLabel16I)); EXPECT_EQ("depth", tester.label(PixelType::kDepth32F)); EXPECT_EQ("depth", tester.label(PixelType::kDepth16U)); EXPECT_EQ("grey_scale", tester.label(PixelType::kGrey8U)); EXPECT_EQ(".png", tester.extension(PixelType::kRgba8U)); EXPECT_EQ(".png", tester.extension(PixelType::kLabel16I)); EXPECT_EQ(".tiff", tester.extension(PixelType::kDepth32F)); EXPECT_EQ(".png", tester.extension(PixelType::kDepth16U)); EXPECT_EQ(".png", tester.extension(PixelType::kGrey8U)); } // Tests the processing of file format for extracting the directory. TEST_F(ImageWriterTest, DirectoryFromFormat) { ImageWriter writer; ImageWriterTester tester{writer}; DRAKE_EXPECT_THROWS_MESSAGE( tester.DirectoryFromFormat("", "port_name", PixelType::kRgba8U), ".*empty.*"); EXPECT_EQ( "", tester.DirectoryFromFormat("/root", "port_name", PixelType::kRgba8U)); DRAKE_EXPECT_THROWS_MESSAGE( tester.DirectoryFromFormat("/root/", "port_name", PixelType::kRgba8U), ".*cannot end with a '/'"); EXPECT_EQ("/root", tester.DirectoryFromFormat("/root/file", "port_name", PixelType::kRgba8U)); // Don't use all three image types; the FileNameFormatting test already // tests those permutations. We just want to make sure it's engaged here. EXPECT_EQ("/root/color", tester.DirectoryFromFormat("/root/{image_type}/file", "port_name", PixelType::kRgba8U)); EXPECT_EQ("/root/my_port", tester.DirectoryFromFormat("/root/{port_name}/file", "my_port", PixelType::kRgba8U)); // Test against invalid formatting arguments. DRAKE_EXPECT_THROWS_MESSAGE( tester.DirectoryFromFormat("/root/{count}/file", "port", PixelType::kRgba8U), ".*The directory path cannot include time or image count"); DRAKE_EXPECT_THROWS_MESSAGE( tester.DirectoryFromFormat("/root/{time_double}/file", "port", PixelType::kRgba8U), ".*The directory path cannot include time or image count"); DRAKE_EXPECT_THROWS_MESSAGE( tester.DirectoryFromFormat("/root/{time_usec}/file", "port", PixelType::kRgba8U), ".*The directory path cannot include time or image count"); DRAKE_EXPECT_THROWS_MESSAGE( tester.DirectoryFromFormat("/root/{time_msec}/file", "port", PixelType::kRgba8U), ".*The directory path cannot include time or image count"); // Make sure it's not fooled by strings that are *almost* format arguments. EXPECT_EQ("/root/time_double", tester.DirectoryFromFormat("/root/time_double/file", "my_port", PixelType::kRgba8U)); EXPECT_EQ("/root/time_usec", tester.DirectoryFromFormat("/root/time_usec/file", "my_port", PixelType::kRgba8U)); EXPECT_EQ("/root/time_msec", tester.DirectoryFromFormat("/root/time_msec/file", "my_port", PixelType::kRgba8U)); EXPECT_EQ("/root/count", tester.DirectoryFromFormat("/root/count/file", "my_port", PixelType::kRgba8U)); } // Tests the logic for formatting images. TEST_F(ImageWriterTest, FileNameFormatting) { auto test_file_name = [](const ImageWriter& writer, const std::string& format, PixelType pixel_type, double time, const std::string& port_name, int count, const std::string expected) { const std::string path = ImageWriterTester(writer).MakeFileName( format, pixel_type, time, port_name, count); EXPECT_EQ(path, expected); }; ImageWriter writer; // Completely hard-coded; not dependent on any of ImageWriter's baked values. test_file_name(writer, "/hard/coded/file.png", PixelType::kRgba8U, 0, "port", 0, "/hard/coded/file.png"); // Use the port name. test_file_name(writer, "/hard/{port_name}/file.png", PixelType::kRgba8U, 0, "port", 0, "/hard/port/file.png"); // Use the image type. test_file_name(writer, "/hard/{image_type}/file.png", PixelType::kRgba8U, 0, "port", 0, "/hard/color/file.png"); test_file_name(writer, "/hard/{image_type}/file.png", PixelType::kDepth32F, 0, "port", 0, "/hard/depth/file.png"); test_file_name(writer, "/hard/{image_type}/file.png", PixelType::kLabel16I, 0, "port", 0, "/hard/label/file.png"); // Use the time values. test_file_name(writer, "/hard/{time_double:.2f}.png", PixelType::kRgba8U, 0, "port", 0, "/hard/0.00.png"); test_file_name(writer, "/hard/{time_double:.2f}.png", PixelType::kRgba8U, 1.111, "port", 0, "/hard/1.11.png"); test_file_name(writer, "/hard/{time_double:.2f}.png", PixelType::kRgba8U, 1.116, "port", 0, "/hard/1.12.png"); test_file_name(writer, "/hard/{time_usec:03}.png", PixelType::kRgba8U, 0, "port", 0, "/hard/000.png"); test_file_name(writer, "/hard/{time_usec:03}.png", PixelType::kRgba8U, 1.111, "port", 0, "/hard/1111000.png"); test_file_name(writer, "/hard/{time_msec:03}.png", PixelType::kRgba8U, 0, "port", 0, "/hard/000.png"); test_file_name(writer, "/hard/{time_msec:03}.png", PixelType::kRgba8U, 1.111, "port", 0, "/hard/1111.png"); // Use the count value. test_file_name(writer, "/hard/{count:03}.png", PixelType::kRgba8U, 1.111, "port", 0, "/hard/000.png"); test_file_name(writer, "/hard/{count:03}.png", PixelType::kRgba8U, 1.111, "port", 12, "/hard/012.png"); // Bad place holders. EXPECT_THROW( test_file_name(writer, "/hard/{port}/file.png", PixelType::kRgba8U, 0, "port", 0, "/hard/{port}/file.png"), fmt::format_error); } // Tests the write-ability of an image writer based on the validity of the // directory path. TEST_F(ImageWriterTest, ValidateDirectory) { // Case: Non-existent directory. EXPECT_TRUE( ImageWriterTester::DirectoryIsMissing("this/path/does/not_exist")); // Case: No write permissions (assuming that this isn't run as root). fs::path path(temp_dir()); path.append("unwritable"); fs::create_directory(path); fs::permissions(path, fs::perms::owner_write, fs::perm_options::remove); EXPECT_TRUE(ImageWriterTester::DirectoryIsUnwritable(path)); // Case: the path is to a file. const std::string file_name = temp_name(); std::ofstream stream(file_name, std::ios::out); ASSERT_FALSE(stream.fail()); EXPECT_TRUE(ImageWriterTester::DirectoryIsFile(file_name)); } // Confirm behavior on documented errors in TEST_F(ImageWriterTest, ConfigureInputPortErrors) { ImageWriter writer; // Bad publish period. DRAKE_EXPECT_THROWS_MESSAGE(writer.DeclareImageInputPort<PixelType::kRgba8U>( "port", "format", -0.1, 0), ".* publish period must be positive"); // Invalid directory -- relies on tested correctness of ValidateDirectory() // and simply uses _one_ of the mechanisms for implying an invalid folder. DRAKE_EXPECT_THROWS_MESSAGE( writer.DeclareImageInputPort<PixelType::kRgba8U>("port", "/root/name", 0.1, 0), ".*The format string .* implied the invalid directory.*"); // Now test a port with the same name -- can only happen if one port has // been successfully declared. fs::path path(temp_dir()); path.append("file_{count:3}"); const auto& port = writer.DeclareImageInputPort<PixelType::kRgba8U>( "port", path.string(), 0.1, 0); EXPECT_EQ(0, port.get_index()); { auto events = writer.AllocateCompositeEventCollection(); auto context = writer.AllocateContext(); writer.CalcNextUpdateTime(*context, events.get()); EXPECT_TRUE(events->HasEvents()); } fs::path path2(temp_dir()); path2.append("alt_file_{count:3}"); DRAKE_EXPECT_THROWS_MESSAGE(writer.DeclareImageInputPort<PixelType::kRgba8U>( "port", path2.string(), 0.1, 0), "System .* already has an input port named .*"); } // Helper function for testing port declaration with a runtime pixel type. template <PixelType kPixelType> void TestRuntimePixelType() { ImageWriter writer; const auto& port = writer.DeclareImageInputPort(kPixelType, "in", "/tmp/{time_usec}", 1, 1); EXPECT_EQ(port.Allocate()->static_type_info(), typeid(Image<kPixelType>)); } // This tests that the runtime pixel types are passed through correctly. TEST_F(ImageWriterTest, RuntimePixelType) { TestRuntimePixelType<PixelType::kRgba8U>(); TestRuntimePixelType<PixelType::kLabel16I>(); TestRuntimePixelType<PixelType::kDepth32F>(); TestRuntimePixelType<PixelType::kDepth16U>(); TestRuntimePixelType<PixelType::kGrey8U>(); } // Helper function for testing the extension produced for a given pixel type. template <PixelType kPixelType> void TestPixelExtension(const std::string& folder, ImageWriter* writer, int* count) { using std::to_string; ImageWriterTester tester(*writer); fs::path format(folder); format.append("file"); const auto& port = writer->DeclareImageInputPort<kPixelType>( "port" + to_string(++(*count)), format.string(), 1, 1); const std::string& final_format = tester.port_format(port.get_index()); EXPECT_NE(format.string(), final_format); const std::string& ext = tester.extension(kPixelType); EXPECT_EQ(ext, final_format.substr(final_format.size() - ext.size())); } // This tests that format strings pick up the appropriate extension based on // image type. TEST_F(ImageWriterTest, FileExtension) { using std::to_string; ImageWriter writer; int count = 0; // Case: each image type applies the right extension to an extension-less // format string. TestPixelExtension<PixelType::kRgba8U>(temp_dir(), &writer, &count); TestPixelExtension<PixelType::kLabel16I>(temp_dir(), &writer, &count); TestPixelExtension<PixelType::kDepth32F>(temp_dir(), &writer, &count); TestPixelExtension<PixelType::kDepth16U>(temp_dir(), &writer, &count); TestPixelExtension<PixelType::kGrey8U>(temp_dir(), &writer, &count); ImageWriterTester tester(writer); // Case: Format string with correct extension remains unchanged. { fs::path format(temp_dir()); format.append("file.png"); const auto& port = writer.DeclareImageInputPort<PixelType::kRgba8U>( "port" + to_string(++count), format.string(), 1, 1); const std::string& final_format = tester.port_format(port.get_index()); EXPECT_EQ(format.string(), final_format); } // Case: wrong extension gets correct extension appended. { fs::path format(temp_dir()); format.append("file.txt"); const auto& port = writer.DeclareImageInputPort<PixelType::kRgba8U>( "port" + to_string(++count), format.string(), 1, 1); const std::string& final_format = tester.port_format(port.get_index()); const std::string& ext = tester.extension(PixelType::kRgba8U); EXPECT_EQ(format.string() + ext, final_format); } } // Probes the correctness of a single declared port. TEST_F(ImageWriterTest, SingleConfiguredPort) { ImageWriter writer; ImageWriterTester tester(writer); // Freshly constructed, the writer has no timed events. { auto events = writer.AllocateCompositeEventCollection(); auto context = writer.AllocateContext(); writer.CalcNextUpdateTime(*context, events.get()); EXPECT_FALSE(events->HasEvents()); } // Values for port declaration. const double period = 1 / 10.0; // 10 Hz. const double start_time = 0.25; const std::string port_name{"single_color_port"}; const PixelType pixel_type = PixelType::kRgba8U; fs::path path(temp_dir()); path.append("single_port_{time_usec}"); const auto& port = writer.DeclareImageInputPort<PixelType::kRgba8U>( port_name, path.string(), period, start_time); // Count gets properly initialized to zero (no images written from this port). EXPECT_EQ(0, tester.port_count(port.get_index())); // Confirm a reported periodic event and a forced publish event. The // configuration parameters above are called out below in commented lines. { auto events = writer.AllocateCompositeEventCollection(); auto forced_events = writer.AllocateForcedPublishEventCollection(); auto context = writer.AllocateContext(); context->SetTime(0.); double next_time = writer.CalcNextUpdateTime(*context, events.get()); // Confirm start time fed into the periodic event. EXPECT_EQ(start_time, next_time); EXPECT_TRUE(events->HasEvents()); EXPECT_FALSE(events->HasDiscreteUpdateEvents()); EXPECT_FALSE(events->HasUnrestrictedUpdateEvents()); EXPECT_TRUE(events->HasPublishEvents()); EXPECT_TRUE(forced_events->HasEvents()); { const auto& publish_events = dynamic_cast<const LeafEventCollection<PublishEvent<double>>&>( events->get_publish_events()) .get_events(); ASSERT_EQ(1u, publish_events.size()); const auto& event = publish_events.front(); EXPECT_EQ(TriggerType::kPeriodic, event->get_trigger_type()); const auto& forced_publish_events = dynamic_cast<const LeafEventCollection<PublishEvent<double>>&>( *forced_events) .get_events(); // The event collection should have two events: ImageWriter's explicitly // declared event and the collection's built-in no-op event. ASSERT_EQ(2u, forced_publish_events.size()); const auto& forced_event = forced_publish_events.front(); EXPECT_EQ(TriggerType::kForced, forced_event->get_trigger_type()); // With no connection on the input port, publishing this event will result // in an error. DRAKE_EXPECT_THROWS_MESSAGE( writer.Publish(*context, events->get_publish_events()), ".*InputPort.* is not connected"); // Confirms that a valid publish increments the counter. port.FixValue(context.get(), test_image<PixelType::kRgba8U>()); std::string expected_name = tester.MakeFileName( tester.port_format(port.get_index()), pixel_type, context->get_time(), port_name, tester.port_count(port.get_index())); fs::path expected_file(expected_name); EXPECT_FALSE(fs::exists(expected_file)); const EventStatus status = writer.Publish(*context, events->get_publish_events()); EXPECT_TRUE(status.succeeded()); EXPECT_TRUE(fs::exists(expected_file)); EXPECT_EQ(1, tester.port_count(port.get_index())); add_file_for_cleanup(expected_file.string()); // Confirms that a valid forced publish increments the counter and writes // an image. We keep the image saved, so that we can immediately test a // redundant call to ForcedPublish() with the same context. context->SetTime(1e-6); expected_name = tester.MakeFileName( tester.port_format(port.get_index()), pixel_type, context->get_time(), port_name, tester.port_count(port.get_index())); expected_file.assign(expected_name); EXPECT_FALSE(fs::exists(expected_file)); writer.ForcedPublish(*context); EXPECT_TRUE(fs::exists(expected_file)); EXPECT_EQ(2, tester.port_count(port.get_index())); // Confirms that invoking ForcedPublish() a second time simply redundantly // writes the image. writer.ForcedPublish(*context); EXPECT_TRUE(fs::exists(expected_file)); EXPECT_EQ(3, tester.port_count(port.get_index())); add_file_for_cleanup(expected_file.string()); // Confirms resetting count to zero works. writer.ResetAllImageCounts(); EXPECT_EQ(0, tester.port_count(port.get_index())); } // Confirm period is correct. context->SetTime(start_time + 0.1 * period); events->Clear(); next_time = writer.CalcNextUpdateTime(*context, events.get()); EXPECT_EQ(start_time + period, next_time); } } // This simply confirms that the color image gets written to the right format. TEST_F(ImageWriterTest, WritesColorImage) { TestWritingImageOnPort<PixelType::kRgba8U>(); } // This confirms that the label image gets written properly. TEST_F(ImageWriterTest, WritesLabelImage) { TestWritingImageOnPort<PixelType::kLabel16I>(); } // This simply confirms that the depth image gets written to the right format. TEST_F(ImageWriterTest, WritesDepthImage) { TestWritingImageOnPort<PixelType::kDepth32F>(); } // This simply confirms that the depth image gets written to the right format. TEST_F(ImageWriterTest, WritesDepthImage16U) { TestWritingImageOnPort<PixelType::kDepth16U>(); } // This simply confirms that the color image gets written to the right format. TEST_F(ImageWriterTest, WritesGreyImage) { TestWritingImageOnPort<PixelType::kGrey8U>(); } } // namespace } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/rgbd_sensor_async_gl_test.dmd.yaml
directives: - add_model: name: bin file: package://drake_models/manipulation_station/bin.sdf - add_weld: parent: world child: bin::bin_base X_PC: translation: [0, 0, 0.20] - add_model: name: ball_1 file: package://drake_models/manipulation_station/sphere.sdf default_free_body_pose: { base_link: { translation: [0.08, 0.01, 0.3] } } - add_model: name: ball_2 file: package://drake_models/manipulation_station/sphere.sdf default_free_body_pose: { base_link: { translation: [0.07, 0.02, 0.6] } } - add_model: name: ball_3 file: package://drake_models/manipulation_station/sphere.sdf default_free_body_pose: { base_link: { translation: [0.06, 0.03, 0.9] } } - add_model: name: ball_4 file: package://drake_models/manipulation_station/sphere.sdf default_free_body_pose: { base_link: { translation: [0.05, 0.04, 1.2] } } - add_model: name: ball_5 file: package://drake_models/manipulation_station/sphere.sdf default_free_body_pose: { base_link: { translation: [0.04, 0.05, 1.5] } } - add_model: name: ball_6 file: package://drake_models/manipulation_station/sphere.sdf default_free_body_pose: { base_link: { translation: [0.03, 0.06, 1.8] } } - add_model: name: ball_7 file: package://drake_models/manipulation_station/sphere.sdf default_free_body_pose: { base_link: { translation: [0.02, 0.07, 2.1] } } - add_model: name: ball_8 file: package://drake_models/manipulation_station/sphere.sdf default_free_body_pose: { base_link: { translation: [0.01, 0.08, 2.4] } } - add_model: name: ball_9 file: package://drake_models/manipulation_station/sphere.sdf default_free_body_pose: { base_link: { translation: [0.00, 0.09, 2.7] } }
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/rgbd_sensor_test.cc
#include "drake/systems/sensors/rgbd_sensor.h" #include <functional> #include <memory> #include <type_traits> #include <utility> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/geometry/geometry_frame.h" #include "drake/geometry/geometry_state.h" #include "drake/geometry/scene_graph.h" #include "drake/geometry/test_utilities/dummy_render_engine.h" #include "drake/systems/framework/context.h" #include "drake/systems/framework/diagram_builder.h" namespace drake { namespace systems { namespace sensors { using Eigen::AngleAxisd; using Eigen::Vector3d; using geometry::FrameId; using geometry::FramePoseVector; using geometry::GeometryFrame; using geometry::QueryObject; using geometry::SceneGraph; using geometry::SourceId; using geometry::internal::DummyRenderEngine; using geometry::render::ClippingRange; using geometry::render::ColorRenderCamera; using geometry::render::DepthRange; using geometry::render::DepthRenderCamera; using geometry::render::RenderCameraCore; using geometry::render::RenderEngine; using math::RigidTransformd; using math::RollPitchYawd; using std::make_pair; using std::make_unique; using std::unique_ptr; using std::vector; using systems::Context; using systems::Diagram; using systems::DiagramBuilder; std::ostream& operator<<(std::ostream& out, const CameraInfo& info) { out << "\n width: " << info.width() << "\n height: " << info.height() << "\n focal_x: " << info.focal_x() << "\n focal_y: " << info.focal_y() << "\n center_x: " << info.center_x() << "\n center_y: " << info.center_y(); return out; } std::ostream& operator<<(std::ostream& out, const ColorRenderCamera& camera) { out << "ColorRenderCamera\n" << camera.core().intrinsics() << "\n show_window: " << camera.show_window(); return out; } std::ostream& operator<<(std::ostream& out, const DepthRenderCamera& camera) { out << "DepthRenderCamera\n" << camera.core().intrinsics() << "\n min_depth: " << camera.depth_range().min_depth() << "\n max_depth: " << camera.depth_range().max_depth(); return out; } namespace { template <typename T> const DummyRenderEngine* GetDummyRenderEngine( const systems::Context<T>& context, const std::string& name) { // Technically brittle, but relatively safe assumption that GeometryState // is abstract Parameter value 0. auto& geo_state = context.get_parameters() .template get_abstract_parameter<geometry::GeometryState<T>>(0); const DummyRenderEngine* engine = dynamic_cast<const DummyRenderEngine*>( geo_state.GetRenderEngineByName(name)); DRAKE_DEMAND(engine != nullptr); return engine; } ::testing::AssertionResult CompareCameraInfo(const CameraInfo& test, const CameraInfo& expected) { if (test.width() != expected.width() || test.height() != expected.height() || test.focal_x() != expected.focal_x() || test.focal_y() != expected.focal_y() || test.center_x() != expected.center_x() || test.center_y() != expected.center_y()) { return ::testing::AssertionFailure() << "Intrinsic values don't match.\n Expected " << expected << "\n got: " << test; } return ::testing::AssertionSuccess(); } ::testing::AssertionResult CompareClipping(const ClippingRange& test, const ClippingRange& expected) { if (test.near() != expected.near()) { return ::testing::AssertionFailure() << "Near clipping planes don't match.\n Expected " << expected.near() << "\n got " << test.near(); } if (test.far() != expected.far()) { return ::testing::AssertionFailure() << "Far clipping planes don't match.\n Expected " << expected.far() << "\n got " << test.far(); } return ::testing::AssertionSuccess(); } ::testing::AssertionResult CompareDepthRange(const DepthRange& test, const DepthRange& expected) { if (test.min_depth() != expected.min_depth()) { return ::testing::AssertionFailure() << "Minimum depth doesn't match.\n Expected " << expected.min_depth() << "\n got " << test.min_depth(); } if (test.max_depth() != expected.max_depth()) { return ::testing::AssertionFailure() << "Maximum depth doesn't match.\n Expected " << expected.max_depth() << "\n got " << test.max_depth(); } return ::testing::AssertionSuccess(); } ::testing::AssertionResult CompareCameraCore(const RenderCameraCore& test, const RenderCameraCore& expected) { ::testing::AssertionResult result{true}; result = CompareCameraInfo(test.intrinsics(), expected.intrinsics()); if (!result) return result; if (test.renderer_name() != expected.renderer_name()) { return ::testing::AssertionFailure() << "Renderer name doesn't match.\n Expected " << expected.renderer_name() << "\n got " << test.renderer_name(); } result = CompareClipping(test.clipping(), expected.clipping()); if (!result) return result; return CompareMatrices(test.sensor_pose_in_camera_body().GetAsMatrix4(), expected.sensor_pose_in_camera_body().GetAsMatrix4()); } ::testing::AssertionResult Compare(const ColorRenderCamera& test, const ColorRenderCamera& expected) { if (test.show_window() != expected.show_window()) { return ::testing::AssertionFailure() << "'show_window' doesn't match.\n Expected " << expected.show_window() << "\n got " << test.show_window(); } return CompareCameraCore(test.core(), expected.core()); } ::testing::AssertionResult Compare(const DepthRenderCamera& test, const DepthRenderCamera& expected) { auto result = CompareCameraCore(test.core(), expected.core()); if (!result) return result; return CompareDepthRange(test.depth_range(), expected.depth_range()); } class RgbdSensorTest : public ::testing::Test { public: RgbdSensorTest() : ::testing::Test(), // N.B. This is using arbitrary yet different intrinsics for color vs. // depth. The pose of the sensor in the camera body frame is *not* the // identity. We want to make sure that the RgbdSensor doesn't make use // of it. color_camera_({kRendererName, {640, 480, M_PI / 4}, {0.1, 10.0}, RigidTransformd{Vector3d{1, 0, 0}}}, false), depth_camera_({kRendererName, {320, 240, M_PI / 6}, {0.1, 10.0}, RigidTransformd{Vector3d{-1, 0, 0}}}, {0.1, 10}) {} protected: // Creates a Diagram with a SceneGraph and RgbdSensor connected appropriately. // Various components are stored in members for easy access. This should only // be called once per test. // make_sensor is a callback that will create the sensor. It is provided a // pointer to the SceneGraph so it has the opportunity to modify the // SceneGraph as it needs. void MakeCameraDiagram( std::function<unique_ptr<RgbdSensor>(SceneGraph<double>*)> make_sensor) { ASSERT_EQ(scene_graph_, nullptr) << "Only call MakeCameraDiagram() once per test"; DiagramBuilder<double> builder; scene_graph_ = builder.AddSystem<SceneGraph<double>>(); scene_graph_->AddRenderer(kRendererName, make_unique<DummyRenderEngine>()); sensor_ = builder.AddSystem(make_sensor(scene_graph_)); builder.Connect(scene_graph_->get_query_output_port(), sensor_->query_object_input_port()); diagram_ = builder.Build(); context_ = diagram_->CreateDefaultContext(); context_->SetTime(22.2); // An arbitrary non-zero value. context_->DisableCaching(); scene_graph_context_ = &diagram_->GetMutableSubsystemContext(*scene_graph_, context_.get()); sensor_context_ = &diagram_->GetMutableSubsystemContext(*sensor_, context_.get()); // Must get the render engine instance from the context itself. render_engine_ = GetDummyRenderEngine(*scene_graph_context_, kRendererName); } // Confirms that the member sensor_ matches the expected properties. Part // of this confirmation entails rendering the camera which *may* pull on // an input port. The optional `pre_render_callback` should do any work // necessary to make the input port viable. ::testing::AssertionResult ValidateConstruction( FrameId parent_id, const RigidTransformd& X_WC_expected, std::function<void()> pre_render_callback = {}) const { if (sensor_->parent_frame_id() != parent_id) { return ::testing::AssertionFailure() << "The sensor's parent id (" << sensor_->parent_frame_id() << ") does not match the expected id (" << parent_id << ")"; } ::testing::AssertionResult result = ::testing::AssertionSuccess(); result = CompareCameraInfo(sensor_->color_camera_info(), color_camera_.core().intrinsics()); if (!result) return result; result = Compare(sensor_->color_render_camera(), color_camera_); if (!result) return result; result = CompareCameraInfo(sensor_->depth_camera_info(), depth_camera_.core().intrinsics()); if (!result) return result; result = Compare(sensor_->depth_render_camera(), depth_camera_); if (!result) return result; // The poses of color and depth frames w.r.t. the camera body are defined // by the render cameras; RgbdSensor merely exposes those values. EXPECT_TRUE(CompareMatrices( sensor_->X_BC().GetAsMatrix4(), color_camera_.core().sensor_pose_in_camera_body().GetAsMatrix4())); EXPECT_TRUE(CompareMatrices( sensor_->X_BD().GetAsMatrix4(), depth_camera_.core().sensor_pose_in_camera_body().GetAsMatrix4())); // Confirm the pose used by the renderer is the expected X_WC pose. We do // this by invoking a render (the dummy render engine will cache the last // call to UpdateViewpoint()). if (pre_render_callback) pre_render_callback(); sensor_->color_image_output_port().Eval<ImageRgba8U>(*sensor_context_); EXPECT_TRUE( CompareMatrices(render_engine_->last_updated_X_WC().GetAsMatrix4(), X_WC_expected.GetAsMatrix4(), 1e-15)); return result; } ColorRenderCamera color_camera_; DepthRenderCamera depth_camera_; unique_ptr<Diagram<double>> diagram_; unique_ptr<Context<double>> context_; // Convenient pointers into the diagram and context; the underlying systems // are owned by the diagram and its context. SceneGraph<double>* scene_graph_{}; RgbdSensor* sensor_{}; const DummyRenderEngine* render_engine_{}; Context<double>* sensor_context_{}; Context<double>* scene_graph_context_{}; static const char kRendererName[]; }; const char RgbdSensorTest::kRendererName[] = "renderer"; // Confirms that port names are as documented in rgbd_sensor.h. This uses the // anchored constructor and assumes that the ports are the same for the // frame-fixed port. TEST_F(RgbdSensorTest, PortNames) { RgbdSensor sensor(SceneGraph<double>::world_frame_id(), RigidTransformd::Identity(), depth_camera_); EXPECT_EQ(sensor.query_object_input_port().get_name(), "geometry_query"); EXPECT_EQ(sensor.color_image_output_port().get_name(), "color_image"); EXPECT_EQ(sensor.depth_image_32F_output_port().get_name(), "depth_image_32f"); EXPECT_EQ(sensor.depth_image_16U_output_port().get_name(), "depth_image_16u"); EXPECT_EQ(sensor.label_image_output_port().get_name(), "label_image"); EXPECT_EQ(sensor.body_pose_in_world_output_port().get_name(), "body_pose_in_world"); EXPECT_EQ(sensor.image_time_output_port().get_name(), "image_time"); } // Tests that the anchored camera reports the correct parent frame and has the // right pose passed to the renderer. TEST_F(RgbdSensorTest, ConstructAnchoredCamera) { const Vector3d p_WB(1, 2, 3); const RollPitchYawd rpy_WB(M_PI / 2, 0, 0); const RigidTransformd X_WB(rpy_WB, p_WB); auto make_sensor = [this, &X_WB](SceneGraph<double>*) { return make_unique<RgbdSensor>(SceneGraph<double>::world_frame_id(), X_WB, color_camera_, depth_camera_); }; MakeCameraDiagram(make_sensor); const RigidTransformd& X_BC = sensor_->X_BC(); const RigidTransformd X_WC_expected = X_WB * X_BC; EXPECT_TRUE( ValidateConstruction(scene_graph_->world_frame_id(), X_WC_expected)); EXPECT_EQ(sensor_->image_time_output_port().Eval(*sensor_context_), Vector1d{22.2}); } // Similar to the AnchoredCamera test -- but, in this case, the reported pose // of the camera X_WC depends on the value of the specified parent frame P. TEST_F(RgbdSensorTest, ConstructFrameFixedCamera) { SourceId source_id; const GeometryFrame frame("camera_frame"); const RigidTransformd X_PB(AngleAxisd(M_PI / 6, Vector3d(1, 1, 1)), Vector3d(1, 2, 3)); const RigidTransformd X_WP(AngleAxisd(M_PI / 7, Vector3d(-1, 0, 1)), Vector3d(-2, -1, -3)); const FramePoseVector<double> X_WPs{{frame.id(), X_WP}}; // The sensor requires a frame to be registered in order to attach to the // frame. auto make_sensor = [this, &source_id, &frame, &X_PB](SceneGraph<double>* graph) { source_id = graph->RegisterSource("source"); graph->RegisterFrame(source_id, frame); return make_unique<RgbdSensor>(frame.id(), X_PB, color_camera_, depth_camera_); }; MakeCameraDiagram(make_sensor); const RigidTransformd& X_BC = sensor_->X_BC(); // NOTE: This *particular* factorization eliminates the need for a tolerance // in the matrix comparison -- it is the factorization that is implicit in // the code path for rendering. const RigidTransformd X_WC_expected = X_WP * (X_PB * X_BC); auto pre_render_callback = [this, &X_WPs, source_id]() { scene_graph_->get_source_pose_port(source_id).FixValue(scene_graph_context_, X_WPs); }; EXPECT_TRUE( ValidateConstruction(frame.id(), X_WC_expected, pre_render_callback)); } TEST_F(RgbdSensorTest, ConstructCameraWithNonTrivialOffsets) { const RigidTransformd X_BC{ math::RotationMatrixd::MakeFromOrthonormalRows(Eigen::Vector3d(0, 0, 1), Eigen::Vector3d(-1, 0, 0), Eigen::Vector3d(0, -1, 0)), Eigen::Vector3d(0, 0.02, 0)}; // For uniqueness, simply invert X_BC. const RigidTransformd X_BD{X_BC.inverse()}; const ColorRenderCamera color_camera{ {color_camera_.core().renderer_name(), color_camera_.core().intrinsics(), color_camera_.core().clipping(), X_BC}, color_camera_.show_window()}; const DepthRenderCamera depth_camera{ {depth_camera_.core().renderer_name(), depth_camera_.core().intrinsics(), depth_camera_.core().clipping(), X_BD}, depth_camera_.depth_range()}; const RigidTransformd X_WB; const RgbdSensor sensor(scene_graph_->world_frame_id(), X_WB, color_camera, depth_camera); EXPECT_TRUE( CompareMatrices(sensor.X_BC().GetAsMatrix4(), X_BC.GetAsMatrix4())); EXPECT_TRUE( CompareMatrices(sensor.X_BD().GetAsMatrix4(), X_BD.GetAsMatrix4())); } TEST_F(RgbdSensorTest, ConstructCameraWithNonTrivialOffsetsDeprecated) { const RigidTransformd X_BC{ math::RotationMatrixd::MakeFromOrthonormalRows(Eigen::Vector3d(0, 0, 1), Eigen::Vector3d(-1, 0, 0), Eigen::Vector3d(0, -1, 0)), Eigen::Vector3d(0, 0.02, 0)}; // For uniqueness, simply invert X_BC. const RigidTransformd X_BD{X_BC.inverse()}; const RigidTransformd X_WB; const ColorRenderCamera color_camera( {color_camera_.core().renderer_name(), {color_camera_.core().intrinsics().width(), color_camera_.core().intrinsics().height(), color_camera_.core().intrinsics().fov_y()}, color_camera_.core().clipping(), X_BC}, false); const DepthRenderCamera depth_camera( {depth_camera_.core().renderer_name(), {depth_camera_.core().intrinsics().width(), depth_camera_.core().intrinsics().height(), depth_camera_.core().intrinsics().fov_y()}, depth_camera_.core().clipping(), X_BD}, depth_camera_.depth_range()); const RgbdSensor sensor(scene_graph_->world_frame_id(), X_WB, color_camera, depth_camera); EXPECT_TRUE( CompareMatrices(sensor.X_BC().GetAsMatrix4(), X_BC.GetAsMatrix4())); EXPECT_TRUE( CompareMatrices(sensor.X_BD().GetAsMatrix4(), X_BD.GetAsMatrix4())); } // We don't explicitly test any of the image outputs. The image outputs simply // wrap the corresponding QueryObject call; the only calculations they do is to // produce the X_PC matrix (which is implicitly tested in the construction tests // above). // TODO(jwnimmer-tri) The body_pose_in_world_output_port should have unit test // coverage of its output value, not just its name. It ends up being indirectly // tested in sim_rgbd_sensor_test.cc but it would be better to identify bugs in // the RgbdSensor directly instead of intermingled with the wrapper code. } // namespace } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/rgbd_sensor_async_gl_test.cc
#include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/temp_directory.h" #include "drake/common/trajectories/piecewise_pose.h" #include "drake/geometry/render_gl/factory.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/framework/leaf_system.h" #include "drake/systems/sensors/image_writer.h" #include "drake/systems/sensors/rgbd_sensor.h" #include "drake/systems/sensors/rgbd_sensor_async.h" #include "drake/systems/sensors/rgbd_sensor_discrete.h" // This is an end-to-end acceptance test of the RgbdSensorAsync. // // More specific test cases tests of the System dynamics and API details are // covered by rgbd_sensor_async_test.cc. In particular, the exact timings of // capture offset and output delay are checked there; this test program is // solely focused on the image contents, not the event timing. // // We run a representative simulation with a discrete sensor alongside the async // sensor, with both sensors using the same fps. We presume that the discrete // sensor is correct (from its own unit tests). Other than the configured output // delay, the streams of images from the async sensor should be identical to the // discrete sensor. // // The discrete sensor is configured to sample and hold at these times: // Sample // 0 ms // 250 ms // 500 ms // 750 ms // etc // // The async sensor is configured to sample and output at these times: // Sample Output // 0 ms 125ms // 250 ms 375ms // 500 ms 625ms // 750 ms 875ms // etc // // Therefore, if we log the image output ports at 200ms, 450ms, etc. they should // be identical for both sensors. // // The images are written to disk for manual inspection in case of failures; see // drake/bazel-testlogs/systems/sensors/rgbd_sensor_async_gl_test/test.outputs/. namespace drake { namespace systems { namespace sensors { namespace { using Eigen::Vector3d; using geometry::FrameId; using geometry::FramePoseVector; using geometry::GeometryFrame; using geometry::MakeRenderEngineGl; using geometry::RenderEngineGlParams; using geometry::SourceId; using geometry::render::ColorRenderCamera; using geometry::render::DepthRenderCamera; using math::RigidTransform; using math::RollPitchYaw; using multibody::AddMultibodyPlantSceneGraph; using multibody::Parser; using systems::DiagramBuilder; using systems::LeafSystem; using trajectories::PiecewisePose; // TODO(#16294) Replace this with AbstractLogSink from systems/primitives once // that class exists. template <typename T> class AbstractLogSink final : public LeafSystem<T> { public: static_assert(std::is_same_v<T, double>); explicit AbstractLogSink(const AbstractValue& model_value) { this->DeclareAbstractInputPort("u0", model_value); // See the comment atop this file to understand the period & offset. const double period = 0.250; const double offset = 0.200; this->DeclarePeriodicPublishEvent(period, offset, &AbstractLogSink<T>::WriteToLog); } void WriteToLog(const Context<T>& context) const { const AbstractValue& value = this->get_input_port().template Eval<AbstractValue>(context); values_.emplace_back(value.Clone()); } const std::vector<copyable_unique_ptr<AbstractValue>>& values() const { return values_; } private: // In general, logging events to a member field is unsuitable for the systems // framework, but in the narrow use case of this unit test it's fine. mutable std::vector<copyable_unique_ptr<AbstractValue>> values_; }; /* Outputs the given trajectory as a FramePoseVector for use by SceneGraph. */ class FramePoseTrajectorySource final : public LeafSystem<double> { public: FramePoseTrajectorySource(FrameId frame_id, const PiecewisePose<double>& traj) : frame_id_(frame_id), traj_(traj) { this->DeclareAbstractOutputPort("frame_pose_vector", &FramePoseTrajectorySource::CalcOutput); } private: void CalcOutput(const Context<double>& context, FramePoseVector<double>* output) const { *output = {{frame_id_, traj_.GetPose(context.get_time())}}; } const FrameId frame_id_; const PiecewisePose<double> traj_; }; constexpr char kRendererName[] = "renderer_name"; GTEST_TEST(RgbdSensorAsyncGlTest, CompareAsyncToDiscrete) { // Add the plant, scene_graph, and renderer. DiagramBuilder<double> builder; auto [plant, scene_graph] = AddMultibodyPlantSceneGraph(&builder, 0.001); RenderEngineGlParams render_params; scene_graph.AddRenderer(kRendererName, MakeRenderEngineGl(render_params)); // Load some models. Parser(&plant).AddModelsFromUrl( "package://drake/systems/sensors/test/" "rgbd_sensor_async_gl_test.dmd.yaml"); plant.Finalize(); // Add a moving frame for the cameras. We'll use a non-MbP frame so that it is // easy to prescribe the trajectory (without the need for inverse dynamics). // This starts out looking at the side of the bin, and then swoops up and tips // down to look inside. constexpr double start_time = 0.0; constexpr double end_time = 2.0; const RigidTransform<double> X_WC_start(RollPitchYaw<double>{0.0, 0.0, 0.0}, Vector3d{-1.5, 0.0, 0.3}); const RigidTransform<double> X_WC_end(RollPitchYaw<double>{0.0, M_PI_2, 0.0}, Vector3d{0.0, 0.0, 1.5}); const PiecewisePose<double> camera_traj = PiecewisePose<double>::MakeLinear( {start_time, end_time}, {X_WC_start, X_WC_end}); const SourceId camera_kinematics_source = scene_graph.RegisterSource("camera_kinematics"); const FrameId camera_kinematics_frame = scene_graph.RegisterFrame( camera_kinematics_source, GeometryFrame{"camera_frame"}); const auto* camera_kinematics = builder.AddNamedSystem<FramePoseTrajectorySource>( "camera_pose", camera_kinematics_frame, camera_traj); builder.Connect(camera_kinematics->get_output_port(), scene_graph.get_source_pose_port(camera_kinematics_source)); // These settings are common to both cameras. Choose some arbitrary but // distinctive settings. (In particular, X_PB rotates us to look along +X // using -Z as image-down, plus a few millimeters of translational offset.) const FrameId parent_id = camera_kinematics_frame; const RigidTransform<double> X_PB(RollPitchYaw<double>{-M_PI_2, 0, -M_PI_2}, Vector3d{0.001, 0.002, 0.003}); const ColorRenderCamera color_camera( {kRendererName, {320, 240, M_PI / 4}, {0.1, 10.0}, {}}); const DepthRenderCamera depth_camera( {kRendererName, {160, 120, M_PI / 6}, {0.1, 10.0}, {}}, {0.1, 10}); const double fps = 4.0; const bool render_label_image = true; // Add the async sensor (the device under test). const double async_capture_offset = 0.0; const double async_output_delay = 0.125; const auto* sensor_async = builder.AddSystem<RgbdSensorAsync>( &scene_graph, parent_id, X_PB, fps, async_capture_offset, async_output_delay, color_camera, depth_camera, render_label_image); builder.Connect(scene_graph.get_query_output_port(), sensor_async->get_input_port()); // Add the non-async (discrete) sensor that will provide our reference images. // Refer to the file overview comment for details of image capture timings. const double discrete_period = 1.0 / fps; const auto* sensor_discrete = builder.AddSystem<RgbdSensorDiscrete>( std::make_unique<RgbdSensor>(parent_id, X_PB, color_camera, depth_camera), discrete_period, render_label_image); builder.Connect(scene_graph.get_query_output_port(), sensor_discrete->query_object_input_port()); // Prepare the output directory. std::string outputs_dir; if (const char* bazel_dir = std::getenv("TEST_UNDECLARED_OUTPUTS_DIR")) { outputs_dir = bazel_dir; log()->info("Images will be written to {}", "drake/bazel-testlogs/systems/sensors/" "rgbd_sensor_async_gl_test/test.outputs/"); } else { outputs_dir = temp_directory(); log()->info("Images will be written to {}", outputs_dir); } // Log all of the images. The 200ms offset is explained in the file overview. const std::string file_name_format = outputs_dir + "/{port_name}_{count}.png"; const double image_writer_offset = 0.200; auto* image_writer = builder.AddSystem<ImageWriter>(); const std::vector<std::pair<std::string, PixelType>> ports{ {"color_image", PixelType::kRgba8U}, {"label_image", PixelType::kLabel16I}, {"depth_image_16u", PixelType::kDepth16U}}; for (const auto& [port_name, pixel_type] : ports) { const std::string async_name = fmt::format("{}_async", port_name); const std::string discrete_name = fmt::format("{}_discrete", port_name); // Log the images to memory for test comparison. std::unique_ptr<AbstractValue> image; switch (pixel_type) { case PixelType::kRgba8U: image = std::make_unique<Value<Image<PixelType::kRgba8U>>>(); break; case PixelType::kLabel16I: image = std::make_unique<Value<Image<PixelType::kLabel16I>>>(); break; case PixelType::kDepth16U: image = std::make_unique<Value<Image<PixelType::kDepth16U>>>(); break; default: GTEST_FAIL(); return; } const auto* logger_async = builder.AddNamedSystem<AbstractLogSink<double>>(async_name, *image); const auto* logger_discrete = builder.AddNamedSystem<AbstractLogSink<double>>(discrete_name, *image); builder.Connect(sensor_async->GetOutputPort(port_name), logger_async->get_input_port()); builder.Connect(sensor_discrete->GetOutputPort(port_name), logger_discrete->get_input_port()); // Log the images to disk for offline inspection by humans. const auto& writer_port_async = image_writer->DeclareImageInputPort( pixel_type, async_name, file_name_format, 1.0 / fps, image_writer_offset); const auto& writer_port_discrete = image_writer->DeclareImageInputPort( pixel_type, discrete_name, file_name_format, 1.0 / fps, image_writer_offset); builder.Connect(sensor_async->GetOutputPort(port_name), writer_port_async); builder.Connect(sensor_discrete->GetOutputPort(port_name), writer_port_discrete); } // Run the simulation. const auto diagram = builder.Build(); Simulator<double> simulator(*diagram); simulator.AdvanceTo(end_time); log()->info("Simulation rate was {:.3}x realtime", simulator.get_actual_realtime_rate()); // Check the image outputs. auto image_eq = [](PixelType pixel_type, const AbstractValue& actual, const AbstractValue& expected) -> bool { switch (pixel_type) { case PixelType::kRgba8U: return actual.template get_value<Image<PixelType::kRgba8U>>() == expected.template get_value<Image<PixelType::kRgba8U>>(); case PixelType::kLabel16I: return actual.template get_value<Image<PixelType::kLabel16I>>() == expected.template get_value<Image<PixelType::kLabel16I>>(); break; case PixelType::kDepth16U: return actual.template get_value<Image<PixelType::kDepth16U>>() == expected.template get_value<Image<PixelType::kDepth16U>>(); default: DRAKE_UNREACHABLE(); } }; for (const auto& [port_name, pixel_type] : ports) { const std::vector<copyable_unique_ptr<AbstractValue>>& async_values = diagram ->template GetDowncastSubsystemByName<AbstractLogSink>( fmt::format("{}_async", port_name)) .values(); const std::vector<copyable_unique_ptr<AbstractValue>>& discrete_values = diagram ->template GetDowncastSubsystemByName<AbstractLogSink>( fmt::format("{}_discrete", port_name)) .values(); ASSERT_EQ(async_values.size(), 8); ASSERT_EQ(discrete_values.size(), 8); for (int i = 0; i < 8; ++i) { // If anything here fails, look at the logged images to see the problem. SCOPED_TRACE(fmt::format("pixel_type = {}, i = {}", static_cast<int>(pixel_type), i)); // Check that the async and discrete images are identical. ASSERT_TRUE(image_eq(pixel_type, *async_values[i], *discrete_values[i])); // Check that the images are actually different every frame. if (i > 0) { ASSERT_FALSE( image_eq(pixel_type, *discrete_values[i], *discrete_values[i - 1])); } } } // Check the pose outputs. // TODO(#19198) Cross-check the pose outputs between the two sensors. // We can't do that today because the discrete sensor is broken. } } // namespace } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/sim_rgbd_sensor_test.cc
#include "drake/systems/sensors/sim_rgbd_sensor.h" #include <string> #include <utility> #include <fmt/format.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/geometry/scene_graph.h" #include "drake/lcm/drake_lcm.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/lcm/lcm_publisher_system.h" #include "drake/systems/sensors/image_to_lcm_image_array_t.h" #include "drake/systems/sensors/rgbd_sensor.h" namespace drake { namespace systems { namespace sensors { namespace internal { namespace kcov339_avoidance_magic { namespace { // We need drake:: because there's also a systems::lcm namespace. using drake::lcm::DrakeLcm; using Eigen::Vector3d; using geometry::SceneGraph; using geometry::render::ClippingRange; using geometry::render::ColorRenderCamera; using geometry::render::DepthRange; using geometry::render::DepthRenderCamera; using geometry::render::RenderCameraCore; using math::RigidTransformd; using multibody::AddMultibodyPlantSceneGraph; using multibody::FixedOffsetFrame; using multibody::Frame; using multibody::MultibodyPlant; using multibody::RigidBody; using systems::lcm::LcmPublisherSystem; /* Returns a pointer to the named instance of TargetSystem (if it exists). */ template <typename TargetSystem> const TargetSystem* GetSystem(const DiagramBuilder<double>& builder, const std::string& name) { for (const auto* system : builder.GetSystems()) { if (system->get_name() == name) { const TargetSystem* result = dynamic_cast<const TargetSystem*>(system); EXPECT_NE(result, nullptr); return result; } } return nullptr; } std::pair<ColorRenderCamera, DepthRenderCamera> MakeCameras() { const RenderCameraCore core("dummy_renderer", CameraInfo(320, 240, 0.75), ClippingRange{10, 20}, {}); return {ColorRenderCamera(core, true), DepthRenderCamera(core, DepthRange{11.5, 13.5})}; } class SimRgbdSensorTest : public ::testing::Test { protected: void SetUp() override { std::tie(plant_, scene_graph_) = AddMultibodyPlantSceneGraph(&builder_, 1e-2); bodyA_ = &plant_->AddRigidBody("bodyA"); bodyB_ = &plant_->AddRigidBody("bodyB"); X_AF_ = RigidTransformd(Vector3d(-0.5, 0.5, 0.75)); frame_F_ = &plant_->AddFrame(std::make_unique<FixedOffsetFrame<double>>( "test_frame", *bodyA_, X_AF_)); plant_->Finalize(); } /* Constructs a default sensor specification. If no frame is given, the sensor is affixed to body A (bodyA_). */ SimRgbdSensor MakeSensorSpec(const Frame<double>* frame = nullptr) { const RigidTransformd X_AB(Vector3d(1, 2, 3)); const auto [color, depth] = MakeCameras(); return SimRgbdSensor("test1", frame ? *frame : bodyA_->body_frame(), 32.0, X_AB, color, depth); } /* Adds an RgbdSensor to builder_. Returns a pointer to the RgbdSensor and the SimRgbdSensor that created it. If no frame is given, the sensor is affixed to body A (bodyA_). @throws std::exception if the RgbdSensor wasn't added. */ const std::pair<SimRgbdSensor, const RgbdSensor*> MakeSensorOrThrow( const Frame<double>* frame = nullptr) { SimRgbdSensor sensor = MakeSensorSpec(frame); AddSimRgbdSensor(*scene_graph_, *plant_, sensor, &builder_); // Get the RgbdSensor from the builder. const auto* rgbd = GetSystem<RgbdSensor>(builder_, "rgbd_sensor_" + sensor.serial()); if (rgbd == nullptr) { throw std::logic_error("Failed to instantiate RgbdSensor"); } return {sensor, rgbd}; } /* Test helper for determining whether specifying an image port produces the expected connections. */ void AssertPublishedPorts(bool rgb, bool depth, bool label) { auto [sensor, rgbd] = MakeSensorOrThrow(); const size_t old_system_count = builder_.GetSystems().size(); AddSimRgbdSensorLcmPublisher( sensor, rgb ? &rgbd->color_image_output_port() : nullptr, depth ? &rgbd->depth_image_16U_output_port() : nullptr, label ? &rgbd->label_image_output_port() : nullptr, false, &builder_, &lcm_); EXPECT_LT(old_system_count, builder_.GetSystems().size()); const auto* images = GetSystem<ImageToLcmImageArrayT>( builder_, "image_to_lcm_" + sensor.serial()); ASSERT_NE(images, nullptr); if (rgb) { EXPECT_NO_THROW(images->GetInputPort("rgb")); } else { EXPECT_THROW(images->GetInputPort("rgb"), std::exception); } if (depth) { EXPECT_NO_THROW(images->GetInputPort("depth")); } else { EXPECT_THROW(images->GetInputPort("depth"), std::exception); } if (label) { EXPECT_NO_THROW(images->GetInputPort("label")); } else { EXPECT_THROW(images->GetInputPort("label"), std::exception); } } DiagramBuilder<double> builder_; MultibodyPlant<double>* plant_{}; SceneGraph<double>* scene_graph_{}; const RigidBody<double>* bodyA_{}; const RigidBody<double>* bodyB_{}; const Frame<double>* frame_F_{}; RigidTransformd X_AF_; DrakeLcm lcm_; }; /* Simply tests that all values passed in are available. We'll create two different instances with arbitrarily different values and confirm that the values are returned. */ TEST_F(SimRgbdSensorTest, SimRgbdSensorValues) { // The values for the camera core are irrelevant to the test -- to confirm // that camera properties get copied, we'll just look for unique values // at the highest level (i.e., color and depth) and assume that if *those* // values get copied, then all of the values got copied. const RenderCameraCore core("dummy_renderer", CameraInfo(320, 240, 0.75), ClippingRange{10, 20}, {}); { const ColorRenderCamera color(core, true); const DepthRenderCamera depth(core, DepthRange{11.5, 13.5}); const RigidTransformd X_PB(Vector3d(1, 2, 3)); const Frame<double>& frame = bodyA_->body_frame(); SimRgbdSensor sensor("test1", frame, 32.0, X_PB, color, depth); EXPECT_EQ("test1", sensor.serial()); EXPECT_EQ(&frame, &sensor.frame()); EXPECT_TRUE(drake::CompareMatrices(X_PB.GetAsMatrix34(), sensor.X_PB().GetAsMatrix34())); EXPECT_TRUE(sensor.color_properties().show_window()); EXPECT_EQ(11.5, sensor.depth_properties().depth_range().min_depth()); EXPECT_EQ(32.0, sensor.rate_hz()); } { const ColorRenderCamera color(core, false); const DepthRenderCamera depth(core, DepthRange{13.5, 15.5}); const RigidTransformd X_PB(Vector3d(10, 20, 30)); const Frame<double>& frame = bodyB_->body_frame(); SimRgbdSensor sensor("test2", frame, 64.0, X_PB, color, depth); EXPECT_EQ("test2", sensor.serial()); EXPECT_EQ(&frame, &sensor.frame()); EXPECT_TRUE(drake::CompareMatrices(X_PB.GetAsMatrix34(), sensor.X_PB().GetAsMatrix34())); EXPECT_FALSE(sensor.color_properties().show_window()); EXPECT_EQ(13.5, sensor.depth_properties().depth_range().min_depth()); EXPECT_EQ(64.0, sensor.rate_hz()); } } /* Confirms that when the frame is a body frame, that the RgbdSensor is affixed to the expected *geometry* frame with the expected pose. */ TEST_F(SimRgbdSensorTest, AddSensorWithBodyFrameSpecification) { auto [sensor, rgbd] = MakeSensorOrThrow(); EXPECT_EQ(rgbd->parent_frame_id(), plant_->GetBodyFrameIdOrThrow(bodyA_->index())); auto diagram = builder_.Build(); auto context = diagram->CreateDefaultContext(); auto& plant_context = plant_->GetMyMutableContextFromRoot(context.get()); const RigidTransformd X_WA(Vector3d(-3, -4, -5)); plant_->SetFreeBodyPose(&plant_context, *bodyA_, X_WA); const auto& rgbd_context = rgbd->GetMyContextFromRoot(*context); const auto& X_WB = rgbd->body_pose_in_world_output_port().Eval<RigidTransformd>( rgbd_context); const RigidTransformd& X_AB = sensor.X_PB(); EXPECT_TRUE(drake::CompareMatrices(X_WB.GetAsMatrix34(), (X_WA * X_AB).GetAsMatrix34())); } /* Confirms that when the frame is a secondary frame P, that the RgbdSensor is affixed to the *geometry* frame associated with the secondary frame's body A and with a pose that accounts for both X_PB and X_AP. */ TEST_F(SimRgbdSensorTest, AddSensorWithBodyOffsetFrameSpecification) { auto [sensor, rgbd] = MakeSensorOrThrow(frame_F_); EXPECT_EQ(rgbd->parent_frame_id(), plant_->GetBodyFrameIdOrThrow(bodyA_->index())); auto diagram = builder_.Build(); auto context = diagram->CreateDefaultContext(); auto& plant_context = plant_->GetMyMutableContextFromRoot(context.get()); const RigidTransformd X_WA(Vector3d(-3, -4, -5)); plant_->SetFreeBodyPose(&plant_context, *bodyA_, X_WA); const auto& rgbd_context = rgbd->GetMyContextFromRoot(*context); const auto& X_WB = rgbd->body_pose_in_world_output_port().Eval<RigidTransformd>( rgbd_context); const RigidTransformd& X_FB = sensor.X_PB(); EXPECT_TRUE(drake::CompareMatrices(X_WB.GetAsMatrix34(), (X_WA * X_AF_ * X_FB).GetAsMatrix34())); } /* Confirms that the added RgbdSensor has been properly configured: - it has been named based on serial, - its query object port is connected, and - the camera properties match the input specification. */ TEST_F(SimRgbdSensorTest, AddSensorForRgbdSensorConfiguration) { auto [sensor, rgbd] = MakeSensorOrThrow(); // Test criteria. EXPECT_THAT(rgbd->get_name(), ::testing::HasSubstr(sensor.serial())); EXPECT_TRUE(builder_.IsConnectedOrExported(rgbd->query_object_input_port())); // Relying on glass-box testing, the cameras should simply use copy semantics. // So, we'll test one field (renderer_name) and infer that the whole thing // got copied. EXPECT_EQ(rgbd->color_render_camera().core().renderer_name(), sensor.color_properties().core().renderer_name()); EXPECT_EQ(rgbd->depth_render_camera().core().renderer_name(), sensor.depth_properties().core().renderer_name()); } /* Confirms that if no ports have been provided in the invocation, that the builder remains unchanged. In fact, we don't even have to have an RgbdSensor instantiated. */ TEST_F(SimRgbdSensorTest, AddPublisherNoPortIsNoOp) { const size_t old_system_count = builder_.GetSystems().size(); SimRgbdSensor sensor = MakeSensorSpec(); AddSimRgbdSensorLcmPublisher(sensor, nullptr, nullptr, nullptr, false, &builder_, &lcm_); EXPECT_EQ(old_system_count, builder_.GetSystems().size()); } /* Confirms that if only the rgb port is provided, only the rgb port is connected. */ TEST_F(SimRgbdSensorTest, AddPublisherRgbOnly) { AssertPublishedPorts(true /* rgb */, false /* depth */, false /* label */); } /* Confirms that if only the depth port is provided, only the depth port is connected. */ TEST_F(SimRgbdSensorTest, AddPublisherDepthOnly) { AssertPublishedPorts(false /* rgb */, true /* depth */, false /* label */); } /* Confirms that if only the label port is provided, only the label port is connected. */ TEST_F(SimRgbdSensorTest, AddPublisherLabelOnly) { AssertPublishedPorts(false /* rgb */, false /* depth */, true /* label */); } /* Confirms that if all the ports are provided, all should be connected. */ TEST_F(SimRgbdSensorTest, AddPublisherRgbDepthAndLabel) { AssertPublishedPorts(true /* rgb */, true /* depth */, true /* label */); } /* Confirms that publisher is configured properly (channel name and period). We don't test that `do_compress` is passed because the ImageToLcmImageArrayT class provides no introspection. */ TEST_F(SimRgbdSensorTest, AddPublisherTestProperties) { const auto [sensor, rgbd] = MakeSensorOrThrow(); const size_t old_system_count = builder_.GetSystems().size(); AddSimRgbdSensorLcmPublisher(sensor, &rgbd->color_image_output_port(), &rgbd->depth_image_16U_output_port(), &rgbd->label_image_output_port(), false, &builder_, &lcm_); EXPECT_LT(old_system_count, builder_.GetSystems().size()); const auto* publisher = GetSystem<LcmPublisherSystem>( builder_, fmt::format("LcmPublisherSystem(DRAKE_RGBD_CAMERA_IMAGES_{})", sensor.serial())); ASSERT_NE(publisher, nullptr); EXPECT_DOUBLE_EQ(publisher->get_publish_period(), 1.0 / sensor.rate_hz()); EXPECT_THAT(publisher->get_channel_name(), ::testing::HasSubstr(sensor.serial())); } } // namespace } // namespace kcov339_avoidance_magic } // namespace internal } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/lcm_image_array_to_images_test.cc
#include "drake/systems/sensors/lcm_image_array_to_images.h" #include <fstream> #include <memory> #include <gtest/gtest.h> #include "drake/common/find_resource.h" #include "drake/lcmt_image_array.hpp" #include "drake/systems/sensors/image.h" namespace drake { namespace systems { namespace sensors { namespace { void LoadImageData(const std::string& filename, lcmt_image* image) { std::ifstream is(filename, std::ios::binary); EXPECT_TRUE(is.good()); image->data.clear(); while (true) { uint8_t c = is.get(); if (is.eof()) { break; } image->data.push_back(c); } EXPECT_TRUE(is.eof()); EXPECT_FALSE(is.bad()); image->size = image->data.size(); } void DecodeImageArray(LcmImageArrayToImages* dut, const lcmt_image_array& lcm_images, ImageRgba8U* color_image, ImageDepth32F* depth_image, ImageLabel16I* label_image) { std::unique_ptr<Context<double>> context = dut->CreateDefaultContext(); dut->image_array_t_input_port().FixValue(context.get(), lcm_images); *color_image = dut->color_image_output_port().Eval<ImageRgba8U>(*context); *depth_image = dut->depth_image_output_port().Eval<ImageDepth32F>(*context); *label_image = dut->label_image_output_port().Eval<ImageLabel16I>(*context); } GTEST_TEST(LcmImageArrayToImagesTest, EmptyArrayTest) { lcmt_image_array lcm_images{}; // Populate our expected images with some width/height and expect they're // cleared. ImageRgba8U color_image(32, 32); ImageDepth32F depth_image(32, 32); ImageLabel16I label_image(32, 32); LcmImageArrayToImages dut; DecodeImageArray(&dut, lcm_images, &color_image, &depth_image, &label_image); EXPECT_EQ(color_image.size(), 0); EXPECT_EQ(depth_image.size(), 0); EXPECT_EQ(label_image.size(), 0); } GTEST_TEST(LcmImageArrayToImagesTest, JpegTest) { // Start with an empty color image and expect that it will be populated. ImageRgba8U color_image; // Start with populated depth and label images, expect they will be cleared. ImageDepth32F depth_image(32, 32); ImageLabel16I label_image(32, 32); lcmt_image jpeg_image{}; jpeg_image.width = 32; jpeg_image.height = 32; jpeg_image.row_stride = jpeg_image.width * 3; jpeg_image.bigendian = 0; jpeg_image.pixel_format = lcmt_image::PIXEL_FORMAT_RGB; jpeg_image.channel_type = lcmt_image::CHANNEL_TYPE_UINT8; jpeg_image.compression_method = lcmt_image::COMPRESSION_METHOD_JPEG; LoadImageData(FindResourceOrThrow("drake/systems/sensors/test/jpeg_test.jpg"), &jpeg_image); lcmt_image_array lcm_images{}; lcm_images.num_images = 1; lcm_images.images.push_back(jpeg_image); LcmImageArrayToImages dut; DecodeImageArray(&dut, lcm_images, &color_image, &depth_image, &label_image); EXPECT_EQ(color_image.size(), 32 * 32 * 4); EXPECT_EQ(depth_image.size(), 0); EXPECT_EQ(label_image.size(), 0); } GTEST_TEST(LcmImageArrayToImagesTest, PngTest) { lcmt_image png_image{}; png_image.width = 32; png_image.height = 32; png_image.row_stride = png_image.width * 3; png_image.bigendian = 0; png_image.pixel_format = lcmt_image::PIXEL_FORMAT_RGB; png_image.channel_type = lcmt_image::CHANNEL_TYPE_UINT8; png_image.compression_method = lcmt_image::COMPRESSION_METHOD_PNG; LoadImageData( FindResourceOrThrow("drake/systems/sensors/test/png_color_test.png"), &png_image); lcmt_image_array lcm_images{}; lcm_images.num_images = 1; lcm_images.images.push_back(png_image); png_image.row_stride = png_image.width * 2; png_image.pixel_format = lcmt_image::PIXEL_FORMAT_DEPTH; png_image.channel_type = lcmt_image::CHANNEL_TYPE_UINT16; LoadImageData( FindResourceOrThrow("drake/systems/sensors/test/png_gray16_test.png"), &png_image); ++lcm_images.num_images; lcm_images.images.push_back(png_image); png_image.pixel_format = lcmt_image::PIXEL_FORMAT_LABEL; png_image.channel_type = lcmt_image::CHANNEL_TYPE_INT16; ++lcm_images.num_images; lcm_images.images.push_back(png_image); LcmImageArrayToImages dut; ImageRgba8U color_image; ImageDepth32F depth_image; ImageLabel16I label_image; DecodeImageArray(&dut, lcm_images, &color_image, &depth_image, &label_image); EXPECT_EQ(color_image.size(), 32 * 32 * 4); EXPECT_EQ(depth_image.size(), 32 * 32); EXPECT_EQ(label_image.size(), 32 * 32); } } // namespace } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/rgbd_sensor_async_test.cc
#include "drake/systems/sensors/rgbd_sensor_async.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/geometry/test_utilities/dummy_render_engine.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/diagram_builder.h" // This file contains specific tests of the System dynamics and API details, but // mostly does not inspect the actual rendered images. Instead, an end-to-end // acceptance test of RgbdSensorAsync lives in rgbd_sensor_async_gl_test.cc. namespace drake { namespace systems { namespace sensors { namespace { using geometry::FrameId; using geometry::GeometryId; using geometry::GeometryInstance; using geometry::PerceptionProperties; using geometry::SceneGraph; using geometry::Sphere; using geometry::internal::DummyRenderEngine; using geometry::render::ColorRenderCamera; using geometry::render::DepthRenderCamera; using geometry::render::RenderLabel; using math::RigidTransform; using multibody::AddMultibodyPlantSceneGraph; using systems::DiagramBuilder; using systems::EventCollection; using systems::UnrestrictedUpdateEvent; /* A render engine for unit testing that always outputs images that are entirely filled with the clear color, empty label, or too-far depth measurement. */ class SimpleRenderEngine final : public DummyRenderEngine { public: static constexpr uint8_t kClearColor = 66; static constexpr double kClearDepth32 = ImageTraits<PixelType::kDepth32F>::kTooFar; static constexpr uint16_t kClearDepth16 = ImageTraits<PixelType::kDepth16U>::kTooFar; static const RenderLabel& kClearLabel; SimpleRenderEngine() { this->set_force_accept(true); } private: std::unique_ptr<RenderEngine> DoClone() const final { return std::make_unique<SimpleRenderEngine>(*this); } void DoRenderColorImage(const ColorRenderCamera& camera, ImageRgba8U* output) const final { DummyRenderEngine::DoRenderColorImage(camera, output); *output = ImageRgba8U(camera.core().intrinsics().width(), camera.core().intrinsics().height(), kClearColor); } void DoRenderDepthImage(const DepthRenderCamera& camera, ImageDepth32F* output) const final { DummyRenderEngine::DoRenderDepthImage(camera, output); *output = ImageDepth32F(camera.core().intrinsics().width(), camera.core().intrinsics().height(), kClearDepth32); } void DoRenderLabelImage(const ColorRenderCamera& camera, ImageLabel16I* output) const final { DummyRenderEngine::DoRenderLabelImage(camera, output); *output = ImageLabel16I(camera.core().intrinsics().width(), camera.core().intrinsics().height(), kClearLabel); } }; const RenderLabel& SimpleRenderEngine::kClearLabel = RenderLabel::kEmpty; constexpr char kRendererName[] = "renderer_name"; /* A test fixture for the basics of the async sensor. */ class RgbdSensorAsyncTest : public ::testing::Test { public: RgbdSensorAsyncTest() : ::testing::Test(), // N.B. This is using arbitrary yet different intrinsics for color vs. // depth. color_camera_({kRendererName, {64, 48, M_PI / 4}, {0.1, 10.0}, {}}, false), depth_camera_({kRendererName, {32, 24, M_PI / 6}, {0.1, 10.0}, {}}, {0.1, 10}) {} /* Checks that all four image output ports of the given system are producing a "default" image (i.e., zero width and height), and the output_time is NaN. */ void ExpectDefaultImages(const System<double>& system, const Context<double>& context) { SCOPED_TRACE(fmt::format("... at context.time = {}", context.get_time())); const auto& color_image = system.GetOutputPort("color_image").Eval<ImageRgba8U>(context); const auto& label_image = system.GetOutputPort("label_image").Eval<ImageLabel16I>(context); const auto& depth32_image = system.GetOutputPort("depth_image_32f").Eval<ImageDepth32F>(context); const auto& depth16_image = system.GetOutputPort("depth_image_16u").Eval<ImageDepth16U>(context); const Eigen::VectorXd& image_time = system.GetOutputPort("image_time").Eval(context); ASSERT_EQ(color_image.width(), 0); ASSERT_EQ(color_image.height(), 0); ASSERT_EQ(label_image.width(), 0); ASSERT_EQ(label_image.height(), 0); ASSERT_EQ(depth32_image.width(), 0); ASSERT_EQ(depth32_image.height(), 0); ASSERT_EQ(depth16_image.width(), 0); ASSERT_EQ(depth16_image.height(), 0); ASSERT_EQ(image_time.size(), 1); EXPECT_THAT(image_time(0), testing::IsNan()); } /* Checks that all four image output ports of the given system are producing a "clear" image of the correct size, and the output_time is expected_time. */ void ExpectClearImages(const System<double>& system, const Context<double>& context, double expected_time) { SCOPED_TRACE(fmt::format("... at context.time = {}", context.get_time())); const auto& color_image = system.GetOutputPort("color_image").Eval<ImageRgba8U>(context); const auto& label_image = system.GetOutputPort("label_image").Eval<ImageLabel16I>(context); const auto& depth32_image = system.GetOutputPort("depth_image_32f").Eval<ImageDepth32F>(context); const auto& depth16_image = system.GetOutputPort("depth_image_16u").Eval<ImageDepth16U>(context); const Eigen::VectorXd& image_time = system.GetOutputPort("image_time").Eval(context); const auto& color_intrinsics = color_camera_.core().intrinsics(); ASSERT_EQ(color_image.width(), color_intrinsics.width()); ASSERT_EQ(color_image.height(), color_intrinsics.height()); ASSERT_EQ(label_image.width(), color_intrinsics.width()); ASSERT_EQ(label_image.height(), color_intrinsics.height()); const auto& depth_intrinsics = depth_camera_.core().intrinsics(); ASSERT_EQ(depth32_image.width(), depth_intrinsics.width()); ASSERT_EQ(depth32_image.height(), depth_intrinsics.height()); ASSERT_EQ(depth16_image.width(), depth_intrinsics.width()); ASSERT_EQ(depth16_image.height(), depth_intrinsics.height()); auto to_vector = [](const auto& image) { return std::vector(image.at(0, 0), image.at(0, 0) + image.size()); }; ASSERT_THAT(to_vector(color_image), ::testing::Each(SimpleRenderEngine::kClearColor)); ASSERT_THAT(to_vector(label_image), ::testing::Each(SimpleRenderEngine::kClearLabel)); ASSERT_THAT(to_vector(depth32_image), ::testing::Each(SimpleRenderEngine::kClearDepth32)); ASSERT_THAT(to_vector(depth16_image), ::testing::Each(SimpleRenderEngine::kClearDepth16)); ASSERT_EQ(image_time.size(), 1); EXPECT_EQ(image_time(0), expected_time); } protected: ColorRenderCamera color_camera_; DepthRenderCamera depth_camera_; }; TEST_F(RgbdSensorAsyncTest, ConstructorAndSimpleAccessors) { SceneGraph<double> scene_graph; const FrameId parent_id = SceneGraph<double>::world_frame_id(); const RigidTransform<double> X_PB(Eigen::Vector3d(1, 2, 3)); const double fps = 4; const double capture_offset = 0.001; const double output_delay = 0.200; const bool render_label_image = true; const RgbdSensorAsync dut(&scene_graph, parent_id, X_PB, fps, capture_offset, output_delay, color_camera_, depth_camera_, render_label_image); EXPECT_EQ(dut.parent_id(), parent_id); EXPECT_EQ(dut.X_PB().GetAsMatrix34(), X_PB.GetAsMatrix34()); EXPECT_EQ(dut.fps(), fps); EXPECT_EQ(dut.capture_offset(), capture_offset); EXPECT_EQ(dut.output_delay(), output_delay); EXPECT_TRUE(dut.color_camera().has_value()); EXPECT_TRUE(dut.depth_camera().has_value()); EXPECT_EQ(dut.get_input_port().get_name(), "geometry_query"); EXPECT_EQ(dut.color_image_output_port().get_name(), "color_image"); EXPECT_EQ(dut.depth_image_32F_output_port().get_name(), "depth_image_32f"); EXPECT_EQ(dut.depth_image_16U_output_port().get_name(), "depth_image_16u"); EXPECT_EQ(dut.label_image_output_port().get_name(), "label_image"); EXPECT_EQ(dut.body_pose_in_world_output_port().get_name(), "body_pose_in_world"); Simulator<double> simulator(dut); simulator.Initialize(); } // Confirm that we fail-fast when geometry changes post-initialze. TEST_F(RgbdSensorAsyncTest, GeometryVersionFailFast) { // Prepare a full simulation. DiagramBuilder<double> builder; auto [plant, scene_graph] = AddMultibodyPlantSceneGraph(&builder, 0); plant.Finalize(); scene_graph.AddRenderer(kRendererName, std::make_unique<SimpleRenderEngine>()); const FrameId world = SceneGraph<double>::world_frame_id(); const RigidTransform<double> X; const double fps = 4; const double capture_offset = 0.001; const double output_delay = 0.200; const auto* dut = builder.AddSystem<RgbdSensorAsync>( &scene_graph, world, X, fps, capture_offset, output_delay, color_camera_, std::nullopt); builder.Connect(scene_graph.get_query_output_port(), dut->get_input_port()); Simulator<double> simulator(builder.Build()); // Trigger the initialiation event. This sets up the Worker. simulator.Initialize(); // Add a new geometry to the context after initialization. Context<double>* scene_graph_context = &scene_graph.GetMyMutableContextFromRoot( &simulator.get_mutable_context()); const GeometryId geometry_id = scene_graph.RegisterGeometry( scene_graph_context, plant.get_source_id().value(), world, std::make_unique<GeometryInstance>(X, Sphere(0.1), "sphere")); PerceptionProperties properties; properties.UpdateProperty("label", "id", RenderLabel(1)); scene_graph.AssignRole(scene_graph_context, plant.get_source_id().value(), geometry_id, properties); // Simulating again is an error (for now). Ideally, we'd adapt to the new // geometry but for now at least we fail-fast. DRAKE_EXPECT_THROWS_MESSAGE(simulator.AdvanceTo(0.002), ".*must manually call.*Initialize.*"); } TEST_F(RgbdSensorAsyncTest, ConstructorColorOnly) { SceneGraph<double> scene_graph; const FrameId parent_id = SceneGraph<double>::world_frame_id(); const RigidTransform<double> X_PB; const double fps = 4; const double capture_offset = 0.001; const double output_delay = 0.200; const bool render_label_image = false; const RgbdSensorAsync dut(&scene_graph, parent_id, X_PB, fps, capture_offset, output_delay, color_camera_, std::nullopt, render_label_image); EXPECT_TRUE(dut.color_camera().has_value()); EXPECT_NO_THROW(dut.color_image_output_port()); EXPECT_FALSE(dut.depth_camera().has_value()); EXPECT_THROW(dut.depth_image_32F_output_port(), std::exception); EXPECT_THROW(dut.depth_image_16U_output_port(), std::exception); EXPECT_THROW(dut.label_image_output_port(), std::exception); Simulator<double> simulator(dut); simulator.Initialize(); } TEST_F(RgbdSensorAsyncTest, ConstructorDepthOnly) { SceneGraph<double> scene_graph; const FrameId parent_id = SceneGraph<double>::world_frame_id(); const RigidTransform<double> X_PB; const double fps = 4; const double capture_offset = 0.001; const double output_delay = 0.200; const bool render_label_image = false; const RgbdSensorAsync dut(&scene_graph, parent_id, X_PB, fps, capture_offset, output_delay, std::nullopt, depth_camera_, render_label_image); EXPECT_TRUE(dut.depth_camera().has_value()); EXPECT_NO_THROW(dut.depth_image_32F_output_port()); EXPECT_NO_THROW(dut.depth_image_16U_output_port()); EXPECT_FALSE(dut.color_camera().has_value()); EXPECT_THROW(dut.color_image_output_port(), std::exception); EXPECT_THROW(dut.label_image_output_port(), std::exception); Simulator<double> simulator(dut); simulator.Initialize(); } // Sanity check the basic plumbing and event scheduling by rendering an empty // scene. Initially there is no image output because time has not advanced far // enough yet, so all output ports evaluate to their default value (i.e., all // pixels are zero). After enough time has passed, the output port evaluation // will provide rendered images filled with a uniform non-zero background color, // i.e., the "clear" color. TEST_F(RgbdSensorAsyncTest, RenderBackgroundColor) { // Add the plant, scene_graph, and renderer. DiagramBuilder<double> builder; auto [plant, scene_graph] = AddMultibodyPlantSceneGraph(&builder, 0); scene_graph.AddRenderer(kRendererName, std::make_unique<SimpleRenderEngine>()); // Add the RgbdSensorAsync and export all of its output ports. const FrameId parent_id = SceneGraph<double>::world_frame_id(); const RigidTransform<double> X_PB(Eigen::Vector3d(1, 2, 3)); const double fps = 4; const double capture_offset = 0.001; const double output_delay = 0.200; const bool render_label_image = true; const auto* dut = builder.AddSystem<RgbdSensorAsync>( &scene_graph, parent_id, X_PB, fps, capture_offset, output_delay, color_camera_, depth_camera_, render_label_image); builder.Connect(scene_graph.get_query_output_port(), dut->get_input_port()); for (OutputPortIndex i{0}; i < dut->num_output_ports(); ++i) { const auto& output_port = dut->get_output_port(i); builder.ExportOutput(output_port, output_port.get_name()); } // Prepare the simulation. plant.Finalize(); Simulator<double> simulator(builder.Build()); // The dut has two main kinds of events, 'tick' and 'tock'. The tick events // snapshot the geometry kinematics and then launch the async render task. The // tock events wait for the async render task to finish and then set the // output port to the new image. // // In this test we'll Start the simulation at time == 100ms to cover the case // where the first tock event happens without any prior tick event. Here's an // event summary: // // - 1ms scheduled tick event, but we've set up simulator to skip over this // - 100ms initialize event (this is the start time of simulation) // - 201ms tock event, but there is no async render task yet so it's a no-op // - 251ms tick event, launches async render task // - 451ms tock event, sets the output images simulator.get_mutable_context().SetTime(0.100); // Prior to initialization, the output image is empty. ExpectDefaultImages(simulator.get_system(), simulator.get_context()); // The output image is still empty as we pass through various initialization // and update events. for (double time : {0.101, 0.202, 0.252, 0.450}) { simulator.AdvanceTo(time); ExpectDefaultImages(simulator.get_system(), simulator.get_context()); } // After the second tock event, we see the engine's "clear" color. simulator.AdvanceTo(0.452); ExpectClearImages(simulator.get_system(), simulator.get_context(), 0.251); // Likewise, the pose port finally has the correct value. EXPECT_EQ(simulator.get_system() .GetOutputPort("body_pose_in_world") .Eval<RigidTransform<double>>(simulator.get_context()) .translation(), X_PB.translation()); // Nuke the state back to default so that we can test the recovery logic for a // missing initialization event during a *tick*. // - 451ms reset state to default; therefore the output is default as well // - 501ms tick; output is still default // - 702ms tock; output is back to clear simulator.get_mutable_context().get_mutable_state().SetFrom( simulator.get_system().CreateDefaultContext()->get_state()); ExpectDefaultImages(simulator.get_system(), simulator.get_context()); simulator.AdvanceTo(0.502); ExpectDefaultImages(simulator.get_system(), simulator.get_context()); simulator.AdvanceTo(0.702); ExpectClearImages(simulator.get_system(), simulator.get_context(), 0.501); // Nuke the state back to default so that we can test the recovery logic for a // missing initialization event during a *tock*. // - 751ms tick // - 752ms reset state to default; therefore the output is default as well // - 952ms tock; output is still default (no tick) // - 1001ms tick; output is still default // - 1201ms tock; output is finally back to clear simulator.AdvanceTo(0.752); simulator.get_mutable_context().get_mutable_state().SetFrom( simulator.get_system().CreateDefaultContext()->get_state()); for (double time : {0.952, 1.002}) { simulator.AdvanceTo(time); ExpectDefaultImages(simulator.get_system(), simulator.get_context()); } simulator.AdvanceTo(1.202); ExpectClearImages(simulator.get_system(), simulator.get_context(), 1.001); // Now the wheels really come off the cart. Advance time to fire a *tick*, // then fast forward over the matching tock, then manually fire the next tick // to avoid the Simulator interlock that a call to Initialize must happen // inbetween SetTime and AdranceTo. With all these hijinks, a user would // probably never encounter this, but it's a necessary test case to cover the // error handling logic for two Worker::Start() calls back-to-back. // - 1251ms tick // - 1500ms new set time (skipping the tock at 1451ms) // - 1501ms tick simulator.AdvanceTo(1.252); simulator.get_mutable_context().SetTime(1.500); auto events = simulator.get_system().AllocateCompositeEventCollection(); double next_time = simulator.get_system().CalcNextUpdateTime( simulator.get_context(), events.get()); EXPECT_EQ(next_time, 1.501); const EventCollection<UnrestrictedUpdateEvent<double>>& update_events = events->get_unrestricted_update_events(); EXPECT_TRUE(update_events.HasEvents()); auto next_state_out = simulator.get_context().CloneState(); EXPECT_TRUE(simulator.get_system() .CalcUnrestrictedUpdate(simulator.get_context(), update_events, next_state_out.get()) .succeeded()); } } // namespace } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/pixel_types_test.cc
#include "drake/systems/sensors/pixel_types.h" #include <gtest/gtest.h> namespace drake { namespace systems { namespace sensors { namespace { GTEST_TEST(PixelTypesTest, Formatters) { EXPECT_EQ(fmt::to_string(PixelType::kRgba8U), "Rgba8U"); EXPECT_EQ(fmt::to_string(PixelFormat::kRgba), "Rgba"); EXPECT_EQ(fmt::to_string(PixelScalar::k8U), "8U"); } } // namespace } // namespace sensors } // namespace systems } // namespace drake
0