repo_id
stringclasses
205 values
file_path
stringlengths
33
141
content
stringlengths
1
307k
__index_level_0__
int64
0
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/rotary_encoders_test.cc
#include "drake/systems/sensors/rotary_encoders.h" #include <cmath> #include <vector> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/symbolic_test_util.h" #include "drake/systems/framework/test_utilities/scalar_conversion.h" namespace drake { namespace { constexpr double k2Pi = 2.0 * M_PI; // Test with the simple quantization-only constructor. GTEST_TEST(TestEncoders, QuantizeOnly) { // Construct a system where all inputs are encoders, with quantization const std::vector<int> tick_counts = {100, 50}; systems::sensors::RotaryEncoders<double> encoders(tick_counts); Eigen::Vector2d ticks_per_radian; ticks_per_radian << tick_counts[0] / k2Pi, tick_counts[1] / k2Pi; auto context = encoders.CreateDefaultContext(); auto output = encoders.AllocateOutput(); auto measurement = output->get_vector_data(0); double tol = 1e-10; Eigen::Vector2d angle, desired_measurement; // TODO(russt): Use c++11 random generators instead (w/ some wrappers). srand(42); for (int i = 0; i < 10; i++) { angle = Eigen::Vector2d::Random(); using std::floor; for (int j = 0; j < 2; j++) { desired_measurement(j) = floor(angle(j) * ticks_per_radian(j)) / ticks_per_radian(j); } encoders.get_input_port().FixValue(context.get(), angle); encoders.CalcOutput(*context, output.get()); EXPECT_TRUE(CompareMatrices(desired_measurement, measurement->CopyToVector(), tol, MatrixCompareType::absolute)); } } // Test with the simple selector-only constructor. GTEST_TEST(TestEncoders, SelectorOnly) { // Construct a system with no quantization, and only inputs 1 and 2 are // passed. const std::vector<int> indices = {1, 2}; systems::sensors::RotaryEncoders<double> encoders(4, indices); auto context = encoders.CreateDefaultContext(); auto output = encoders.AllocateOutput(); auto measurement = output->get_vector_data(0); double tol = 1e-10; Eigen::Vector4d angle; Eigen::Vector2d desired_measurement; // TODO(russt): Use c++11 random generators instead (w/ some wrappers). srand(42); for (int i = 0; i < 10; i++) { angle = Eigen::Vector4d::Random(); desired_measurement = angle.segment(1, 2); encoders.get_input_port().FixValue(context.get(), angle); encoders.CalcOutput(*context, output.get()); EXPECT_TRUE(CompareMatrices(desired_measurement, measurement->CopyToVector(), tol, MatrixCompareType::absolute)); } } // Test with the simple quantization and selector constructor. GTEST_TEST(TestEncoders, QuantizationAndSelector) { // Construct a system with quantization, and only inputs 1 and 2 are // passed. const std::vector<int> indices = {1, 2}; const std::vector<int> tick_counts = {100, 50}; systems::sensors::RotaryEncoders<double> encoders(4, indices, tick_counts); Eigen::Vector2d ticks_per_radian; ticks_per_radian << tick_counts[0] / k2Pi, tick_counts[1] / k2Pi; auto context = encoders.CreateDefaultContext(); auto output = encoders.AllocateOutput(); auto measurement = output->get_vector_data(0); double tol = 1e-10; Eigen::Vector4d angle; Eigen::Vector2d desired_measurement; // TODO(russt): Use c++11 random generators instead (w/ some wrappers). srand(42); for (int i = 0; i < 10; i++) { angle = Eigen::Vector4d::Random(); encoders.get_input_port().FixValue(context.get(), angle); using std::ceil; using std::floor; for (int j = 0; j < 2; j++) { desired_measurement(j) = floor(angle(indices[j]) * ticks_per_radian(j)) / ticks_per_radian(j); } encoders.CalcOutput(*context, output.get()); EXPECT_TRUE(CompareMatrices(desired_measurement, measurement->CopyToVector(), tol, MatrixCompareType::absolute)); } } // Test the calibration offsets (via the parameters). GTEST_TEST(TestEncoders, CalibrationOffsets) { // Construct a system where all inputs are encoders, with quantization. const std::vector<int> tick_counts = {100, 50}; systems::sensors::RotaryEncoders<double> encoders(tick_counts); Eigen::Vector2d ticks_per_radian; ticks_per_radian << tick_counts[0] / k2Pi, tick_counts[1] / k2Pi; auto context = encoders.CreateDefaultContext(); auto output = encoders.AllocateOutput(); auto measurement = output->get_vector_data(0); // Set some offsets. Eigen::Vector2d offsets; offsets << 0.1, M_PI_4; encoders.set_calibration_offsets(context.get(), offsets); double tol = 1e-10; Eigen::Vector2d angle, desired_measurement; // TODO(russt): Use c++11 random generators instead (w/ some wrappers). srand(42); for (int i = 0; i < 10; i++) { angle = Eigen::Vector2d::Random(); encoders.get_input_port().FixValue(context.get(), angle); angle -= offsets; using std::ceil; using std::floor; for (int j = 0; j < 2; j++) { desired_measurement(j) = floor(angle(j) * ticks_per_radian(j)) / ticks_per_radian(j); } encoders.CalcOutput(*context, output.get()); EXPECT_TRUE(CompareMatrices(desired_measurement, measurement->CopyToVector(), tol, MatrixCompareType::absolute)); } } // Test ToAutoDiff and ToSymbolic. GTEST_TEST(TestEncoders, ScalarConversion) { using Expression = symbolic::Expression; const std::vector<int> indices = {1, 2}; const std::vector<int> tick_counts = {2, 4}; systems::sensors::RotaryEncoders<double> encoders(4, indices, tick_counts); // Sanity check AutoDiff form. We rely on symbolic form to test correctness. EXPECT_TRUE(is_autodiffxd_convertible(encoders)); // Check that both the indices and tick_counts made it into symbolic form. EXPECT_TRUE(is_symbolic_convertible( encoders, [&](const systems::sensors::RotaryEncoders<Expression>& dut) { auto context = dut.CreateDefaultContext(); // Set input to be symbolic variables. const Vector4<Expression> input{ symbolic::Variable("u0"), symbolic::Variable("u1"), symbolic::Variable("u2"), symbolic::Variable("u3")}; dut.get_input_port().FixValue(context.get(), input); // Obtain the symbolic outputs. auto outputs = dut.AllocateOutput(); dut.CalcOutput(*context, outputs.get()); const systems::BasicVector<Expression>& output = *(outputs->get_vector_data(0)); ASSERT_EQ(output.size(), 2); // Symbolic form should be as expected. using symbolic::test::ExprEqual; EXPECT_PRED2(ExprEqual, output[0], floor((M_1_PI * input[1])) / M_1_PI); EXPECT_PRED2(ExprEqual, output[1], floor((M_2_PI * input[2])) / M_2_PI); })); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/image_to_lcm_image_array_t_test.cc
#include "drake/systems/sensors/image_to_lcm_image_array_t.h" #include <gtest/gtest.h> #include "drake/lcmt_image_array.hpp" #include "drake/systems/sensors/image.h" namespace drake { namespace systems { namespace sensors { namespace { const char* kColorFrameName = "color_frame_name"; const char* kDepthFrameName = "depth_frame_name"; const char* kLabelFrameName = "label_frame_name"; // Using very tiny image. const int kImageWidth = 8; const int kImageHeight = 6; lcmt_image_array SetUpInputAndOutput(ImageToLcmImageArrayT* dut, const ImageRgba8U& color_image, const ImageDepth32F& depth_image, const ImageLabel16I& label_image) { const InputPort<double>& color_image_input_port = dut->color_image_input_port(); const InputPort<double>& depth_image_input_port = dut->depth_image_input_port(); const InputPort<double>& label_image_input_port = dut->label_image_input_port(); std::unique_ptr<Context<double>> context = dut->CreateDefaultContext(); color_image_input_port.FixValue(context.get(), color_image); depth_image_input_port.FixValue(context.get(), depth_image); label_image_input_port.FixValue(context.get(), label_image); return dut->image_array_t_msg_output_port().Eval<lcmt_image_array>(*context); } GTEST_TEST(ImageToLcmImageArrayT, ValidTest) { ImageRgba8U color_image(kImageWidth, kImageHeight); ImageDepth32F depth_image(kImageWidth, kImageHeight); ImageLabel16I label_image(kImageWidth, kImageHeight); auto Verify = [color_image, depth_image, label_image]( const ImageToLcmImageArrayT& dut, const lcmt_image_array& output_image_array, uint8_t compression_method) { // Verifyies lcmt_image_array EXPECT_EQ(output_image_array.header.seq, 0); EXPECT_EQ(output_image_array.header.utime, 0); EXPECT_EQ(output_image_array.header.frame_name, ""); EXPECT_EQ(output_image_array.num_images, 3); EXPECT_EQ(output_image_array.images.size(), 3); // Verifyies each lcmt_image. for (auto const& image : output_image_array.images) { EXPECT_EQ(image.header.seq, 0); EXPECT_EQ(image.header.utime, 0); EXPECT_EQ(image.width, kImageWidth); EXPECT_EQ(image.height, kImageHeight); EXPECT_EQ(image.data.size(), image.size); EXPECT_FALSE(image.bigendian); EXPECT_EQ(image.compression_method, compression_method); std::string frame_name; int row_stride; int8_t pixel_format; int8_t channel_type; if (image.pixel_format == lcmt_image::PIXEL_FORMAT_RGBA) { frame_name = kColorFrameName; row_stride = color_image.width() * color_image.kNumChannels * sizeof(*color_image.at(0, 0)); pixel_format = lcmt_image::PIXEL_FORMAT_RGBA; channel_type = lcmt_image::CHANNEL_TYPE_UINT8; } else if (image.pixel_format == lcmt_image::PIXEL_FORMAT_DEPTH) { frame_name = kDepthFrameName; row_stride = depth_image.width() * depth_image.kNumChannels * sizeof(*depth_image.at(0, 0)); pixel_format = lcmt_image::PIXEL_FORMAT_DEPTH; channel_type = lcmt_image::CHANNEL_TYPE_FLOAT32; } else if (image.pixel_format == lcmt_image::PIXEL_FORMAT_LABEL) { frame_name = kLabelFrameName; row_stride = label_image.width() * label_image.kNumChannels * sizeof(*label_image.at(0, 0)); pixel_format = lcmt_image::PIXEL_FORMAT_LABEL; channel_type = lcmt_image::CHANNEL_TYPE_INT16; } else { EXPECT_FALSE(true); } EXPECT_EQ(image.header.frame_name, frame_name); EXPECT_EQ(image.row_stride, row_stride); EXPECT_EQ(image.pixel_format, pixel_format); EXPECT_EQ(image.channel_type, channel_type); } }; ImageToLcmImageArrayT dut_compressed(kColorFrameName, kDepthFrameName, kLabelFrameName, true); auto image_array_t_compressed = SetUpInputAndOutput( &dut_compressed, color_image, depth_image, label_image); Verify(dut_compressed, image_array_t_compressed, lcmt_image::COMPRESSION_METHOD_ZLIB); ImageToLcmImageArrayT dut_uncompressed(kColorFrameName, kDepthFrameName, kLabelFrameName, false); auto image_array_t_uncompressed = SetUpInputAndOutput( &dut_uncompressed, color_image, depth_image, label_image); Verify(dut_uncompressed, image_array_t_uncompressed, lcmt_image::COMPRESSION_METHOD_NOT_COMPRESSED); } } // namespace } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/vtk_diagnostic_event_observer_test.cc
#include "drake/systems/sensors/vtk_diagnostic_event_observer.h" #include <string> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> // To ease build system upkeep, we annotate VTK includes with their deps. #include <vtkNew.h> // vtkCommonCore namespace drake { namespace systems { namespace sensors { namespace internal { namespace { using drake::internal::DiagnosticDetail; using drake::internal::DiagnosticPolicy; GTEST_TEST(VtkDiagnosticEventObserverTest, General) { // Prepare a DiagnosticPolicy that simply accumulates its messages. std::vector<std::string> messages; DiagnosticPolicy diagnostic_policy; diagnostic_policy.SetActionForWarnings([&](const DiagnosticDetail& detail) { messages.push_back(detail.FormatWarning()); }); diagnostic_policy.SetActionForErrors([&](const DiagnosticDetail& detail) { messages.push_back(detail.FormatError()); }); // Create the device under test. vtkNew<VtkDiagnosticEventObserver> dut; dut->set_diagnostic(&diagnostic_policy); // Create a dummy object that will generate messages observed by the dut. vtkNew<vtkObject> dummy; dummy->AddObserver(vtkCommand::ErrorEvent, dut); dummy->AddObserver(vtkCommand::WarningEvent, dut); // Generate messages. const char* const error_message = "text for error\n" "next line\n\n"; const char* const warning_message = "text for warning\n" "next line\n\n"; dummy->InvokeEvent( vtkCommand::ErrorEvent, const_cast<void*>(static_cast<const void*>(error_message))); dummy->InvokeEvent( vtkCommand::WarningEvent, const_cast<void*>(static_cast<const void*>(warning_message))); // Check for what came out. EXPECT_THAT(messages, testing::ElementsAre("error: text for error: next line", "warning: text for warning: next line")); } } // namespace } // namespace internal } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/camera_info_test.cc
#include "drake/systems/sensors/camera_info.h" #include <limits> #include <utility> #include <vector> #include <Eigen/Dense> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" namespace drake { namespace systems { namespace sensors { namespace { using Eigen::Matrix3d; // This is because there is a precision difference between Ubuntu and Mac. const double kTolerance = 1e-12; const int kWidth = 640; const int kHeight = 480; const double kFx = 554.25625842204079; // In pixels. const double kFy = 579.41125496954282; // In pixels. const double kCx = kWidth * 0.5 - 0.5; const double kCy = kHeight * 0.5 - 0.5; const double kVerticalFov = 0.78539816339744828; // 45.0 degrees. void Verify(const Matrix3d& expected, const CameraInfo& dut) { EXPECT_EQ(kWidth, dut.width()); EXPECT_EQ(kHeight, dut.height()); EXPECT_NEAR(expected(0, 0), dut.focal_x(), kTolerance); EXPECT_NEAR(expected(1, 1), dut.focal_y(), kTolerance); EXPECT_NEAR(expected(0, 2), dut.center_x(), kTolerance); EXPECT_NEAR(expected(1, 2), dut.center_y(), kTolerance); EXPECT_TRUE(CompareMatrices(expected, dut.intrinsic_matrix(), kTolerance)); } GTEST_TEST(TestCameraInfo, ConstructionTest) { const Matrix3d expected( (Matrix3d() << kFx, 0., kCx, 0., kFy, kCy, 0., 0., 1.).finished()); { SCOPED_TRACE("Spelled out"); CameraInfo dut(kWidth, kHeight, kFx, kFy, kCx, kCy); Verify(expected, dut); } { SCOPED_TRACE("Matrix"); CameraInfo dut(kWidth, kHeight, expected); Verify(expected, dut); } } // The focal lengths become identical with this constructor. GTEST_TEST(TestCameraInfo, ConstructionWithFovTest) { const Matrix3d expected( (Matrix3d() << kFy, 0., kCx, 0., kFy, kCy, 0., 0., 1.).finished()); CameraInfo dut(kWidth, kHeight, kVerticalFov); Verify(expected, dut); } // Confirms that values that lie outside of the valid range throw. We're largely // going to focus on using the parameterized constructor (w, h, fx, fy, cx, cz) // even though the throwing happens in the matrix-based constructor. // // 1. It's simpler to iterate over different kinds of bad values via this // constructor compactly. // 2. We know it simply constructs a matrix and forwards it along, so we'll be // exercising that constructor. // // We will evaluate the matrix-based constructor to test for the "malformed // matrix condition". GTEST_TEST(TestCameraInfo, BadConstructionThrows) { constexpr double kInf = std::numeric_limits<double>::infinity(); constexpr double kNaN = std::numeric_limits<double>::quiet_NaN(); constexpr double kW = kWidth; constexpr double kH = kHeight; // Bad image size. DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(-13, kH, kFx, kFy, kCx, kCy), "[^]*Width.+-13[^]*"); DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, -17, kFx, kFy, kCx, kCy), "[^]*Height.+-17[^]*"); // Bad focal length. DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, kH, 0, kFy, kCx, kCy), "[^]*Focal X.+0[^]*"); DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, kH, -10, kFy, kCx, kCy), "[^]*Focal X.+-10[^]*"); DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, kH, kInf, kFy, kCx, kCy), "[^]*Focal X.+inf[^]*"); DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, kH, kNaN, kFy, kCx, kCy), "[^]*Focal X.+nan[^]*"); DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, kH, kFx, 0, kCx, kCy), "[^]*Focal Y.+0[^]*"); DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, kH, kFx, -10, kCx, kCy), "[^]*Focal Y.+-10[^]*"); DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, kH, kFx, kInf, kCx, kCy), "[^]*Focal Y.+inf[^]*"); DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, kH, kFx, kNaN, kCx, kCy), "[^]*Focal Y.+nan[^]*"); // Bad principal point. DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, kH, kFx, kFy, 0, kCy), "[^]*Center X.+0[^]*"); DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, kH, kFx, kFy, -10, kCy), "[^]*Center X.+-10[^]*"); DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, kH, kFx, kFy, kW, kCy), "[^]*Center X.+\\d+[^]*"); DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, kH, kFx, kFy, kW + 1, kCy), "[^]*Center X.+\\d+[^]*"); DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, kH, kFx, kFy, kCx, 0), "[^]*Center Y.+0[^]*"); DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, kH, kFx, kFy, kCx, -10), "[^]*Center Y.+-10[^]*"); DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, kH, kFx, kFy, kCx, kH), "[^]*Center Y.+\\d+[^]*"); DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, kH, kFx, kFy, kCx, kH + 1), "[^]*Center Y.+\\d+[^]*"); // All bad values get independently enumerated. try { CameraInfo(-1, -1, -1, -1, -1, -1); GTEST_FAIL() << "Didn't throw an exception!"; } catch (std::exception& e) { EXPECT_THAT(e.what(), ::testing::HasSubstr("Width")) << e.what(); EXPECT_THAT(e.what(), ::testing::HasSubstr("Height")) << e.what(); EXPECT_THAT(e.what(), ::testing::HasSubstr("Focal X")) << e.what(); EXPECT_THAT(e.what(), ::testing::HasSubstr("Focal Y")) << e.what(); EXPECT_THAT(e.what(), ::testing::HasSubstr("Center X")) << e.what(); EXPECT_THAT(e.what(), ::testing::HasSubstr("Center Y")) << e.what(); } // Test for a malformed matrix; we'll start with an otherwise valid matrix and // perturb the off-diagonal and homogeneous row entries to become "malformed". const Matrix3d K_valid( (Matrix3d() << kFy, 0., kCx, 0., kFy, kCy, 0., 0., 1.).finished()); EXPECT_NO_THROW(CameraInfo(kW, kH, K_valid)); const std::vector<std::pair<int, int>> indices{ {0, 1}, {1, 0}, {2, 0}, {2, 1}, {2, 2}}; for (auto [i, j] : indices) { Matrix3d K = K_valid; K(i, j) = -1; DRAKE_EXPECT_THROWS_MESSAGE(CameraInfo(kW, kH, K), "[^]*intrinsic matrix is malformed[^]*"); } } // Confirms that the reported field of view (in radians) is the same as is // given. GTEST_TEST(TestCameraInfo, FieldOfView) { // Pick some arbitrary angle that isn't a "nice" angle. const double fov_y = M_PI / 7; const double kEps = std::numeric_limits<double>::epsilon(); { // Square camera: fields of view are equal in x- and y-directions. CameraInfo camera(100, 100, fov_y); EXPECT_NEAR(camera.fov_y(), fov_y, kEps); EXPECT_NEAR(camera.fov_x(), fov_y, kEps); } { // Rectangular camera: has an identical *focal lengths* in the x- and y- // directions. But the rectangular image leads to different fields of view. const int w = 100; const int h = 200; CameraInfo camera{w, h, fov_y}; const double fov_x = 2 * atan(w * tan(fov_y / 2) / h); EXPECT_NEAR(camera.fov_y(), fov_y, kEps); EXPECT_NEAR(camera.fov_x(), fov_x, kEps); } } } // namespace } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/vtk_image_reader_writer_test.cc
#include <gmock/gmock.h> #include <gtest/gtest.h> // To ease build system upkeep, we annotate VTK includes with their deps. #include <vtkImageData.h> // vtkCommonDataModel #include <vtkImageExport.h> // vtkIOImage #include "drake/common/eigen_types.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/vtk_image_reader_writer.h" namespace drake { namespace systems { namespace sensors { namespace internal { namespace { namespace fs = std::filesystem; class VtkImageReaderWriterTest : public testing::TestWithParam<ImageIoTestParams> { public: VtkImageReaderWriterTest() = default; }; // Checks MakeWriter() and MakeReader() back-to-back. This provides a simple // sanity check for these low-level helper functions. TEST_P(VtkImageReaderWriterTest, RoundTrip) { const ImageIoTestParams& param = GetParam(); const ImageFileFormat format = param.format; const bool write_to_file = param.write_to_file; const int vtk_scalar = param.vtk_scalar(); // Create a sample image in memory. auto image = param.CreateIotaVtkImage(); // Check MakeWriter() construction. // Set it up to write either to `filename` xor `writer_output`. fs::path filename; std::vector<uint8_t> writer_output; vtkSmartPointer<vtkImageWriter> writer; if (write_to_file) { filename = fs::path(temp_directory()) / fmt::format("RoundTrip_{}.image", format); writer = MakeWriter(format, filename); } else { writer = MakeWriter(format, &writer_output); } ASSERT_TRUE(writer != nullptr); // Ask MakeWriter() to write out the image. writer->SetInputData(image.Get()); writer->Write(); // Check MakeReader(). vtkSmartPointer<vtkImageReader2> reader; if (write_to_file) { reader = MakeReader(format, filename); } else { reader = MakeReader(format, writer_output.data(), writer_output.size()); } ASSERT_TRUE(reader != nullptr); reader->Update(); // Check the image metadata. We'll use ASSERT not EXPECT because momentarily // we'll also compare the image data buffers, which we don't want to do when // the sizes were wrong. vtkNew<vtkImageExport> loader; loader->SetInputConnection(reader->GetOutputPort(0)); loader->Update(); const int* const dims = loader->GetDataDimensions(); ASSERT_EQ(dims[0], param.width()); ASSERT_EQ(dims[1], param.height()); ASSERT_EQ(dims[2], param.depth()); ASSERT_EQ(loader->GetDataNumberOfScalarComponents(), param.channels()); ASSERT_EQ(loader->GetDataScalarType(), vtk_scalar); const void* const original = image->GetScalarPointer(); const void* const readback = loader->GetPointerToData(); param.CompareImageBuffer(original, readback); } INSTANTIATE_TEST_SUITE_P(All, VtkImageReaderWriterTest, GetAllImageIoTestParams()); // Checks that an unsupported operation produces an error. GTEST_TEST(UnparameterizedVtkImageReaderWriterTest, TiffWriteToMemoryThrow) { std::vector<uint8_t> output; DRAKE_EXPECT_THROWS_MESSAGE(MakeWriter(ImageFileFormat::kTiff, &output), ".*TIFF.*memory buffer.*"); } } // namespace } // namespace internal } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/accelerometer_test.cc
#include "drake/systems/sensors/accelerometer.h" #include <gtest/gtest.h> #include "drake/common/eigen_types.h" #include "drake/common/find_resource.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/framework/test_utilities/scalar_conversion.h" namespace drake { namespace { using systems::BasicVector; using systems::sensors::Accelerometer; class AccelerometerTest : public ::testing::Test { protected: void SetUp() override { // Plant/System initialization. systems::DiagramBuilder<double> builder; plant_ = builder.AddSystem<multibody::MultibodyPlant>(0.0); const std::string urdf_name = FindResourceOrThrow("drake/examples/pendulum/Pendulum.urdf"); multibody::Parser parser(plant_); parser.AddModels(urdf_name); plant_->Finalize(); // Connect a pendulum to the accelerometer. const multibody::RigidBody<double>& arm_body = plant_->GetBodyByName("arm"); const math::RigidTransform<double> X_BS(Eigen::Vector3d(0, 0, -r_BS_)); gravity_ = plant_->gravity_field().gravity_vector(); accel_default_ = builder.AddSystem<Accelerometer>(arm_body, X_BS, gravity_); builder.Connect(plant_->get_body_poses_output_port(), accel_default_->get_body_poses_input_port()); builder.Connect(plant_->get_body_spatial_velocities_output_port(), accel_default_->get_body_velocities_input_port()); builder.Connect(plant_->get_body_spatial_accelerations_output_port(), accel_default_->get_body_accelerations_input_port()); const math::RigidTransform<double> X_BS_rotated( math::RotationMatrix<double>::MakeYRotation(M_PI / 2), Eigen::Vector3d(0, 0, -r_BS_)); accel_rotated_ = &Accelerometer<double>::AddToDiagram( arm_body, X_BS_rotated, gravity_, *plant_, &builder); diagram_ = builder.Build(); } double r_BS_ = 0.375; Eigen::Vector3d gravity_; const Accelerometer<double>* accel_default_; const Accelerometer<double>* accel_rotated_; std::unique_ptr<systems::Diagram<double>> diagram_; multibody::MultibodyPlant<double>* plant_; }; TEST_F(AccelerometerTest, DefaultRotation) { double tol = 10 * std::numeric_limits<double>::epsilon(); auto diagram_context = diagram_->CreateDefaultContext(); auto& plant_context = diagram_->GetMutableSubsystemContext(*plant_, diagram_context.get()); auto& accel_context = diagram_->GetMutableSubsystemContext( *accel_default_, diagram_context.get()); double angle = .5; // Test zero-velocity state. plant_->get_actuation_input_port().FixValue(&plant_context, Vector1d(0)); plant_->SetPositions(&plant_context, Vector1d(angle)); plant_->SetVelocities(&plant_context, Vector1d(0)); const auto& result = accel_default_->get_measurement_output_port().Eval<BasicVector<double>>( accel_context); // Compute expected result: // g/L sin(theta) double angular_acceleration = -gravity_.norm() / .5 * sin(angle); Eigen::Vector3d expected_result(-angular_acceleration * r_BS_, 0, 0); Eigen::Vector3d g_S(cos(angle) * gravity_(0) - sin(angle) * gravity_(2), gravity_(1), cos(angle) * gravity_(2) + sin(angle) * gravity_(0)); expected_result -= g_S; EXPECT_TRUE(CompareMatrices(result.get_value(), expected_result, tol)); // Test with non-zero velocity. double angular_velocity = -2; // g/L sin(theta) - b/(m * L^2) * thetadot double g = 9.81; // Constants below from URDF. double L = .5; double m = 1; double b = .1; angular_acceleration = -g / L * sin(angle) - b * angular_velocity / (m * L * L); plant_->SetVelocities(&plant_context, Vector1d(angular_velocity)); const auto& result_with_velocity = accel_default_->get_output_port(0).Eval<BasicVector<double>>( accel_context); Eigen::Vector3d expected_result_with_velocity( -angular_acceleration * r_BS_, 0, angular_velocity * angular_velocity * r_BS_); expected_result_with_velocity -= g_S; EXPECT_TRUE(CompareMatrices(result_with_velocity.get_value(), expected_result_with_velocity, tol)); } TEST_F(AccelerometerTest, Rotated) { double tol = 10 * std::numeric_limits<double>::epsilon(); auto diagram_context = diagram_->CreateDefaultContext(); auto& plant_context = diagram_->GetMutableSubsystemContext(*plant_, diagram_context.get()); auto& accel_context = diagram_->GetMutableSubsystemContext( *accel_rotated_, diagram_context.get()); double angle = .5; // Test zero-velocity state. plant_->get_actuation_input_port().FixValue(&plant_context, Vector1d(0)); plant_->SetPositions(&plant_context, Vector1d(angle)); plant_->SetVelocities(&plant_context, Vector1d(0)); const auto& result = accel_rotated_->get_output_port(0).Eval<BasicVector<double>>( accel_context); // Compute expected result: // g/L sin(theta) double angular_acceleration = -gravity_.norm() / .5 * sin(angle); Eigen::Vector3d expected_result(0, 0, -angular_acceleration * r_BS_); Eigen::Vector3d g_S(-cos(angle) * gravity_(2) - sin(angle) * gravity_(0), gravity_(1), cos(angle) * gravity_(0) - sin(angle) * gravity_(2)); expected_result -= g_S; EXPECT_TRUE(CompareMatrices(result.get_value(), expected_result, tol)); // Test with non-zero velocity. double angular_velocity = -2; // g/L sin(theta) - b/(m * L^2) * thetadot double g = 9.81; // Constants below from URDF. double L = .5; double m = 1; double b = .1; angular_acceleration = -g / L * sin(angle) - b * angular_velocity / (m * L * L); plant_->SetVelocities(&plant_context, Vector1d(angular_velocity)); const auto& result_with_velocity = accel_rotated_->get_output_port(0).Eval<BasicVector<double>>( accel_context); Eigen::Vector3d expected_result_with_velocity( -angular_velocity * angular_velocity * r_BS_, 0, -angular_acceleration * r_BS_); expected_result_with_velocity -= g_S; EXPECT_TRUE(CompareMatrices(result_with_velocity.get_value(), expected_result_with_velocity, tol)); } TEST_F(AccelerometerTest, ScalarConversionTest) { EXPECT_TRUE(is_autodiffxd_convertible(*accel_default_)); EXPECT_TRUE(is_symbolic_convertible(*accel_default_)); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/gyroscope_test.cc
#include "drake/systems/sensors/gyroscope.h" #include <gtest/gtest.h> #include "drake/common/eigen_types.h" #include "drake/common/find_resource.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/framework/test_utilities/scalar_conversion.h" namespace drake { namespace { using systems::BasicVector; using systems::sensors::Gyroscope; class GyroscopeTest : public ::testing::Test { protected: void SetUp() override { // Plant/System initialization. systems::DiagramBuilder<double> builder; plant_ = builder.AddSystem<multibody::MultibodyPlant>(0.0); const std::string urdf_name = FindResourceOrThrow("drake/examples/pendulum/Pendulum.urdf"); multibody::Parser parser(plant_); parser.AddModels(urdf_name); plant_->Finalize(); const multibody::RigidBody<double>& arm_body = plant_->GetBodyByName("arm"); const math::RotationMatrix<double> R_BS( drake::math::RollPitchYaw<double>(M_PI / 2, 0, 0)); const math::RigidTransform<double> X_BS(R_BS, Eigen::Vector3d::Zero()); gyroscope_ = &Gyroscope<double>::AddToDiagram(arm_body, X_BS, *plant_, &builder); diagram_ = builder.Build(); } const Gyroscope<double>* gyroscope_; std::unique_ptr<systems::Diagram<double>> diagram_; multibody::MultibodyPlant<double>* plant_; }; TEST_F(GyroscopeTest, Rotated) { double tol = 10 * std::numeric_limits<double>::epsilon(); auto diagram_context = diagram_->CreateDefaultContext(); auto& plant_context = diagram_->GetMutableSubsystemContext(*plant_, diagram_context.get()); auto& gyro_context = diagram_->GetMutableSubsystemContext(*gyroscope_, diagram_context.get()); double theta = M_PI / 2; double omega = .5; // Test zero-velocity state. plant_->get_actuation_input_port().FixValue(&plant_context, Vector1d(0)); plant_->SetPositions(&plant_context, Vector1d(theta)); plant_->SetVelocities(&plant_context, Vector1d(omega)); const auto& result = gyroscope_->get_measurement_output_port().Eval<BasicVector<double>>( gyro_context); // Compute expected result. // Angular velocity in world coordinates is (0, omega, 0). // In body coordinates, it is the same, (0, omega, 0). // The sensor frame is rotated by pi/2 about the x-axis, so // the expected measurement is (0, 0, -omega). Eigen::Vector3d expected_result(0, 0, -omega); EXPECT_TRUE(CompareMatrices(result.get_value(), expected_result, tol)); } TEST_F(GyroscopeTest, ScalarConversionTest) { EXPECT_TRUE(is_autodiffxd_convertible(*gyroscope_)); EXPECT_TRUE(is_symbolic_convertible(*gyroscope_)); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/image_test.cc
#include "drake/systems/sensors/image.h" #include <gtest/gtest.h> namespace drake { namespace systems { namespace sensors { namespace { const int kWidth = 640; const int kHeight = 480; const uint8_t kInitialValue = 100; GTEST_TEST(TestImage, EmptyTest0) { ImageRgb8U dut; EXPECT_EQ(dut.width(), 0); EXPECT_EQ(dut.height(), 0); EXPECT_EQ(dut.size(), 0); EXPECT_EQ(dut.kNumChannels, 3); EXPECT_EQ(dut.kPixelSize, 3); EXPECT_EQ(dut.kPixelFormat, PixelFormat::kRgb); } GTEST_TEST(TestImage, EmptyTest2) { ImageRgb8U dut(0, 0); EXPECT_EQ(dut.width(), 0); EXPECT_EQ(dut.height(), 0); EXPECT_EQ(dut.size(), 0); EXPECT_THROW(ImageRgb8U(0, 1), std::exception); EXPECT_THROW(ImageRgb8U(1, 0), std::exception); EXPECT_THROW(ImageRgb8U(-1, 1), std::exception); EXPECT_THROW(ImageRgb8U(1, -1), std::exception); } GTEST_TEST(TestImage, EmptyTest3) { ImageRgb8U dut(0, 0, 0); EXPECT_EQ(dut.width(), 0); EXPECT_EQ(dut.height(), 0); EXPECT_EQ(dut.size(), 0); EXPECT_THROW(ImageRgb8U(0, 1, 0), std::exception); EXPECT_THROW(ImageRgb8U(1, 0, 0), std::exception); EXPECT_THROW(ImageRgb8U(-1, 1, 0), std::exception); EXPECT_THROW(ImageRgb8U(1, -1, 0), std::exception); } GTEST_TEST(TestImage, InstantiateTest) { ImageBgr8U dut(kWidth, kHeight); const int kNumChannels = 3; EXPECT_EQ(dut.width(), kWidth); EXPECT_EQ(dut.height(), kHeight); EXPECT_EQ(dut.kNumChannels, kNumChannels); EXPECT_EQ(dut.kPixelSize, 3); EXPECT_EQ(dut.size(), kWidth * kHeight * kNumChannels); EXPECT_EQ(dut.kPixelFormat, PixelFormat::kBgr); } GTEST_TEST(TestImage, InitializeAndAccessToPixelValuesTest) { // If you don't give initial value, the default value is zero. ImageRgba8U dut(kWidth, kHeight); ImageRgba8U dut2(kWidth, kHeight, kInitialValue); for (int u = 0; u < kWidth; ++u) { for (int v = 0; v < kHeight; ++v) { for (int channel = 0; channel < dut.kNumChannels; ++channel) { EXPECT_EQ(dut.at(u, v)[channel], 0); EXPECT_EQ(dut2.at(u, v)[channel], kInitialValue); } } } EXPECT_EQ(dut.kPixelFormat, PixelFormat::kRgba); EXPECT_EQ(dut.kPixelSize, 4); EXPECT_EQ(dut2.kPixelFormat, PixelFormat::kRgba); } GTEST_TEST(TestImage, CopyConstructorTest) { ImageBgra8U image(kWidth, kHeight, kInitialValue); ImageBgra8U dut(image); ImageBgra8U dut2 = image; EXPECT_EQ(dut.width(), image.width()); EXPECT_EQ(dut.height(), image.height()); EXPECT_EQ(dut.kNumChannels, image.kNumChannels); EXPECT_EQ(dut.kPixelSize, 4); EXPECT_EQ(dut2.width(), image.width()); EXPECT_EQ(dut2.height(), image.height()); EXPECT_EQ(dut2.kNumChannels, image.kNumChannels); EXPECT_EQ(dut2.kPixelSize, 4); EXPECT_EQ(image.kPixelFormat, PixelFormat::kBgra); EXPECT_EQ(dut.kPixelFormat, PixelFormat::kBgra); EXPECT_EQ(dut2.kPixelFormat, PixelFormat::kBgra); for (int u = 0; u < kWidth; ++u) { for (int v = 0; v < kHeight; ++v) { for (int channel = 0; channel < image.kNumChannels; ++channel) { EXPECT_EQ(dut.at(u, v)[channel], image.at(u, v)[channel]); EXPECT_EQ(dut2.at(u, v)[channel], image.at(u, v)[channel]); } } } } GTEST_TEST(TestImage, AssignmentOperatorTest) { ImageDepth32F image(kWidth, kHeight, kInitialValue); ImageDepth32F dut(1, 1); dut = image; EXPECT_EQ(dut.width(), image.width()); EXPECT_EQ(dut.height(), image.height()); EXPECT_EQ(dut.kNumChannels, image.kNumChannels); EXPECT_EQ(dut.kPixelFormat, PixelFormat::kDepth); EXPECT_EQ(dut.kPixelSize, 4); EXPECT_EQ(image.kPixelFormat, PixelFormat::kDepth); for (int u = 0; u < kWidth; ++u) { for (int v = 0; v < kHeight; ++v) { for (int channel = 0; channel < image.kNumChannels; ++channel) { EXPECT_EQ(dut.at(u, v)[channel], image.at(u, v)[channel]); } } } } GTEST_TEST(TestImage, MoveConstructorTest) { ImageLabel16I image(kWidth, kHeight, kInitialValue); ImageLabel16I dut(std::move(image)); const int kNumChannels = 1; EXPECT_EQ(dut.width(), kWidth); EXPECT_EQ(dut.height(), kHeight); EXPECT_EQ(dut.kNumChannels, kNumChannels); EXPECT_EQ(dut.kPixelFormat, PixelFormat::kLabel); EXPECT_EQ(dut.kPixelSize, 2); EXPECT_EQ(image.width(), 0); EXPECT_EQ(image.height(), 0); EXPECT_EQ(image.kNumChannels, kNumChannels); EXPECT_EQ(image.kPixelFormat, PixelFormat::kLabel); for (int u = 0; u < kWidth; ++u) { for (int v = 0; v < kHeight; ++v) { for (int channel = 0; channel < image.kNumChannels; ++channel) { EXPECT_EQ(dut.at(u, v)[channel], kInitialValue); } } } } GTEST_TEST(TestImage, MoveAssignmentOperatorTest) { ImageGrey8U image(kWidth, kHeight, kInitialValue); ImageGrey8U dut(kWidth / 2, kHeight / 2); dut = std::move(image); const int kNumChannels = 1; EXPECT_EQ(dut.width(), kWidth); EXPECT_EQ(dut.height(), kHeight); EXPECT_EQ(dut.kNumChannels, kNumChannels); EXPECT_EQ(dut.kPixelFormat, PixelFormat::kGrey); EXPECT_EQ(dut.kPixelSize, 1); EXPECT_EQ(image.width(), 0); EXPECT_EQ(image.height(), 0); EXPECT_EQ(image.kNumChannels, kNumChannels); EXPECT_EQ(image.kPixelFormat, PixelFormat::kGrey); for (int u = 0; u < kWidth; ++u) { for (int v = 0; v < kHeight; ++v) { for (int channel = 0; channel < image.kNumChannels; ++channel) { EXPECT_EQ(dut.at(u, v)[channel], kInitialValue); } } } } GTEST_TEST(TestImage, ResizeTest) { ImageDepth16U dut(kWidth, kHeight); const int kWidthResized = 64; const int kHeightResized = 48; const int kNumChannels = 1; // Resize to non-zero. dut.resize(kWidthResized, kHeightResized); EXPECT_EQ(dut.width(), kWidthResized); EXPECT_EQ(dut.height(), kHeightResized); EXPECT_EQ(dut.kNumChannels, kNumChannels); EXPECT_EQ(dut.kPixelFormat, PixelFormat::kDepth); EXPECT_EQ(dut.kPixelSize, 2); EXPECT_EQ(dut.size(), kWidthResized * kHeightResized * kNumChannels); // Invalid resizes. EXPECT_THROW(dut.resize(0, 1), std::exception); EXPECT_THROW(dut.resize(1, 0), std::exception); EXPECT_THROW(dut.resize(-1, 1), std::exception); EXPECT_THROW(dut.resize(1, -1), std::exception); // Resize to zero. dut.resize(0, 0); EXPECT_EQ(dut.width(), 0); EXPECT_EQ(dut.height(), 0); EXPECT_EQ(dut.size(), 0); } GTEST_TEST(ImageTest, DepthImage32FTo16U) { // Create a list of test inputs and outputs (pixels). using InPixel = ImageDepth32F::Traits; using OutPixel = ImageDepth16U::Traits; const std::vector<std::pair<float, uint16_t>> test_cases{ // Too close or too far. {InPixel::kTooClose, OutPixel::kTooClose}, {InPixel::kTooFar, OutPixel::kTooFar}, // Valid distances for both pixel types. {3.0f, 3000}, {10.0f, 10000}, // Valid distance for input pixel, but saturates the output pixel. {100.0f, OutPixel::kTooFar}, // Input pixels approaching the saturation point of the output pixel. {65.531f, 65531}, {65.534001f, 65534}, {65.535f, 65535}, {65.536f, OutPixel::kTooFar}, {65.537f, OutPixel::kTooFar}, // Crazy input value. {-1.0f, OutPixel::kTooClose}, // Special values. {-std::numeric_limits<float>::infinity(), OutPixel::kTooClose}, {std::numeric_limits<float>::infinity(), OutPixel::kTooFar}, {std::numeric_limits<float>::quiet_NaN(), OutPixel::kTooFar}, }; // Check each pair of input and output pixel values. for (const auto& [pixel_in, pixel_out] : test_cases) { SCOPED_TRACE(fmt::format("pixel_in = {}", pixel_in)); ImageDepth32F image_in(1, 1); ImageDepth16U image_out(1, 1); image_in.at(0, 0)[0] = pixel_in; ConvertDepth32FTo16U(image_in, &image_out); ASSERT_EQ(image_out.width(), 1); ASSERT_EQ(image_out.height(), 1); EXPECT_EQ(image_out.at(0, 0)[0], pixel_out); } // Check that height and width auto-resizing is correct. ImageDepth32F image_in(3, 4); ImageDepth16U image_out; ConvertDepth32FTo16U(image_in, &image_out); EXPECT_EQ(image_out.width(), image_in.width()); EXPECT_EQ(image_out.height(), image_in.height()); image_in.resize(0, 0); ConvertDepth32FTo16U(image_in, &image_out); EXPECT_EQ(image_out.width(), 0); EXPECT_EQ(image_out.height(), 0); } GTEST_TEST(ImageTest, DepthImage16UTo32F) { // Create a list of test inputs and outputs (pixels). using InPixel = ImageDepth16U::Traits; using OutPixel = ImageDepth32F::Traits; const std::vector<std::pair<uint16_t, float>> test_cases{ // Too close or too far. {InPixel::kTooClose, OutPixel::kTooClose}, {InPixel::kTooFar, OutPixel::kTooFar}, // Valid distances for both pixel types. {3000, 3.0f}, {10000, 10.0f}, }; // Check each pair of input and output pixel values. for (const auto& [pixel_in, pixel_out] : test_cases) { SCOPED_TRACE(fmt::format("pixel_in = {}", pixel_in)); ImageDepth16U image_in(1, 1); ImageDepth32F image_out(1, 1); image_in.at(0, 0)[0] = pixel_in; ConvertDepth16UTo32F(image_in, &image_out); ASSERT_EQ(image_out.width(), 1); ASSERT_EQ(image_out.height(), 1); EXPECT_EQ(image_out.at(0, 0)[0], pixel_out); } // Check that height and width auto-resizing is correct. ImageDepth16U image_in(3, 4); ImageDepth32F image_out; ConvertDepth16UTo32F(image_in, &image_out); EXPECT_EQ(image_out.width(), image_in.width()); EXPECT_EQ(image_out.height(), image_in.height()); image_in.resize(0, 0); ConvertDepth16UTo32F(image_in, &image_out); EXPECT_EQ(image_out.width(), 0); EXPECT_EQ(image_out.height(), 0); } } // namespace } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/rgbd_sensor_discrete_test.cc
#include "drake/systems/sensors/rgbd_sensor_discrete.h" #include <gtest/gtest.h> #include "drake/geometry/scene_graph.h" #include "drake/systems/primitives/zero_order_hold.h" namespace drake { namespace systems { namespace sensors { namespace { using geometry::SceneGraph; using geometry::render::DepthRenderCamera; using math::RigidTransformd; using std::make_unique; using std::vector; // Tests that the discrete sensor is properly constructed. GTEST_TEST(RgbdSensorDiscrete, Construction) { const DepthRenderCamera depth_camera( {"render", {640, 480, M_PI / 4}, {0.1, 10.0}, {}}, {0.1, 10}); const double kPeriod = 0.1; const bool include_render_port = true; // N.B. In addition to testing a discrete sensor, this also tests // the `RgbdSensor` constructor which takes only `DepthRenderCamera`. RgbdSensorDiscrete sensor( make_unique<RgbdSensor>(SceneGraph<double>::world_frame_id(), RigidTransformd::Identity(), depth_camera), kPeriod, include_render_port); 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"); // Confirm that the period was passed into the ZOH correctly. If the ZOH // reports the expected period, we rely on it to do the right thing. EXPECT_EQ(sensor.period(), kPeriod); } // Test that the diagram's internal architecture is correct and, likewise, // wired correctly. GTEST_TEST(RgbdSensorDiscrete, ImageHold) { const DepthRenderCamera depth_camera( {"render", {640, 480, M_PI / 4}, {0.1, 10.0}, {}}, {0.1, 10}); // N.B. In addition to testing a discrete sensor, this also tests // the `RgbdSensor` constructor which takes only `DepthRenderCamera`. auto sensor = make_unique<RgbdSensor>(SceneGraph<double>::world_frame_id(), RigidTransformd::Identity(), depth_camera); RgbdSensor* sensor_raw = sensor.get(); const int num_outputs = sensor_raw->num_output_ports(); const double kPeriod = 0.1; const bool include_render_port = true; RgbdSensorDiscrete discrete_sensor(std::move(sensor), kPeriod, include_render_port); EXPECT_EQ(discrete_sensor.num_output_ports(), num_outputs); // This tests very *explicit* knowledge of what the wiring should be. As such, // it's a bit brittle, but this is the most efficient way to affect this test. // We assume these systems are reported in the order they were added. vector<const System<double>*> sub_systems = discrete_sensor.GetSystems(); // For our diagram's sub-systems, we expect to have the sensor and then one // zero-order hold per output port. ASSERT_EQ(sub_systems.size(), 1 + num_outputs); ASSERT_EQ(sub_systems[0], sensor_raw); // For each output port, we want to make sure it's connected to the expected // zero-order hold and that the hold's period is kPeriod. This proves that // RgbdSensorDiscrete has wired things up properly. auto confirm_hold = [&sensor_raw, &sub_systems, &kPeriod, &discrete_sensor](int port_index) { const auto* zoh = dynamic_cast<const ZeroOrderHold<double>*>( sub_systems.at(1 + port_index)); ASSERT_NE(zoh, nullptr); EXPECT_EQ(zoh->period(), kPeriod); EXPECT_TRUE(discrete_sensor.AreConnected( sensor_raw->get_output_port(port_index), zoh->get_input_port())); }; for (int i = 0; i < num_outputs; ++i) { SCOPED_TRACE(fmt::format("i = {}", i)); confirm_hold(i); } // TODO(SeanCurtis-TRI): Consider confirming that the exported ports map to // the expected sub-system ports. } } // namespace } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/sensors
/home/johnshepherd/drake/systems/sensors/test/image_io_test_params.cc
#include "drake/systems/sensors/test/image_io_test_params.h" #include <numeric> namespace drake { namespace systems { namespace sensors { vtkNew<vtkImageData> ImageIoTestParams::CreateIotaVtkImage() const { vtkNew<vtkImageData> image; image->SetDimensions(width(), height(), depth()); image->AllocateScalars(vtk_scalar(), channels()); if (vtk_scalar() == VTK_TYPE_UINT8) { auto* dest = reinterpret_cast<uint8_t*>(image->GetScalarPointer()); std::iota(dest, dest + total_storage(), uint8_t{0x01}); } else if (vtk_scalar() == VTK_TYPE_UINT16) { auto* dest = reinterpret_cast<uint16_t*>(image->GetScalarPointer()); std::iota(dest, dest + total_storage(), uint16_t{0x0001}); } else { auto* dest = reinterpret_cast<float*>(image->GetScalarPointer()); std::iota(dest, dest + total_storage(), 1.0f); } return image; } ImageAny ImageIoTestParams::CreateIotaDrakeImage() const { if (force_gray && pixel_scalar() == PixelScalar::k8U) { DRAKE_DEMAND(channels() == 1); ImageGrey8U result(width(), height()); auto* dest = result.at(0, 0); std::iota(dest, dest + result.size(), uint8_t{0x01}); return result; } if (alpha && pixel_scalar() == PixelScalar::k8U) { DRAKE_DEMAND(channels() == 4); ImageRgba8U result(width(), height()); auto* dest = result.at(0, 0); std::iota(dest, dest + result.size(), uint8_t{0x01}); return result; } if (pixel_scalar() == PixelScalar::k8U) { DRAKE_DEMAND(channels() == 3); ImageRgb8U result(width(), height()); auto* dest = result.at(0, 0); std::iota(dest, dest + result.size(), uint8_t{0x01}); return result; } if (pixel_scalar() == PixelScalar::k16U) { DRAKE_DEMAND(channels() == 1); ImageDepth16U result(width(), height()); auto* dest = result.at(0, 0); std::iota(dest, dest + result.size(), uint16_t{0x0001}); return result; } if (pixel_scalar() == PixelScalar::k32F) { DRAKE_DEMAND(channels() == 1); ImageDepth32F result(width(), height()); auto* dest = result.at(0, 0); std::iota(dest, dest + result.size(), 1.0f); return result; } throw std::logic_error("CreateIotaDrakeImage unsupported params"); } void ImageIoTestParams::CompareImageBuffer(const void* original, const void* readback) const { // For JPEG images, we can't exactly compare the pixels because the lossy // compression algorithm will have adjusted them slightly. if (format == ImageFileFormat::kJpeg) { // Instead, we'll check that the data is still monotonically increasing // (within some tolerance). This is sufficient to notice if any data was // mistakenly transposed. DRAKE_DEMAND(pixel_scalar() == PixelScalar::k8U); auto* loaded = reinterpret_cast<const uint8_t*>(readback); Eigen::Map<const MatrixX<uint8_t>> head(loaded, 1, total_storage() - 1); Eigen::Map<const MatrixX<uint8_t>> tail(loaded + 1, 1, total_storage() - 1); const Eigen::Array<int, 1, Eigen::Dynamic> increments = tail.cast<int>().array() - head.cast<int>().array(); const int max_increment = 2; EXPECT_LE(increments.abs().maxCoeff(), max_increment) << fmt::to_string(fmt_eigen(increments.matrix())); return; } // Compare the loaded pixels to the original image. We'll compare using // an Eigen::Map wrapper over the image data, to get a better printout. if (pixel_scalar() == PixelScalar::k8U) { auto* orig = reinterpret_cast<const uint8_t*>(original); auto* loaded = reinterpret_cast<const uint8_t*>(readback); Eigen::Map<const MatrixX<uint8_t>> orig_map(orig, 1, total_storage()); Eigen::Map<const MatrixX<uint8_t>> loaded_map(loaded, 1, total_storage()); EXPECT_EQ(orig_map.template cast<int>(), loaded_map.template cast<int>()); } else if (pixel_scalar() == PixelScalar::k16U) { auto* orig = reinterpret_cast<const uint16_t*>(original); auto* loaded = reinterpret_cast<const uint16_t*>(readback); Eigen::Map<const MatrixX<uint16_t>> orig_map(orig, 1, total_storage()); Eigen::Map<const MatrixX<uint16_t>> loaded_map(loaded, 1, total_storage()); EXPECT_EQ(orig_map, loaded_map); } else { DRAKE_DEMAND(pixel_scalar() == PixelScalar::k32F); auto* orig = reinterpret_cast<const float*>(original); auto* loaded = reinterpret_cast<const float*>(readback); Eigen::Map<const MatrixX<float>> orig_map(orig, 1, total_storage()); Eigen::Map<const MatrixX<float>> loaded_map(loaded, 1, total_storage()); EXPECT_EQ(orig_map, loaded_map); } } } // namespace sensors } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/benchmarking/framework_benchmarks.cc
#include <benchmark/benchmark.h> #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/primitives/adder.h" #include "drake/systems/primitives/pass_through.h" #include "drake/tools/performance/fixture_common.h" /* A collection of scenarios to benchmark, scoped to cover all code within the drake/systems/framework package. */ namespace drake { namespace systems { namespace { class BasicFixture : public benchmark::Fixture { public: BasicFixture() { tools::performance::AddMinMaxStatistics(this); } void SetUp(benchmark::State&) override { builder_ = std::make_unique<DiagramBuilder<double>>(); } void Build() { diagram_ = builder_->Build(); context_ = diagram_->CreateDefaultContext(); builder_.reset(); } protected: std::unique_ptr<DiagramBuilder<double>> builder_; std::unique_ptr<Diagram<double>> diagram_; std::unique_ptr<Context<double>> context_; }; // NOLINTNEXTLINE(runtime/references) cpplint disapproves of gbench choices. BENCHMARK_F(BasicFixture, PassThrough3)(benchmark::State& state) { const int n = 7; auto* alpha = builder_->AddSystem<PassThrough<double>>(n); auto* bravo = builder_->AddSystem<PassThrough<double>>(n); auto* charlie = builder_->AddSystem<PassThrough<double>>(n); builder_->ExportInput(alpha->get_input_port()); builder_->Cascade(*alpha, *bravo); builder_->Cascade(*bravo, *charlie); builder_->ExportOutput(charlie->get_output_port()); Build(); Eigen::VectorXd value = Eigen::VectorXd::Constant(n, 22.2); auto& input = diagram_->get_input_port().FixValue(context_.get(), value); auto& output = diagram_->get_output_port(); for (auto _ : state) { // Invalidate the furthest upstream CacheEntry, in order to force // re-computation of all downstream values. This also mimics a common // scenario of interest, where the inputs change on every tick. input.GetMutableData(); output.Eval(*context_); } } // Helper function for the DiagramBuild benchmark. Creates a diagram containing // num_systems subsystems. When depth==0, each subsystem is an Adder, otherwise // each subsystem is a recursive self-call with the next smaller depth. std::unique_ptr<DiagramBuilder<double>> MakeDiagramBuilder(int num_systems, int depth) { DRAKE_DEMAND(num_systems > 0); DRAKE_DEMAND(depth >= 0); auto builder = std::make_unique<DiagramBuilder<double>>(); std::vector<System<double>*> children; for (int i = 0; i < num_systems; ++i) { if (depth == 0) { children.push_back(builder->AddSystem<Adder>(num_systems, 1)); } else { children.push_back(builder->AddSystem( MakeDiagramBuilder(num_systems, depth - 1)->Build())); } System<double>* child = children.back(); // The child's input ports are connected either to the other childrens' // output ports (when possible), or else the diagram's input ports. for (int j = 0; j < num_systems; ++j) { const InputPort<double>& input = child->get_input_port(j); if (j < i) { builder->Connect(children.at(j)->get_output_port(), input); } else { if (i == 0) { builder->ExportInput(input, fmt::to_string(j)); } else { builder->ConnectInput(fmt::to_string(j), input); } } } } builder->ExportOutput(children.back()->get_output_port()); return builder; } void DiagramBuild(benchmark::State& state) { // NOLINT const int num_systems = state.range(0); const int depth = state.range(1); std::unique_ptr<DiagramBuilder<double>> builder; std::unique_ptr<Diagram<double>> diagram; for (auto _ : state) { // Create a DiagramBuilder, sans timekeeping. state.PauseTiming(); diagram.reset(); builder = MakeDiagramBuilder(num_systems, depth); state.ResumeTiming(); // Time the Build operation. diagram = builder->Build(); } } BENCHMARK(DiagramBuild) ->Unit(benchmark::kMillisecond) ->Args({3, 0}) ->Args({30, 0}) ->Args({3, 1}) ->Args({3, 2}); } // namespace } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/benchmarking/BUILD.bazel
load("//tools/lint:lint.bzl", "add_lint_tests") load( "//tools/performance:defs.bzl", "drake_cc_googlebench_binary", "drake_py_experiment_binary", ) package(default_visibility = ["//visibility:private"]) drake_cc_googlebench_binary( name = "framework_benchmarks", srcs = ["framework_benchmarks.cc"], add_test_rule = True, deps = [ "//common:add_text_logging_gflags", "//systems/framework:diagram_builder", "//systems/primitives:adder", "//systems/primitives:pass_through", "//tools/performance:fixture_common", "//tools/performance:gflags_main", ], ) drake_py_experiment_binary( name = "framework_experiment", googlebench_binary = ":framework_benchmarks", ) drake_cc_googlebench_binary( name = "multilayer_perceptron_benchmark", srcs = ["multilayer_perceptron_benchmark.cc"], add_test_rule = True, deps = [ "//common:add_text_logging_gflags", "//systems/primitives:multilayer_perceptron", "//tools/performance:fixture_common", "//tools/performance:gflags_main", ], ) drake_py_experiment_binary( name = "multilayer_perceptron_experiment", googlebench_binary = ":multilayer_perceptron_benchmark", ) add_lint_tests()
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/benchmarking/README.md
Runtime Performance Benchmarks for Dynamical Systems ---------------------------------------------------- ## Supported experiments On Ubuntu, the following commands will build code and save result data to a user supplied directory, under relatively controlled conditions: $ bazel run //systems/benchmarking:framework_experiment -- --output_dir=trial1 $ bazel run //systems/benchmarking:multilayer_perceptron_experiment -- --output_dir=trial2 ## Additional information Documentation for command line arguments is here: https://github.com/google/benchmark#command-line
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/benchmarking/multilayer_perceptron_benchmark.cc
/* @file Measures the performance of the MultilayerPerceptron implementation. Refer to the README.md for more information. */ #include <gflags/gflags.h> #include "drake/systems/primitives/multilayer_perceptron.h" #include "drake/tools/performance/fixture_common.h" namespace drake { namespace systems { namespace { using Eigen::MatrixXd; using Eigen::RowVectorXd; using Eigen::VectorXd; // TODO(jwnimmer-tri) Add benchmarking cases for input sin/cos features. class Mlp : public benchmark::Fixture { public: Mlp() { tools::performance::AddMinMaxStatistics(this); this->Unit(benchmark::kMicrosecond); } void SetUp(benchmark::State& state) { // NOLINT(runtime/references) // Number of inputs. const int num_inputs = state.range(0); DRAKE_DEMAND(num_inputs >= 1); // Number of layers. const int num_layers = state.range(1); DRAKE_DEMAND(num_layers >= 2); // Number of units in each hidden layer. const int width = state.range(2); DRAKE_DEMAND(width >= 1); // Use 1 output so that we can call BatchOutput with gradients. const int num_outputs = 1; // Number of batch evaluations. const int batch_size = state.range(3); DRAKE_DEMAND(batch_size >= 1); // Create the MLP. std::vector<int> layers; layers.push_back(num_inputs); for (int i = 0; i < (num_layers - 2); ++i) { layers.push_back(width); } layers.push_back(num_outputs); mlp_ = std::make_unique<MultilayerPerceptron<double>>(layers); // Prepare the input/output matrix storage. X_ = MatrixXd::Ones(num_inputs, batch_size); Y_.resize(batch_size); dloss_dparams_.resize(mlp_->num_parameters()); Yd_ = RowVectorXd::Ones(batch_size); dYdX_.resize(num_inputs, batch_size); // Prepare a random context. context_ = mlp_->CreateDefaultContext(); RandomGenerator generator(243); mlp_->SetRandomContext(context_.get(), &generator); } protected: std::unique_ptr<MultilayerPerceptron<double>> mlp_; std::unique_ptr<Context<double>> context_; MatrixXd X_; RowVectorXd Y_; RowVectorXd dloss_dparams_; RowVectorXd Yd_; MatrixXd dYdX_; }; BENCHMARK_DEFINE_F(Mlp, Backprop)(benchmark::State& state) { // NOLINT for (auto _ : state) { mlp_->BackpropagationMeanSquaredError(*context_, X_, Yd_, &dloss_dparams_); } } // The Args are { num_inputs, num_layers, width, batch_size }. A few notes // about common parameter values: // - The default architecture in stablebaselines3 has 4 layers, width=64. // - It's relatively rare to have MLPs with more than 8 layers. // - Batch sizes tend to be powers of 2 (16, 32, ..., 256). // - Width also tends to be powers of 2 (64, 128, ...). BENCHMARK_REGISTER_F(Mlp, Backprop) ->Args({10, 4, 64, 32}) ->Args({10, 4, 64, 64}) ->Args({10, 4, 64, 128}) ->Args({10, 4, 64, 256}) ->Args({10, 4, 128, 128}) ->Args({10, 4, 256, 256}) ->Args({128, 4, 64, 256}) ->Args({128, 8, 64, 256}); BENCHMARK_DEFINE_F(Mlp, Output)(benchmark::State& state) { // NOLINT for (auto _ : state) { mlp_->BatchOutput(*context_, X_, &Y_); } } // The Args are { num_inputs, num_layers, width, batch_size }. BENCHMARK_REGISTER_F(Mlp, Output) ->Args({10, 4, 64, 32}) ->Args({10, 4, 64, 64}) ->Args({10, 4, 64, 128}) ->Args({10, 4, 64, 256}) ->Args({10, 4, 128, 128}) ->Args({10, 4, 256, 256}) ->Args({128, 4, 64, 256}) ->Args({128, 8, 64, 256}); BENCHMARK_DEFINE_F(Mlp, OutputGradient)(benchmark::State& state) { // NOLINT for (auto _ : state) { mlp_->BatchOutput(*context_, X_, &Y_, &dYdX_); } } // The Args are { num_inputs, num_layers, width, batch_size }. BENCHMARK_REGISTER_F(Mlp, OutputGradient) ->Args({10, 4, 64, 32}) ->Args({10, 4, 64, 64}) ->Args({10, 4, 64, 128}) ->Args({10, 4, 64, 256}) ->Args({10, 4, 128, 128}) ->Args({10, 4, 256, 256}) ->Args({128, 4, 64, 256}) ->Args({128, 8, 64, 256}); } // namespace } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/joint_stiffness_controller.cc
#include "drake/systems/controllers/joint_stiffness_controller.h" #include <utility> #include <vector> namespace drake { namespace systems { namespace controllers { using multibody::MultibodyForces; using multibody::MultibodyPlant; using Eigen::VectorXd; template <typename T> JointStiffnessController<T>::JointStiffnessController( std::unique_ptr<multibody::MultibodyPlant<T>> owned_plant, const MultibodyPlant<T>* plant, const Eigen::Ref<const Eigen::VectorXd>& kp, const Eigen::Ref<const Eigen::VectorXd>& kd) : LeafSystem<T>(SystemTypeTag<JointStiffnessController>{}), owned_plant_(std::move(owned_plant)), plant_(owned_plant_ ? owned_plant_.get() : plant), kp_(kp), kd_(kd) { // Exactly one of owned_plant_ or plant should have been nullptr. DRAKE_DEMAND(owned_plant_ == nullptr || plant == nullptr); DRAKE_DEMAND(plant_ != nullptr); DRAKE_DEMAND(plant_->is_finalized()); const int num_states = plant_->num_multibody_states(); const int num_q = plant_->num_positions(); DRAKE_DEMAND(num_q == plant_->num_velocities()); DRAKE_DEMAND(num_q == plant_->num_actuated_dofs()); DRAKE_DEMAND(plant_->IsVelocityEqualToQDot()); DRAKE_DEMAND(kp.size() == num_q); DRAKE_DEMAND(kd.size() == num_q); input_port_index_estimated_state_ = this->DeclareInputPort("estimated_state", kVectorValued, num_states) .get_index(); input_port_index_desired_state_ = this->DeclareInputPort("desired_state", kVectorValued, num_states) .get_index(); // Forces need to be recalculated when any input has changed but have no // other dependencies. Specifying this here is also essential so that that // GetDirectFeedthrough won't attempt to cast to Symbolic for evaluation // (which would fail if the plant is not owned). output_port_index_force_ = this->DeclareVectorOutputPort( "generalized_force", num_q, &JointStiffnessController<T>::CalcOutputForce, {this->all_input_ports_ticket()}) .get_index(); auto plant_context = plant_->CreateDefaultContext(); // Declare cache entry for the multibody plant context. plant_context_cache_index_ = this->DeclareCacheEntry( "plant_context_cache", *plant_context, &JointStiffnessController<T>::SetMultibodyContext, {this->input_port_ticket( get_input_port_estimated_state().get_index())}) .cache_index(); // Declare external forces cache entry applied_forces_cache_index_ = this->DeclareCacheEntry( "applied_forces_cache", MultibodyForces<T>(*plant_), &JointStiffnessController<T>::CalcMultibodyForces, {this->cache_entry_ticket(plant_context_cache_index_)}) .cache_index(); } template <typename T> JointStiffnessController<T>::JointStiffnessController( const MultibodyPlant<T>& plant, const Eigen::Ref<const Eigen::VectorXd>& kp, const Eigen::Ref<const Eigen::VectorXd>& kd) : JointStiffnessController(nullptr, &plant, kp, kd) {} template <typename T> JointStiffnessController<T>::JointStiffnessController( std::unique_ptr<multibody::MultibodyPlant<T>> plant, const Eigen::Ref<const Eigen::VectorXd>& kp, const Eigen::Ref<const Eigen::VectorXd>& kd) : JointStiffnessController(std::move(plant), nullptr, kp, kd) {} template <typename T> template <typename U> JointStiffnessController<T>::JointStiffnessController( const JointStiffnessController<U>& other) : JointStiffnessController( systems::System<U>::template ToScalarType<T>(*other.plant_), other.kp_, other.kd_) {} template <typename T> JointStiffnessController<T>::~JointStiffnessController() = default; template <typename T> void JointStiffnessController<T>::SetMultibodyContext( const Context<T>& context, Context<T>* plant_context) const { const VectorX<T>& x = get_input_port_estimated_state().Eval(context); plant_->SetPositionsAndVelocities(plant_context, x); } template <typename T> void JointStiffnessController<T>::CalcMultibodyForces( const Context<T>& context, MultibodyForces<T>* cache_value) const { const auto& plant_context = this->get_cache_entry(plant_context_cache_index_) .template Eval<Context<T>>(context); plant_->CalcForceElementsContribution(plant_context, cache_value); } template <typename T> void JointStiffnessController<T>::CalcOutputForce( const Context<T>& context, BasicVector<T>* output) const { const int num_q = plant_->num_positions(); const auto& plant_context = this->get_cache_entry(plant_context_cache_index_) .template Eval<Context<T>>(context); // These include gravity. const auto& applied_forces = this->get_cache_entry(applied_forces_cache_index_) .template Eval<MultibodyForces<T>>(context); // Compute inverse dynamics with zero generalized accelerations. // ID(q, v, v̇) = M(q)v̇ + C(q, v)v - tau_app // So with v̇ = 0 we get: // ID(q, v, 0) = C(q,v)v - tau_app(q). VectorX<T> tau = plant_->CalcInverseDynamics( plant_context, VectorX<T>::Zero(num_q), /* vdot = 0 */ applied_forces); // Subtract off C(q,v)v // Note: we do not simply set v=0 because we want to be able to cancel the // contribution from damping forces. VectorX<T> Cv(num_q); plant_->CalcBiasTerm(plant_context, &Cv); tau -= Cv; // Add in the stiffness terms. const VectorX<T>& x = get_input_port_estimated_state().Eval(context); const VectorX<T>& x_d = get_input_port_desired_state().Eval(context); tau += (kp_.array() * (x_d.head(num_q) - x.head(num_q)).array() + kd_.array() * (x_d.tail(num_q) - x.tail(num_q)).array()) .matrix(); output->get_mutable_value() = tau; } } // namespace controllers } // namespace systems } // namespace drake DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::controllers::JointStiffnessController)
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/linear_quadratic_regulator.h
#pragma once #include <memory> #include "drake/systems/primitives/linear_system.h" namespace drake { namespace systems { namespace controllers { struct LinearQuadraticRegulatorResult { Eigen::MatrixXd K; Eigen::MatrixXd S; }; /// Computes the optimal feedback controller, u=-Kx, and the optimal /// cost-to-go J = x'Sx for the problem: /// /// @f[ \min_u \int_0^\infty x'Qx + u'Ru + 2x'Nu dt @f] /// @f[ \dot{x} = Ax + Bu @f] /// @f[ Fx = 0 @f] /// /// @param A The state-space dynamics matrix of size num_states x num_states. /// @param B The state-space input matrix of size num_states x num_inputs. /// @param Q A symmetric positive semi-definite cost matrix of size num_states x /// num_states. /// @param R A symmetric positive definite cost matrix of size num_inputs x /// num_inputs. /// @param N A cost matrix of size num_states x num_inputs. If N.rows() == 0, N /// will be treated as a num_states x num_inputs zero matrix. /// @param F A constraint matrix of size num_constraints x num_states. rank(F) /// must be < num_states. If F.rows() == 0, F will be treated as a 0 x /// num_states zero matrix. /// @returns A structure that contains the optimal feedback gain K and the /// quadratic cost term S. The optimal feedback control is u = -Kx; /// /// @throws std::exception if R is not positive definite. /// @note The system (A₁, B) should be stabilizable, where A₁=A−BR⁻¹Nᵀ. /// @note The system (Q₁, A₁) should be detectable, where Q₁=Q−NR⁻¹Nᵀ. /// @ingroup control /// @pydrake_mkdoc_identifier{AB} /// LinearQuadraticRegulatorResult LinearQuadraticRegulator( const Eigen::Ref<const Eigen::MatrixXd>& A, const Eigen::Ref<const Eigen::MatrixXd>& B, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const Eigen::MatrixXd>& R, const Eigen::Ref<const Eigen::MatrixXd>& N = Eigen::Matrix<double, 0, 0>::Zero(), const Eigen::Ref<const Eigen::MatrixXd>& F = Eigen::Matrix<double, 0, 0>::Zero()); // TODO(russt): Consider implementing the optional N argument as in the // continuous-time formulation. /// Computes the optimal feedback controller, u=-Kx, and the optimal /// cost-to-go J = x'Sx for the problem: /// /// @f[ x[n+1] = Ax[n] + Bu[n] @f] /// @f[ \min_u \sum_0^\infty x'Qx + u'Ru @f] /// /// @param A The state-space dynamics matrix of size num_states x num_states. /// @param B The state-space input matrix of size num_states x num_inputs. /// @param Q A symmetric positive semi-definite cost matrix of size num_states x /// num_states. /// @param R A symmetric positive definite cost matrix of size num_inputs x /// num_inputs. /// @returns A structure that contains the optimal feedback gain K and the /// quadratic cost term S. The optimal feedback control is u = -Kx; /// /// @throws std::exception if R is not positive definite. /// @ingroup control LinearQuadraticRegulatorResult DiscreteTimeLinearQuadraticRegulator( const Eigen::Ref<const Eigen::MatrixXd>& A, const Eigen::Ref<const Eigen::MatrixXd>& B, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const Eigen::MatrixXd>& R); /// Creates a system that implements the optimal time-invariant linear quadratic /// regulator (LQR). If @p system is a continuous-time system, then solves /// the continuous-time LQR problem: /// /// @f[ \min_u \int_0^\infty x^T(t)Qx(t) + u^T(t)Ru(t) + + 2x^T(t)Nu(t) dt. /// @f] /// /// If @p system is a discrete-time system, then solves the discrete-time LQR /// problem: /// /// @f[ \min_u \sum_0^\infty x^T[n]Qx[n] + u^T[n]Ru[n] + 2x^T[n]Nu[n]. @f] /// /// @param system The System to be controlled. /// @param Q A symmetric positive semi-definite cost matrix of size num_states x /// num_states. /// @param R A symmetric positive definite cost matrix of size num_inputs x /// num_inputs. /// @param N A cost matrix of size num_states x num_inputs. /// @returns A system implementing the optimal controller in the original system /// coordinates. /// /// @throws std::exception if R is not positive definite. /// @ingroup control_systems /// @pydrake_mkdoc_identifier{system} /// std::unique_ptr<LinearSystem<double>> LinearQuadraticRegulator( const LinearSystem<double>& system, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const Eigen::MatrixXd>& R, const Eigen::Ref<const Eigen::MatrixXd>& N = Eigen::Matrix<double, 0, 0>::Zero()); /// Linearizes the System around the specified Context, computes the optimal /// time-invariant linear quadratic regulator (LQR), and returns a System which /// implements that regulator in the original System's coordinates. If /// @p system is a continuous-time system, then solves /// the continuous-time LQR problem: /// /// @f[ \min_u \int_0^\infty (x-x_0)^TQ(x-x_0) + (u-u_0)^TR(u-u_0) + 2 /// (x-x_0)^TN(u-u_0) dt. @f] /// /// If @p system is a discrete-time system, then solves the discrete-time LQR /// problem: /// /// @f[ \min_u \sum_0^\infty (x-x_0)^TQ(x-x_0) + (u-u_0)^TR(u-u_0) + /// 2(x-x_0)^TN(u-u_0), @f] /// /// where @f$ x_0 @f$ is the nominal state and @f$ u_0 @f$ is the nominal input. /// The system is considered discrete if it has a single discrete state /// vector and a single unique periodic update event declared. /// /// @param system The System to be controlled. /// @param context Defines the desired state and control input to regulate the /// system to. Note that this state/input must be an equilibrium point of the /// system. See drake::systems::Linearize for more details. /// @param Q A symmetric positive semi-definite cost matrix of size num_states x /// num_states. /// @param R A symmetric positive definite cost matrix of size num_inputs x /// num_inputs. /// @param N A cost matrix of size num_states x num_inputs. If the matrix is /// zero-sized, N will be treated as a num_states x num_inputs zero matrix. /// @param input_port_index The index of the input port to linearize around. /// @returns A system implementing the optimal controller in the original system /// coordinates. /// /// @throws std::exception if R is not positive definite. /// @ingroup control_systems /// @see drake::systems::Linearize() /// @pydrake_mkdoc_identifier{linearize_at_context} /// std::unique_ptr<AffineSystem<double>> LinearQuadraticRegulator( const System<double>& system, const Context<double>& context, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const Eigen::MatrixXd>& R, const Eigen::Ref<const Eigen::MatrixXd>& N = Eigen::Matrix<double, 0, 0>::Zero(), int input_port_index = 0); } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/BUILD.bazel
load("@bazel_skylib//rules:copy_file.bzl", "copy_file") load("//tools/lint:lint.bzl", "add_lint_tests") load( "//tools/skylark:drake_cc.bzl", "drake_cc_googletest", "drake_cc_library", "drake_cc_package_library", ) package(default_visibility = ["//visibility:public"]) drake_cc_package_library( name = "controllers", visibility = ["//visibility:public"], deps = [ ":dynamic_programming", ":finite_horizon_linear_quadratic_regulator", ":inverse_dynamics", ":inverse_dynamics_controller", ":joint_stiffness_controller", ":linear_model_predictive_controller", ":linear_quadratic_regulator", ":pid_controlled_system", ":pid_controller", ":state_feedback_controller_interface", ":zmp_planner", ], ) drake_cc_library( name = "state_feedback_controller_interface", hdrs = ["state_feedback_controller_interface.h"], deps = [ "//systems/framework:system", ], ) drake_cc_library( name = "dynamic_programming", srcs = ["dynamic_programming.cc"], hdrs = ["dynamic_programming.h"], deps = [ "//common:essential", "//math:wrap_to", "//solvers:mathematical_program", "//solvers:solve", "//systems/analysis:simulator", "//systems/framework", "//systems/primitives:barycentric_system", ], ) drake_cc_library( name = "finite_horizon_linear_quadratic_regulator", srcs = ["finite_horizon_linear_quadratic_regulator.cc"], hdrs = ["finite_horizon_linear_quadratic_regulator.h"], deps = [ "//common/trajectories", "//math:autodiff", "//math:gradient", "//math:matrix_util", "//systems/analysis:simulator", "//systems/analysis:simulator_config_functions", "//systems/framework", ], ) drake_cc_library( name = "inverse_dynamics", srcs = ["inverse_dynamics.cc"], hdrs = ["inverse_dynamics.h"], deps = [ "//multibody/plant", "//systems/framework", ], ) drake_cc_library( name = "inverse_dynamics_controller", srcs = ["inverse_dynamics_controller.cc"], hdrs = ["inverse_dynamics_controller.h"], deps = [ ":inverse_dynamics", ":pid_controller", ":state_feedback_controller_interface", "//multibody/plant", "//systems/framework", "//systems/primitives:adder", "//systems/primitives:constant_vector_source", "//systems/primitives:demultiplexer", "//systems/primitives:pass_through", ], ) drake_cc_library( name = "joint_stiffness_controller", srcs = ["joint_stiffness_controller.cc"], hdrs = ["joint_stiffness_controller.h"], deps = [ "//multibody/plant", "//systems/framework", ], ) drake_cc_library( name = "linear_model_predictive_controller", srcs = ["linear_model_predictive_controller.cc"], hdrs = ["linear_model_predictive_controller.h"], deps = [ "//common/trajectories:piecewise_polynomial", "//planning/trajectory_optimization:direct_transcription", "//solvers:solve", "//systems/primitives:linear_system", ], ) drake_cc_library( name = "linear_quadratic_regulator", srcs = ["linear_quadratic_regulator.cc"], hdrs = ["linear_quadratic_regulator.h"], deps = [ "//common:is_approx_equal_abstol", "//math:continuous_algebraic_riccati_equation", "//math:discrete_algebraic_riccati_equation", "//systems/framework", "//systems/primitives:linear_system", ], ) drake_cc_library( name = "pid_controller", srcs = ["pid_controller.cc"], hdrs = ["pid_controller.h"], deps = [ ":state_feedback_controller_interface", "//systems/framework:leaf_system", "//systems/primitives:matrix_gain", ], ) drake_cc_library( name = "pid_controlled_system", srcs = ["pid_controlled_system.cc"], hdrs = ["pid_controlled_system.h"], deps = [ ":pid_controller", "//systems/primitives:adder", "//systems/primitives:constant_vector_source", "//systems/primitives:saturation", ], ) # We use a copy_file to de-clutter the deprecation stub. # TODO(2024-08-01) Remove along with deprecation (also the load statement). copy_file( name = "_copy_zmp", src = "stub/zmp_planner.h", out = "zmp_planner.h", allow_symlink = True, ) # TODO(2024-08-01) Remove along with deprecation. drake_cc_library( name = "zmp_planner", hdrs = ["zmp_planner.h"], deps = [ "//planning/locomotion:zmp_planner", ], ) # === test/ === drake_cc_googletest( name = "dynamic_programming_test", # Test timeout increased to not timeout when run with Valgrind. timeout = "long", data = [ "//examples/pendulum:models", ], deps = [ ":dynamic_programming", ":linear_quadratic_regulator", "//common/proto:call_python", "//common/test_utilities:eigen_matrix_compare", "//multibody/parsing", "//multibody/plant", "//systems/framework:diagram_builder", "//systems/primitives:integrator", "//systems/primitives:linear_system", ], ) drake_cc_googletest( name = "finite_horizon_linear_quadratic_regulator_test", deps = [ ":finite_horizon_linear_quadratic_regulator", ":linear_quadratic_regulator", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_no_throw", "//systems/framework/test_utilities:scalar_conversion", "//systems/primitives:linear_system", "//systems/primitives:symbolic_vector_system", ], ) drake_cc_googletest( name = "inverse_dynamics_test", data = [ "@drake_models//:iiwa_description", ], deps = [ ":inverse_dynamics", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_throws_message", "//multibody/parsing", "//systems/controllers/test_utilities", ], ) drake_cc_googletest( name = "inverse_dynamics_controller_test", data = [ "@drake_models//:iiwa_description", ], deps = [ ":inverse_dynamics_controller", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_throws_message", "//multibody/parsing", "//systems/controllers/test_utilities", ], ) drake_cc_googletest( name = "joint_stiffness_controller_test", data = [ "//multibody/benchmarks/acrobot:models", "@drake_models//:iiwa_description", ], deps = [ ":joint_stiffness_controller", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_throws_message", "//multibody/parsing", ], ) drake_cc_googletest( name = "linear_model_predictive_controller_test", deps = [ ":linear_model_predictive_controller", "//common/test_utilities:eigen_matrix_compare", "//math:discrete_algebraic_riccati_equation", "//systems/analysis:simulator", ], ) drake_cc_googletest( name = "linear_quadratic_regulator_test", data = ["//examples/acrobot:models"], deps = [ ":linear_quadratic_regulator", "//common:find_resource", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_no_throw", "//examples/acrobot:acrobot_plant", "//multibody/parsing", "//multibody/plant", ], ) drake_cc_googletest( name = "pid_controlled_system_test", deps = [ ":pid_controlled_system", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_no_throw", ], ) drake_cc_googletest( name = "pid_controller_test", deps = [ ":pid_controller", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_no_throw", ], ) drake_cc_googletest( name = "deprecated_zmp_planner_test", copts = ["-Wno-deprecated-declarations"], deps = [ ":zmp_planner", ], ) add_lint_tests(enable_clang_format_lint = False)
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/inverse_dynamics.h
#pragma once #include <memory> #include <stdexcept> #include "drake/common/default_scalars.h" #include "drake/common/drake_copyable.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/framework/leaf_system.h" namespace drake { namespace systems { namespace controllers { /** * Solves inverse dynamics with no consideration for joint actuator force * limits. * * Computes the generalized force `τ_id` that needs to be applied so that the * multibody system undergoes a desired acceleration `vd_d`. That is, `τ_id` * is the result of an inverse dynamics computation according to: * <pre> * τ_id = M(q)vd_d + C(q, v)v - τ_g(q) - τ_app * </pre> * where `M(q)` is the mass matrix, `C(q, v)v` is the bias term containing * Coriolis and gyroscopic effects, `τ_g(q)` is the vector of generalized * forces due to gravity and `τ_app` contains applied forces from force * elements added to the multibody model (this can include damping, springs, * etc. See MultibodyPlant::CalcForceElementsContribution()). * * The system also provides a pure gravity compensation mode via an option in * the constructor. In this case, the output is simply * <pre> * τ_id = -τ_g(q). * </pre> * * @note As an alternative to adding a controller to your diagram, gravity * compensation can be modeled by disabling gravity for a given model instance, * see MultibodyPlant::set_gravity_enabled(). * * InverseDynamicsController uses a PID controller to generate desired * acceleration and uses this class to compute generalized forces. Use this * class directly if desired acceleration is computed differently. * * @system * name: InverseDynamics * input_ports: * - estimated_state * - <span style="color:gray">desired_acceleration</span> * output_ports: * - generalized_force * @endsystem * * The desired acceleration port shown in <span style="color:gray">gray</span> * is only present when the `mode` at construction is not * `kGravityCompensation`. * * @tparam_default_scalar * @ingroup control_systems */ template <typename T> class InverseDynamics final : public LeafSystem<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(InverseDynamics); enum InverseDynamicsMode { /// Full inverse computation mode. kInverseDynamics, /// Purely gravity compensation mode. kGravityCompensation }; /** * Constructs the InverseDynamics system. * * @param plant Pointer to the multibody plant model. The life span of * `plant` must be longer than that of this instance. * @param mode If set to kGravityCompensation, this instance will only * consider the gravity term. It also will NOT have the desired acceleration * input port. * @param plant_context A specific context of `plant` to use for computing * inverse dynamics. For example, you can use this to pass in a context with * modified mass parameters. If `nullptr`, the default context of the given * `plant` is used. Note that this will be copied at time of construction, so * there are no lifetime constraints. * @pre The plant must be finalized (i.e., plant.is_finalized() must return * `true`). Also, `plant_context`, if provided, must be compatible with * `plant`. */ explicit InverseDynamics(const multibody::MultibodyPlant<T>* plant, InverseDynamicsMode mode = kInverseDynamics, const Context<T>* plant_context = nullptr); /** * Constructs the InverseDynamics system and takes the ownership of the * input `plant`. * * @exclude_from_pydrake_mkdoc{This overload is not bound.} */ explicit InverseDynamics(std::unique_ptr<multibody::MultibodyPlant<T>> plant, InverseDynamicsMode mode = kInverseDynamics, const Context<T>* plant_context = nullptr); // Scalar-converting copy constructor. See @ref system_scalar_conversion. template <typename U> explicit InverseDynamics(const InverseDynamics<U>& other); ~InverseDynamics() override; /** * Returns the input port for the estimated state. */ const InputPort<T>& get_input_port_estimated_state() const { return this->get_input_port(estimated_state_); } /** * Returns the input port for the desired acceleration. */ const InputPort<T>& get_input_port_desired_acceleration() const { DRAKE_THROW_UNLESS(!this->is_pure_gravity_compensation()); return this->get_input_port(desired_acceleration_); } /** * Returns the output port for the generalized forces that realize the desired * acceleration. The dimension of that force vector will be identical to the * dimensionality of the generalized velocities. */ const OutputPort<T>& get_output_port_generalized_force() const { return this->get_output_port(generalized_force_); } bool is_pure_gravity_compensation() const { return mode_ == InverseDynamicsMode::kGravityCompensation; } private: // Other constructors delegate to this private constructor. InverseDynamics(std::unique_ptr<multibody::MultibodyPlant<T>> owned_plant, const multibody::MultibodyPlant<T>* plant, InverseDynamicsMode mode, const Context<T>* plant_context); // Helper data structure for scalar conversion. struct ScalarConversionData { std::unique_ptr<multibody::MultibodyPlant<T>> plant; InverseDynamicsMode mode{InverseDynamicsMode::kGravityCompensation}; std::unique_ptr<Context<T>> plant_context; }; // Helper function for the scalar conversion constructor that extracts the // plant context from `other` and scalar converts it to this scalar type, T. template <typename U> static ScalarConversionData ScalarConvertHelper( const InverseDynamics<U>& other); // Delegate constructor for scalar conversion. explicit InverseDynamics(ScalarConversionData&& data); template <typename> friend class InverseDynamics; // This is the calculator method for the output port. void CalcOutputForce(const Context<T>& context, BasicVector<T>* force) const; // Methods for updating cache entries. void SetMultibodyContext(const Context<T>&, Context<T>*) const; void CalcMultibodyForces(const Context<T>&, multibody::MultibodyForces<T>*) const; const std::unique_ptr<multibody::MultibodyPlant<T>> owned_plant_{}; const multibody::MultibodyPlant<T>* const plant_; // Mode dictates whether to do inverse dynamics or just gravity compensation. const InverseDynamicsMode mode_; InputPortIndex estimated_state_; InputPortIndex desired_acceleration_; OutputPortIndex generalized_force_; const int q_dim_; const int v_dim_; // Note: unused in gravity compensation mode. CacheIndex external_forces_cache_index_; CacheIndex plant_context_cache_index_; }; } // namespace controllers } // namespace systems } // namespace drake DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::controllers::InverseDynamics)
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/linear_quadratic_regulator.cc
#include "drake/systems/controllers/linear_quadratic_regulator.h" #include <optional> #include <Eigen/QR> #include "drake/common/drake_assert.h" #include "drake/common/is_approx_equal_abstol.h" #include "drake/math/continuous_algebraic_riccati_equation.h" #include "drake/math/discrete_algebraic_riccati_equation.h" #include "drake/systems/primitives/linear_system.h" namespace drake { namespace systems { namespace controllers { namespace { // Compute the kernel of a matrix F, returns P such that the rows of P are the // basis for the null-space of F, namely PPᵀ = I and PFᵀ = 0 // TODO(hongkai.dai): expose this function to the header, and allow different // matrix factorization methods. Eigen::MatrixXd ComputeKernel(const Eigen::Ref<const Eigen::MatrixXd>& F) { // Compute the null-space based on QR decomposition. If Fᵀ*S = [Q1 Q2][R; 0] // = Q1*R, then take P=Q2ᵀ, where S is the permutation matrix. Eigen::ColPivHouseholderQR<Eigen::MatrixXd> qr_F(F.transpose()); if (qr_F.info() != Eigen::Success) { throw std::runtime_error( "LinearQuadraticRegulator(): QR decomposition on F.transpose() " "fails"); } const Eigen::MatrixXd F_Q = qr_F.matrixQ(); const int n = F.cols(); const Eigen::MatrixXd P = F_Q.rightCols(n - qr_F.rank()).transpose(); return P; } } // namespace LinearQuadraticRegulatorResult LinearQuadraticRegulator( const Eigen::Ref<const Eigen::MatrixXd>& A, const Eigen::Ref<const Eigen::MatrixXd>& B, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const Eigen::MatrixXd>& R, const Eigen::Ref<const Eigen::MatrixXd>& N, const Eigen::Ref<const Eigen::MatrixXd>& F) { Eigen::Index n = A.rows(), m = B.cols(); DRAKE_DEMAND(n > 0 && m > 0); DRAKE_DEMAND(B.rows() == n && A.cols() == n); DRAKE_DEMAND(Q.rows() == n && Q.cols() == n); DRAKE_DEMAND(R.rows() == m && R.cols() == m); // N is default to Matrix<double, 0, 0>. if (N.rows() != 0) { DRAKE_DEMAND(N.rows() == n && N.cols() == m); } // F is default to Matrix<double, 0, 0>. if (F.rows() != 0) { DRAKE_DEMAND(F.cols() == n); } DRAKE_DEMAND(is_approx_equal_abstol(R, R.transpose(), 1e-10)); LinearQuadraticRegulatorResult ret; Eigen::LLT<Eigen::MatrixXd> R_cholesky(R); if (R_cholesky.info() != Eigen::Success) throw std::runtime_error("R must be positive definite"); // The rows of P are the orthonormal basis for the null-space of F, namely PPᵀ // = I and PFᵀ = 0 std::optional<Eigen::MatrixXd> P = std::nullopt; if (F.rows() != 0) { // P is the kernel of F. // We introduce projected state y, such that y = Px. // We form a new dynamical system // ẏ = PAPᵀy + PBu // If the original cost is // ∫ xᵀQx + uᵀRu // The cost in terms of y and u is // ∫ yᵀPQPᵀy + uᵀRu P = ComputeKernel(F); } if (N.rows() != 0) { // This is equivalent to the LQR problem of the following modified system // min ∫xᵀQ₁x + u̅ᵀRu̅ // ẋ = A₁x + Bu̅ // where u̅ = u + R⁻¹Nᵀx and Q₁=Q−NR⁻¹Nᵀ, A₁=A−BR⁻¹Nᵀ Eigen::MatrixXd Q1 = Q - N * R_cholesky.solve(N.transpose()); Eigen::MatrixXd A1 = A - B * R_cholesky.solve(N.transpose()); if (F.rows() == 0) { ret.S = math::ContinuousAlgebraicRiccatiEquation(A1, B, Q1, R_cholesky); ret.K = R_cholesky.solve(B.transpose() * ret.S + N.transpose()); } else { const Eigen::MatrixXd Sy = math::ContinuousAlgebraicRiccatiEquation( (*P) * A1 * P->transpose(), (*P) * B, (*P) * Q1 * P->transpose(), R_cholesky); ret.S = P->transpose() * Sy * (*P); // We know N_y = P*N // u = -R⁻¹(B_yᵀS_y + N_yᵀ)y // = -R⁻¹(BᵀPᵀ * PSPᵀ + NᵀPᵀ)*Px // = -R⁻¹(BᵀS+NᵀPᵀP) // Note that PᵀP != I since P is not full rank (although PPᵀ=I). ret.K = R_cholesky.solve(B.transpose() * ret.S + N.transpose() * P->transpose() * (*P)); } } else { if (F.rows() == 0) { ret.S = math::ContinuousAlgebraicRiccatiEquation(A, B, Q, R_cholesky); } else { ret.S = P->transpose() * math::ContinuousAlgebraicRiccatiEquation( (*P) * A * P->transpose(), (*P) * B, (*P) * Q * P->transpose(), R_cholesky) * (*P); } ret.K = R_cholesky.solve(B.transpose() * ret.S); } return ret; } LinearQuadraticRegulatorResult DiscreteTimeLinearQuadraticRegulator( const Eigen::Ref<const Eigen::MatrixXd>& A, const Eigen::Ref<const Eigen::MatrixXd>& B, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const Eigen::MatrixXd>& R) { Eigen::Index n = A.rows(), m = B.cols(); DRAKE_DEMAND(n > 0 && m > 0); DRAKE_DEMAND(B.rows() == n && A.cols() == n); DRAKE_DEMAND(Q.rows() == n && Q.cols() == n); DRAKE_DEMAND(R.rows() == m && R.cols() == m); DRAKE_DEMAND(is_approx_equal_abstol(R, R.transpose(), 1e-10)); LinearQuadraticRegulatorResult ret; ret.S = math::DiscreteAlgebraicRiccatiEquation(A, B, Q, R); Eigen::MatrixXd tmp = B.transpose() * ret.S * B + R; ret.K = tmp.llt().solve(B.transpose() * ret.S * A); return ret; } std::unique_ptr<systems::LinearSystem<double>> LinearQuadraticRegulator( const LinearSystem<double>& system, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const Eigen::MatrixXd>& R, const Eigen::Ref<const Eigen::MatrixXd>& N) { // DiscreteTimeLinearQuadraticRegulator does not support N yet. DRAKE_DEMAND(system.time_period() == 0.0 || N.rows() == 0); const int num_states = system.B().rows(), num_inputs = system.B().cols(); LinearQuadraticRegulatorResult lqr_result = (system.time_period() == 0.0) ? LinearQuadraticRegulator(system.A(), system.B(), Q, R, N) : DiscreteTimeLinearQuadraticRegulator(system.A(), system.B(), Q, R); // Return the controller: u = -Kx. return std::make_unique<systems::LinearSystem<double>>( Eigen::Matrix<double, 0, 0>::Zero(), // A Eigen::MatrixXd::Zero(0, num_states), // B Eigen::MatrixXd::Zero(num_inputs, 0), // C -lqr_result.K, // D system.time_period()); } std::unique_ptr<systems::AffineSystem<double>> LinearQuadraticRegulator( const System<double>& system, const Context<double>& context, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const Eigen::MatrixXd>& R, const Eigen::Ref<const Eigen::MatrixXd>& N, int input_port_index) { // TODO(russt): accept optional additional argument to return the cost-to-go // but note that it will be a full quadratic form (x'S2x + s1'x + s0). const int num_inputs = system.get_input_port(input_port_index).size(); const int num_states = context.num_total_states(); DRAKE_DEMAND(num_states > 0); // The Linearize method call below will verify that the system has either // continuous-time OR (only simple) discrete-time dynamics. // TODO(russt): Confirm behavior if Q is not PSD. // Use specified input and no outputs (the output dynamics are irrelevant for // LQR design). auto linear_system = Linearize( system, context, InputPortIndex{input_port_index}, OutputPortSelection::kNoOutput); // DiscreteTimeLinearQuadraticRegulator does not support N yet. DRAKE_DEMAND(linear_system->time_period() == 0.0 || N.rows() == 0); LinearQuadraticRegulatorResult lqr_result = (linear_system->time_period() == 0.0) ? LinearQuadraticRegulator(linear_system->A(), linear_system->B(), Q, R, N) : DiscreteTimeLinearQuadraticRegulator(linear_system->A(), linear_system->B(), Q, R); const Eigen::VectorXd& x0 = (linear_system->time_period() == 0.0) ? context.get_continuous_state_vector().CopyToVector() : context.get_discrete_state(0).CopyToVector(); const auto& u0 = system.get_input_port(input_port_index).Eval(context); // Return the affine controller: u = u0 - K(x-x0). return std::make_unique<systems::AffineSystem<double>>( Eigen::Matrix<double, 0, 0>::Zero(), // A Eigen::MatrixXd::Zero(0, num_states), // B Eigen::Matrix<double, 0, 1>::Zero(), // xDot0 Eigen::MatrixXd::Zero(num_inputs, 0), // C -lqr_result.K, // D u0 + lqr_result.K * x0, // y0 linear_system->time_period()); } } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/joint_stiffness_controller.h
#pragma once #include <memory> #include <stdexcept> #include "drake/common/default_scalars.h" #include "drake/common/drake_copyable.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/framework/leaf_system.h" namespace drake { namespace systems { namespace controllers { // TODO(russt): Consider adding a feed-forward torque, τ_ff. It's not a // priority since it's trivial to add it to the output of this system with an // Adder block. /** * Implements a joint-space stiffness controller of the form * <pre> * τ_control = −τ_g(q) − τ_app + kp⊙(q_d − q) + kd⊙(v_d − v) * </pre> * where `Kp` and `Kd` are the joint stiffness and damping coefficients, * respectively, `τ_g(q)` is the vector of generalized forces due to gravity, * and `τ_app` contains applied forces from force elements added to the * multibody model (this can include damping, springs, etc. See * MultibodyPlant::CalcForceElementsContribution()). `q_d` and `v_d` are the * desired (setpoint) values for the multibody positions and velocities, * respectively. `kd` and `kp` are taken as vectors, and ⊙ represents * elementwise multiplication. * * The goal of this controller is to produce a closed-loop dynamics that * resembles a spring-damper dynamics at the joints around the setpoint: * <pre> * M(q)v̇ + C(q,v)v + kp⊙(q - q_d) + kd⊙(v - v_d) = τ_ext, * </pre> * where `M(q)v̇ + C(q,v)v` are the original multibody mass and Coriolis terms, * and `τ_ext` are any external generalized forces that can arise, e.g. from * contact forces. * * The controller currently requires that plant.num_positions() == * plant.num_velocities() == plant.num_actuated_dofs() and that * plant.IsVelocityEqualToQDot() is true. * * @system * name: JointStiffnessController * input_ports: * - estimated_state * - desired_state * output_ports: * - generalized_force * @endsystem * * Note that the joint impedance control as implemented on Kuka's iiwa and * Franka' Panda is best modeled as a stiffness controller (unless one were to * model the actual elastic joints and rotor-inertia shaping). See * https://manipulation.csail.mit.edu/force.html for more details. * * @tparam_default_scalar * @ingroup control_systems */ template <typename T> class JointStiffnessController final : public LeafSystem<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(JointStiffnessController) /** * Constructs the JointStiffnessController system. * * @param plant Reference to the multibody plant model. The life span of @p * plant must be at least as long as that of this instance. * @pre The plant must be finalized (i.e., plant.is_finalized() must return * `true`). * @pre plant.num_positions() == plant.num_velocities() == * plant.num_actuated_dofs() == kp.size() == kd.size() * @pre plant.IsVelocityEqualToQDot() is true. */ JointStiffnessController(const multibody::MultibodyPlant<T>& plant, const Eigen::Ref<const Eigen::VectorXd>& kp, const Eigen::Ref<const Eigen::VectorXd>& kd); /** * Constructs the JointStiffnessController system and takes the ownership of * the input `plant`. * @pre The plant must be finalized (i.e., plant.is_finalized() must return * `true`). * @pre plant.num_positions() == plant.num_velocities() == * plant.num_actuated_dofs() == kp.size() == kd.size() * @pre plant.IsVelocityEqualToQDot() is true. * * @exclude_from_pydrake_mkdoc{This overload is not bound.} */ explicit JointStiffnessController( std::unique_ptr<multibody::MultibodyPlant<T>> plant, const Eigen::Ref<const Eigen::VectorXd>& kp, const Eigen::Ref<const Eigen::VectorXd>& kd); // Scalar-converting copy constructor. See @ref system_scalar_conversion. template <typename U> explicit JointStiffnessController(const JointStiffnessController<U>& other); ~JointStiffnessController() override; // TODO(russt): Add support for safety limits. The iiwa driver will fault if // the desired state and the estimated state are too far apart. We should // support that (optional) feature here -- it's not very iiwa-specific. /** * Returns the input port for the estimated state. */ const InputPort<T>& get_input_port_estimated_state() const { return this->get_input_port(input_port_index_estimated_state_); } /** * Returns the input port for the desired state. */ const InputPort<T>& get_input_port_desired_state() const { return this->get_input_port(input_port_index_desired_state_); } /** * Returns the output port for the generalized forces implementing the * control. */ const OutputPort<T>& get_output_port_generalized_force() const { return this->get_output_port(output_port_index_force_); } /** * Returns a constant pointer to the MultibodyPlant used for control. */ const multibody::MultibodyPlant<T>& get_multibody_plant() const { return *plant_; } private: // Other constructors delegate to this private constructor. JointStiffnessController( std::unique_ptr<multibody::MultibodyPlant<T>> owned_plant, const multibody::MultibodyPlant<T>* plant, const Eigen::Ref<const Eigen::VectorXd>& kp, const Eigen::Ref<const Eigen::VectorXd>& kd); template <typename> friend class JointStiffnessController; // This is the calculator method for the output port. void CalcOutputForce(const Context<T>& context, BasicVector<T>* force) const; // Methods for updating cache entries. void SetMultibodyContext(const Context<T>&, Context<T>*) const; void CalcMultibodyForces(const Context<T>&, multibody::MultibodyForces<T>*) const; const std::unique_ptr<multibody::MultibodyPlant<T>> owned_plant_{}; const multibody::MultibodyPlant<T>* const plant_; int input_port_index_estimated_state_{0}; int input_port_index_desired_state_{0}; int output_port_index_force_{0}; Eigen::VectorXd kp_, kd_; drake::systems::CacheIndex applied_forces_cache_index_; drake::systems::CacheIndex plant_context_cache_index_; }; #ifdef DRAKE_DOXYGEN_CXX /** Drake does not yet offer a joint impedance controller, which would use * feedback to shape the stiffness, damping, *and inertia* of the closed-loop * system. We do however offer JointStiffnessController which uses feedback to * shape the closed-loop stiffness and damping. Most modern control stacks, * such as the JointImpedanceControl mode on Kuka's iiwa and Franka's Panda, are * actually better modeled as stiffness control (unless one is also modeling the * details of the elastic joints and rotor-interia shaping). * * See https://manipulation.csail.mit.edu/force.html for more details. * @see JointStiffnessController. * * @ingroup control_systems */ class JointImpedanceController {}; #endif } // namespace controllers } // namespace systems } // namespace drake DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::controllers::JointStiffnessController)
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/linear_model_predictive_controller.h
#pragma once #include <memory> #include "drake/common/drake_copyable.h" #include "drake/common/trajectories/piecewise_polynomial.h" #include "drake/systems/primitives/linear_system.h" namespace drake { namespace systems { namespace controllers { /// Implements a basic Model Predictive Controller that linearizes the system /// about an equilibrium condition and regulates to the same point by solving an /// optimal control problem over a finite time horizon. In particular, MPC /// solves, at each time step k, the following problem to find an optimal u(k) /// as a function of x(k): /// /// @f[ \min_{u(k),\ldots,u(k+N),x(k+1),\ldots,x(k+N)} /// \sum_{i=k}^{k+N} ((x(i) - xd(i))ᵀQ(x(i) - xd(i)) + /// (u(i) - ud(i))ᵀR(u(i) - ud(i))) @f] /// @f[ \mathrm{s.t. } x(k+1) = A(k)x(k) + B(k)u(k) @f] /// /// and subject to linear inequality constraints on the inputs and states, where /// N is the horizon length, Q and R are cost matrices, and xd and ud are the /// desired states and inputs, respectively. Note that the present /// implementation solves the QP in whole at every time step, discarding any /// information between steps. /// /// @system /// name: LinearModelPredictiveController /// input_ports: /// - u0 /// output_ports: /// - y0 /// @endsystem /// /// @tparam_double_only /// @ingroup control_systems template <typename T> class LinearModelPredictiveController : public LeafSystem<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LinearModelPredictiveController) // TODO(jadecastro) Implement a version that regulates to an arbitrary // trajectory. /// Constructor for an unconstrained MPC formulation with linearization /// occurring about the provided base_context. Since this formulation is /// devoid of any externally-imposed input/state constraints, the controller /// essentially behaves the same as a finite-time LQR. /// /// @param model The plant model of the System to be controlled. /// @param base_context The fixed base point about which to linearize of the /// system and regulate the system. To be valid, @p base_context must /// correspond to an equilibrium point of the system. /// @param Q A symmetric positive semi-definite state cost matrix of size /// (num_states x num_states). /// @param R A symmetric positive definite control effort cost matrix of size /// (num_inputs x num_inputs). /// @param time_period The discrete time period (in seconds) at which /// controller updates occur. /// @param time_horizon The prediction time horizon (seconds). /// /// @pre model must have discrete states of dimension num_states and inputs /// of dimension num_inputs. /// @pre base_context must have discrete states set as appropriate for the /// given @p model. The input must also be initialized via /// `input_port.FixValue(base_context, u0)`, or otherwise initialized via /// Diagram. LinearModelPredictiveController( std::unique_ptr<systems::System<double>> model, std::unique_ptr<systems::Context<double>> base_context, const Eigen::MatrixXd& Q, const Eigen::MatrixXd& R, double time_period, double time_horizon); // TODO(jadecastro) Get time_period directly from the plant model. const InputPort<T>& get_state_port() const { return this->get_input_port(state_input_index_); } const OutputPort<T>& get_control_port() const { return this->get_output_port(control_output_index_); } private: void CalcControl(const Context<T>& context, BasicVector<T>* control) const; EventStatus DoNothingButPretendItWasSomething(const Context<T>&, DiscreteValues<T>*) const; // Sets up a DirectTranscription problem and solves for the current control // input. VectorX<T> SetupAndSolveQp(const Context<T>& base_context, const VectorX<T>& current_state) const; const int state_input_index_{-1}; const int control_output_index_{-1}; const std::unique_ptr<systems::System<double>> model_; // The base context that contains the reference point to regulate. const std::unique_ptr<systems::Context<double>> base_context_; const int num_states_{}; const int num_inputs_{}; const Eigen::MatrixXd Q_; const Eigen::MatrixXd R_; const double time_period_{}; const double time_horizon_{}; // Description of the linearized plant model. std::unique_ptr<LinearSystem<double>> linear_model_; }; } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/inverse_dynamics_controller.cc
#include "drake/systems/controllers/inverse_dynamics_controller.h" #include <memory> #include <utility> #include "drake/systems/controllers/inverse_dynamics.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/primitives/adder.h" #include "drake/systems/primitives/constant_vector_source.h" #include "drake/systems/primitives/demultiplexer.h" using drake::multibody::MultibodyPlant; namespace drake { namespace systems { namespace controllers { template <typename T> void InverseDynamicsController<T>::SetUp( std::unique_ptr<multibody::MultibodyPlant<T>> owned_plant, const VectorX<double>& kp, const VectorX<double>& ki, const VectorX<double>& kd, const Context<T>* plant_context) { DRAKE_DEMAND(multibody_plant_for_control_->is_finalized()); DiagramBuilder<T> builder; InverseDynamics<T>* inverse_dynamics{}; if (owned_plant) { inverse_dynamics = builder.template AddNamedSystem<InverseDynamics<T>>( "InverseDynamics", std::move(owned_plant), InverseDynamics<T>::kInverseDynamics, plant_context); } else { inverse_dynamics = builder.template AddNamedSystem<InverseDynamics<T>>( "InverseDynamics", multibody_plant_for_control_, InverseDynamics<T>::kInverseDynamics, plant_context); } const int num_positions = multibody_plant_for_control_->num_positions(); const int num_velocities = multibody_plant_for_control_->num_velocities(); const int num_actuators = multibody_plant_for_control_->num_actuators(); const int dim = kp.size(); DRAKE_DEMAND(num_positions == dim); if (num_positions != num_actuators) { throw std::runtime_error(fmt::format(R"""( Your plant has {} positions, but only {} actuators. InverseDynamicsController (currently) only supports fully-actuated robots. For instance, you cannot use this directly if your robot/model has an unactuated floating base. Note that commonly, the MultibodyPlant used for control is not the same one used for simulation; the simulation model might contain the robot and also some objects in the world which the controller does not have direct observations of nor control over. See https://stackoverflow.com/q/75917723/9510020 for some further discussion.)""", num_positions, num_actuators)); } if (num_positions != num_velocities) { throw std::runtime_error(fmt::format(R"""( Your plant has {} positions, but {} velocities. Likely you have a quaternion floating base. InverseDynamicsController currently requires that the number of positions matches the number of velocities, and does not support joints modeled with quaternions.)""", num_positions, num_velocities)); } /* (vd*) -------------------- | (q*, v*) | ---------> | | | (q, v) |PID| | ---------> | | --+--> | | | | inverse dynamics | ---> force ------------------> | | */ // Adds a PID. pid_ = builder.template AddNamedSystem<PidController<T>>("pid", kp, ki, kd); // Adds a adder to do PID's acceleration + reference acceleration. auto adder = builder.template AddNamedSystem<Adder<T>>("+", 2, dim); // Adds PID's output with reference acceleration builder.Connect(pid_->get_output_port_control(), adder->get_input_port(0)); // Connects desired acceleration to inverse dynamics builder.Connect(adder->get_output_port(), inverse_dynamics->get_input_port_desired_acceleration()); // Exposes estimated state input port. // Connects estimated state to PID. estimated_state_ = builder.ExportInput(pid_->get_input_port_estimated_state(), "estimated_state"); // Connects estimated state to inverse dynamics. builder.ConnectInput(estimated_state_, inverse_dynamics->get_input_port_estimated_state()); // Exposes reference state input port. desired_state_ = builder.ExportInput(pid_->get_input_port_desired_state(), "desired_state"); if (!has_reference_acceleration_) { // Uses a zero constant source for reference acceleration. auto zero_feedforward_acceleration = builder.template AddNamedSystem<ConstantVectorSource<T>>( "desired_acceleration=0", VectorX<T>::Zero(dim)); builder.Connect(zero_feedforward_acceleration->get_output_port(), adder->get_input_port(1)); } else { // Exposes reference acceleration input port. desired_acceleration_ = builder.ExportInput(adder->get_input_port(1), "desired_acceleration"); } // Exposes inverse dynamics' output port. generalized_force_ = builder.ExportOutput( inverse_dynamics->get_output_port_generalized_force(), "generalized_force"); // Finalize ourself. builder.BuildInto(this); } template <typename T> void InverseDynamicsController<T>::set_integral_value( Context<T>* context, const Eigen::Ref<const VectorX<T>>& value) const { Context<T>& pid_context = Diagram<T>::GetMutableSubsystemContext(*pid_, context); pid_->set_integral_value(&pid_context, value); } template <typename T> InverseDynamicsController<T>::InverseDynamicsController( const MultibodyPlant<T>& plant, const VectorX<double>& kp, const VectorX<double>& ki, const VectorX<double>& kd, bool has_reference_acceleration, const Context<T>* plant_context) : multibody_plant_for_control_(&plant), has_reference_acceleration_(has_reference_acceleration) { SetUp(nullptr, kp, ki, kd, plant_context); } template <typename T> InverseDynamicsController<T>::InverseDynamicsController( std::unique_ptr<multibody::MultibodyPlant<T>> plant, const VectorX<double>& kp, const VectorX<double>& ki, const VectorX<double>& kd, bool has_reference_acceleration, const Context<T>* plant_context) : multibody_plant_for_control_(plant.get()), has_reference_acceleration_(has_reference_acceleration) { SetUp(std::move(plant), kp, ki, kd, plant_context); } template <typename T> InverseDynamicsController<T>::~InverseDynamicsController() = default; } // namespace controllers } // namespace systems } // namespace drake DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::controllers::InverseDynamicsController)
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/pid_controller.h
#pragma once #include <stdexcept> #include "drake/common/drake_copyable.h" #include "drake/systems/controllers/state_feedback_controller_interface.h" #include "drake/systems/framework/leaf_system.h" namespace drake { namespace systems { namespace controllers { // TODO(siyuanfeng): Lift the assumption that q and v have the same dimension. // TODO(siyuanfeng): Generalize "q_d - q", e.g. for rotation. // N.B. Inheritance order must remain fixed for pydrake (#9243). /** * Implements the PID controller. Given estimated state `x_in = (q_in, v_in)`, * the controlled state `x_c = (q_c, v_c)` is computed by `x_c = P_x * x_in`, * where `P_x` is a state projection matrix. The desired state * `x_d = (q_d, v_d)`, is in the same space as `x_c`. The output of this * controller is: * <pre> * y = P_y * (kp * (q_d - q_c) + kd * (v_d - v_c) + ki * integral(q_d - q_c)), * </pre> * where `P_y` is the output projection matrix. * * @system * name: PidController * input_ports: * - estimated_state * - desired_state * output_ports: * - control * @endsystem * * This system has one continuous state, which is the integral of position * error, two input ports: estimated state `x_in` and desired state `x_d`, and * one output port `y`. Note that this class assumes `|q_c| = |v_c|` and * `|q_d| = |v_d|`. However, `|q_c|` does not have to equal to `|q_d|`. One * typical use case for non-identity `P_x` and `P_y` is to select a subset of * state for feedback. * * @tparam_default_scalar * @ingroup control_systems */ template <typename T> class PidController : public LeafSystem<T>, public StateFeedbackControllerInterface<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(PidController) /** * Constructs a PID controller. `P_x` and `P_y` are identity * matrices of proper sizes. The estimated and desired state inputs are * 2 * @p kp's size, and the control output has @p kp's size. * @param kp P gain. * @param ki I gain. * @param kd D gain. * * @throws std::exception if @p kp, @p ki and @p kd have different * dimensions. */ PidController(const Eigen::VectorXd& kp, const Eigen::VectorXd& ki, const Eigen::VectorXd& kd); /** * Constructs a PID controller. Calls the full constructor, with the output * projection matrix `P_y` being the identity matrix. * @param state_projection The state projection matrix `P_x`. * @param kp P gain. * @param ki I gain. * @param kd D gain. * * @throws std::exception if @p kp, @p ki and @p kd have different * dimensions or `P_x.row() != 2 * |kp|'. */ PidController(const MatrixX<double>& state_projection, const Eigen::VectorXd& kp, const Eigen::VectorXd& ki, const Eigen::VectorXd& kd); /** * Constructs a PID controller. This assumes that * <pre> * 1. |kp| = |kd| = |ki| = |q_d| = |v_d| * 2. 2 * |q_d| = P_x.rows * 3. |x_in| = P_x.cols * 4. |y| = P_y.rows * 4. |q_d| = P_y.cols * </pre> * * @param state_projection The state projection matrix `P_x`. * @param output_projection The output projection matrix `P_y`. * @param kp P gain. * @param ki I gain. * @param kd V gain. * * @throws std::exception if any assumption is violated. */ PidController(const MatrixX<double>& state_projection, const MatrixX<double>& output_projection, const Eigen::VectorXd& kp, const Eigen::VectorXd& ki, const Eigen::VectorXd& kd); /** Scalar-converting copy constructor. See @ref system_scalar_conversion. */ template <typename U> explicit PidController(const PidController<U>&); /** * Returns the proportional gain constant. This method should only be called * if the proportional gain can be represented as a scalar value, i.e., every * element in the proportional gain vector is the same. It will throw a * `std::runtime_error` if the proportional gain cannot be represented as a * scalar value. */ double get_Kp_singleton() const { return get_single_gain(kp_); } /** * Returns the integral gain constant. This method should only be called if * the integral gain can be represented as a scalar value, i.e., every * element in the integral gain vector is the same. It will throw a * `std::runtime_error` if the integral gain cannot be represented as a * scalar value. */ double get_Ki_singleton() const { return get_single_gain(ki_); } /** * Returns the derivative gain constant. This method should only be called if * the derivative gain can be represented as a scalar value, i.e., every * element in the derivative gain vector is the same. It will throw a * `std::runtime_error` if the derivative gain cannot be represented as a * scalar value. */ double get_Kd_singleton() const { return get_single_gain(kd_); } /** * Returns the proportional gain vector. */ const VectorX<double>& get_Kp_vector() const { return kp_; } /** * Returns the integral gain vector. */ const VectorX<double>& get_Ki_vector() const { return ki_; } /** * Returns the derivative gain vector. */ const VectorX<double>& get_Kd_vector() const { return kd_; } /** * Sets the integral part of the PidController to @p value. * @p value must be a column vector of the appropriate size. */ void set_integral_value(Context<T>* context, const Eigen::Ref<const VectorX<T>>& value) const { VectorBase<T>& state_vector = context->get_mutable_continuous_state_vector(); state_vector.SetFromVector(value); } /** * Returns the input port for the estimated state. */ const InputPort<T>& get_input_port_estimated_state() const final { return this->get_input_port(input_index_state_); } /** * Returns the input port for the desired state. */ const InputPort<T>& get_input_port_desired_state() const final { return this->get_input_port(input_index_desired_state_); } /** * Returns the output port for computed control. */ const OutputPort<T>& get_output_port_control() const final { return this->get_output_port(output_index_control_); } protected: void DoCalcTimeDerivatives(const Context<T>& context, ContinuousState<T>* derivatives) const override; private: template <typename> friend class PidController; static double get_single_gain(const VectorX<double>& gain) { if (!gain.isConstant(gain[0])) { throw std::runtime_error("Gain is not singleton."); } return gain[0]; } void CalcControl(const Context<T>& context, BasicVector<T>* control) const; VectorX<double> kp_; VectorX<double> ki_; VectorX<double> kd_; // Size of controlled positions / output. const int num_controlled_q_{0}; // Size of input actual state. const int num_full_state_{0}; // Projection matrix from full state to controlled state, whose size is // num_controlled_q_ * 2 X num_full_state_. const MatrixX<double> state_projection_; // Output projection matrix, whose size is num_controlled_q_ by the dimension // of the output port. const MatrixX<double> output_projection_; int input_index_state_{-1}; int input_index_desired_state_{-1}; int output_index_control_{-1}; }; } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/finite_horizon_linear_quadratic_regulator.h
#pragma once #include <memory> #include <optional> #include <variant> #include "drake/common/copyable_unique_ptr.h" #include "drake/common/trajectories/piecewise_polynomial.h" #include "drake/systems/analysis/simulator_config.h" #include "drake/systems/framework/system.h" namespace drake { namespace systems { namespace controllers { /** A structure to facilitate passing the myriad of optional arguments to the FiniteHorizonLinearQuadraticRegulator algorithms. */ struct FiniteHorizonLinearQuadraticRegulatorOptions { FiniteHorizonLinearQuadraticRegulatorOptions() = default; /** A num_states x num_states positive semi-definite matrix which specified the cost at the final time. If unset, then Qf will be set to the zero matrix. */ std::optional<Eigen::MatrixXd> Qf; /** A num_states x num_inputs matrix that describes the running cost 2(x-xd(t))'N(u-ud(t)). If unset, then N will be set to the zero matrix. */ std::optional<Eigen::MatrixXd> N; /** A nominal state trajectory. The system is linearized about this trajectory. x0 must be defined over the entire interval [t0, tf]. If null, then x0 is taken to be a constant trajectory (whose value is specified by the context passed into the LQR method). */ const trajectories::Trajectory<double>* x0{nullptr}; /** A nominal input trajectory. The system is linearized about this trajectory. u0 must be defined over the entire interval, [t0, tf]. If null, then u0 is taken to be a constant trajectory (whose value is specified by the context passed into the LQR method). */ const trajectories::Trajectory<double>* u0{nullptr}; /** A desired state trajectory. The objective is to regulate to this trajectory -- the state component of the quadratic running cost is (x-xd(t))'*Q*(x-xd(t)) and the final cost is (x-xd(t))'Qf(x-xd(t)). If null, then xd(t) = x0(t). */ const trajectories::Trajectory<double>* xd{nullptr}; /** A desired input trajectory. The objective is to regulate to this trajectory -- the input component of the quadratic running cost is (u-ud(t))'*R*(u-ud(t)). If null, then ud(t) = u0(t). */ const trajectories::Trajectory<double>* ud{nullptr}; /** For systems with multiple input ports, we must specify which input port is being used in the control design. @see systems::InputPortSelection. */ std::variant<systems::InputPortSelection, InputPortIndex> input_port_index{ systems::InputPortSelection::kUseFirstInputIfItExists}; /** Enables the "square-root" method solution to the Riccati equation. This is slightly more expensive and potentially less numerically accurate (errors are bounded on the square root), but is more numerically robust. When `true`, then you must also set a (positive definite and symmetric) Qf in this options struct. */ bool use_square_root_method{false}; /** For continuous-time dynamical systems, the Riccati equation is solved by the Simulator (running backwards in time). Use this parameter to configure the simulator (e.g. choose non-default integrator or integrator parameters). */ SimulatorConfig simulator_config{}; }; /** A structure that contains the basic FiniteHorizonLinearQuadraticRegulator results. The finite-horizon cost-to-go is given by (x-x0(t))'*S(t)*(x-x0(t)) + 2*(x-x₀(t))'sₓ(t) + s₀(t) and the optimal controller is given by u-u0(t) = -K(t)*(x-x₀(t)) - k₀(t). Please don't overlook the factor of 2 in front of the sₓ(t) term. */ struct FiniteHorizonLinearQuadraticRegulatorResult { copyable_unique_ptr<trajectories::Trajectory<double>> x0; copyable_unique_ptr<trajectories::Trajectory<double>> u0; /// Note: This K is the K_x term in the derivation notes. copyable_unique_ptr<trajectories::Trajectory<double>> K; // Note: This S is the S_xx term in the derivation notes. copyable_unique_ptr<trajectories::Trajectory<double>> S; copyable_unique_ptr<trajectories::Trajectory<double>> k0; copyable_unique_ptr<trajectories::Trajectory<double>> sx; copyable_unique_ptr<trajectories::Trajectory<double>> s0; }; // TODO(russt): Add support for difference-equation systems. // TODO(russt): Add variants for specifying the cost with Q and/or R // trajectories, full quadratic forms, and perhaps even symbolic and/or // std::function cost l(t,x,u) whose's Hessian is evaluated via autodiff to give // the terms. /** Solves the differential Riccati equation to compute the optimal controller and optimal cost-to-go for the finite-horizon linear quadratic regulator: @f[\min_u (x(t_f)-x_d(t_f))'Q_f(x(t_f)-x_d(t_f)) + \int_{t_0}^{t_f} (x(t)-x_d(t))'Q(x(t)-x_d(t)) dt + \int_{t_0}^{t_f} (u(t)-u_d(t))'R(u(t)-u_d(t)) dt + \int_{t_0}^{t_f} 2(x(t)-x_d(t))'N(u(t)-u_d(t)) dt \\ \text{s.t. } \dot{x} - \dot{x}_0(t) = A(t)(x(t) - x_0(t)) + B(t)(u(t) - u_0(t)) + c(t) @f] where A(t), B(t), and c(t) are taken from the gradients of the continuous-time dynamics ẋ = f(t,x,u), as A(t) = dfdx(t, x0(t), u0(t)), B(t) = dfdu(t, x0(t), u0(t)), and c(t) = f(t, x0(t), u0(t)) - ẋ0(t). x0(t) and u0(t) can be specified in @p options, otherwise are taken to be constant trajectories with values given by @p context. @param system a System<double> representing the plant. @param context a Context<double> used to pass the default input, state, and parameters. Note: Use @p options to specify time-varying nominal state and/or input trajectories. @param t0 is the initial time. @param tf is the final time (with tf > t0). @param Q is nxn positive semi-definite. @param R is mxm positive definite. @param options is the optional FiniteHorizonLinearQuadraticRegulatorOptions. @pre @p system must be a System<double> with (only) n continuous state variables and m inputs. It must be convertible to System<AutoDiffXd>. @note Support for difference-equation systems (@see System<T>::IsDifferenceEquationSystem()) by solving the differential Riccati equation and richer specification of the objective are anticipated (they are listed in the code as TODOs). @ingroup control */ FiniteHorizonLinearQuadraticRegulatorResult FiniteHorizonLinearQuadraticRegulator( const System<double>& system, const Context<double>& context, double t0, double tf, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const Eigen::MatrixXd>& R, const FiniteHorizonLinearQuadraticRegulatorOptions& options = FiniteHorizonLinearQuadraticRegulatorOptions()); /** Variant of FiniteHorizonLinearQuadraticRegulator that returns a System implementing the regulator (controller) as a System, with a single "plant_state" input for the estimated plant state, and a single "control" output for the regulator control output. @see FiniteHorizonLinearQuadraticRegulator for details on the arguments. @ingroup control_systems */ std::unique_ptr<System<double>> MakeFiniteHorizonLinearQuadraticRegulator( const System<double>& system, const Context<double>& context, double t0, double tf, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const Eigen::MatrixXd>& R, const FiniteHorizonLinearQuadraticRegulatorOptions& options = FiniteHorizonLinearQuadraticRegulatorOptions()); } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/pid_controller.cc
#include "drake/systems/controllers/pid_controller.h" #include <string> #include "drake/common/default_scalars.h" namespace drake { namespace systems { namespace controllers { template <typename T> PidController<T>::PidController(const Eigen::VectorXd& kp, const Eigen::VectorXd& ki, const Eigen::VectorXd& kd) : PidController(MatrixX<double>::Identity(2 * kp.size(), 2 * kp.size()), kp, ki, kd) {} template <typename T> PidController<T>::PidController(const MatrixX<double>& state_projection, const Eigen::VectorXd& kp, const Eigen::VectorXd& ki, const Eigen::VectorXd& kd) : PidController(state_projection, MatrixX<double>::Identity(kp.size(), kp.size()), kp, ki, kd) {} template <typename T> PidController<T>::PidController(const MatrixX<double>& state_projection, const MatrixX<double>& output_projection, const Eigen::VectorXd& kp, const Eigen::VectorXd& ki, const Eigen::VectorXd& kd) : LeafSystem<T>(SystemTypeTag<PidController>{}), kp_(kp), ki_(ki), kd_(kd), num_controlled_q_(kp.size()), num_full_state_(state_projection.cols()), state_projection_(state_projection), output_projection_(output_projection) { if (kp_.size() != kd_.size() || kd_.size() != ki_.size()) { throw std::logic_error( "Gains must have equal length: |Kp| = " + std::to_string(kp_.size()) + ", |Ki| = " + std::to_string(ki_.size()) + ", |Kd| = " + std::to_string(kd_.size())); } if (state_projection_.rows() != 2 * num_controlled_q_) { throw std::logic_error( "State projection row dimension mismatch, expecting " + std::to_string(2 * num_controlled_q_) + ", is " + std::to_string(state_projection_.rows())); } if (output_projection_.cols() != kp_.size()) { throw std::logic_error( "Output projection column dimension mismatch, expecting " + std::to_string(kp_.size()) + ", is " + std::to_string(output_projection_.cols())); } this->DeclareContinuousState(num_controlled_q_); output_index_control_ = this->DeclareVectorOutputPort("control", output_projection_.rows(), &PidController<T>::CalcControl) .get_index(); input_index_state_ = this->DeclareVectorInputPort("estimated_state", num_full_state_) .get_index(); input_index_desired_state_ = this->DeclareInputPort("desired_state", kVectorValued, 2 * num_controlled_q_) .get_index(); } template <typename T> template <typename U> PidController<T>::PidController(const PidController<U>& other) : PidController(other.state_projection_, other.output_projection_, other.kp_, other.ki_, other.kd_) {} template <typename T> void PidController<T>::DoCalcTimeDerivatives( const Context<T>& context, ContinuousState<T>* derivatives) const { const VectorX<T>& state = get_input_port_estimated_state().Eval(context); const VectorX<T>& state_d = get_input_port_desired_state().Eval(context); // The derivative of the continuous state is the instantaneous position error. VectorBase<T>& derivatives_vector = derivatives->get_mutable_vector(); const VectorX<T> controlled_state_diff = state_d - (state_projection_.cast<T>() * state); derivatives_vector.SetFromVector( controlled_state_diff.head(num_controlled_q_)); } template <typename T> void PidController<T>::CalcControl(const Context<T>& context, BasicVector<T>* control) const { const VectorX<T>& state = get_input_port_estimated_state().Eval(context); const VectorX<T>& state_d = get_input_port_desired_state().Eval(context); // State error. const VectorX<T> controlled_state_diff = state_d - (state_projection_.cast<T>() * state); // Integral error, which is stored in the continuous state. const VectorX<T>& state_vector = dynamic_cast<const BasicVector<T>&>(context.get_continuous_state_vector()) .value(); // Sets output to the sum of all three terms. control->SetFromVector( output_projection_.cast<T>() * ((kp_.array() * controlled_state_diff.head(num_controlled_q_).array()) .matrix() + (kd_.array() * controlled_state_diff.tail(num_controlled_q_).array()) .matrix() + (ki_.array() * state_vector.array()).matrix())); } } // namespace controllers } // namespace systems } // namespace drake DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::controllers::PidController)
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/pid_controlled_system.h
#pragma once #include <memory> #include <utility> #include "drake/common/drake_copyable.h" #include "drake/systems/controllers/pid_controller.h" #include "drake/systems/framework/diagram.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/framework/system.h" #include "drake/systems/primitives/adder.h" #include "drake/systems/primitives/constant_vector_source.h" namespace drake { namespace systems { namespace controllers { /// A system that encapsulates a PidController and a controlled System (a.k.a /// the "plant"). /// /// The passed in plant must meet the following properties: /// /// * Input port `plant_input_port_index` must be all of the control inputs /// (size U). When the plant is a dynamics model, this is typically the /// generalized effort (e.g., force or torque) command. /// /// * The output port passed to the PidControlledSystem constructor must be /// of size 2 * Q, where the first Q elements are the position states of /// the plant, and the second Q elements are the velocity states of the /// plant. Q >= U. /// /// The resulting PidControlledSystem has two input ports with the following /// properties: /// /// * Input port zero is the feed forward control (size U), which will be added /// onto the output of the PID controller. The sum is sent to the plant's /// input. /// /// * Input port one is the desired *controlled* states (2 * U) of the plant, /// where the first half are the *controlled* positions, and the second half /// are the *controlled* velocities. /// /// All output ports of the plant are exposed as output ports of the /// PidControlledSystem in the same order (and therefore with the same index) /// as they appear in the plant. /// /// Some of the constructors include a parameter called `feedback_selector`. /// It is used to select the *controlled* states from the plant's state output /// port. Let `S` be the gain matrix in parameter `feedback_selector`. `S` must /// have dimensions of `(2 * U, 2 * Q)`. Typically, `S` contains one `1` in each /// row, and zeros everywhere else. `S` does not affect the desired state input. /// Let 'x' be the full state of the plant (size 2 * Q), and 'x_d' be the /// desired state (size 2 * U), `S` is used to compute the state error as /// `x_err = S * x - x_d`. /// /// @system /// name: PidControlledSystem /// input_ports: /// - desired_state /// - feedforward_control /// output_ports: /// - (exported output port of plant, with same name) /// - ... /// - (exported output port of plant, with same name) /// @endsystem /// /// @tparam_nonsymbolic_scalar /// @ingroup control_systems template <typename T> class PidControlledSystem : public Diagram<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(PidControlledSystem) /// @p plant full state is used for feedback control, and all the dimensions /// have homogeneous gains specified by @p Kp, @p Kd and @p Ki. /// /// @param[in] plant The system to be controlled. This must not be `nullptr`. /// @param[in] Kp the proportional constant. /// @param[in] Ki the integral constant. /// @param[in] Kd the derivative constant. /// @param[in] state_output_port_index identifies the output port on the /// plant that contains the (full) state information. /// @param[in] plant_input_port_index identifies the input port on the plant /// that takes in the input (computed as the output of the PID controller). /// /// @pydrake_mkdoc_identifier{6args_double_gains} PidControlledSystem(std::unique_ptr<System<T>> plant, double Kp, double Ki, double Kd, int state_output_port_index = 0, int plant_input_port_index = 0); /// @p plant full state is used for feedback control, and the vectorized gains /// are specified by @p Kp, @p Kd and @p Ki. /// /// @param[in] plant The system to be controlled. This must not be `nullptr`. /// @param[in] Kp the proportional vector constant. /// @param[in] Ki the integral vector constant. /// @param[in] Kd the derivative vector constant. /// @param[in] state_output_port_index identifies the output port on the /// plant that contains the (full) state information. /// @param[in] plant_input_port_index identifies the input port on the plant /// that takes in the input (computed as the output of the PID controller). /// /// @pydrake_mkdoc_identifier{6args_vector_gains} PidControlledSystem(std::unique_ptr<System<T>> plant, const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd, int state_output_port_index = 0, int plant_output_port_index = 0); /// A constructor where the gains are scalar values and some of the plant's /// output is part of the feedback signal as specified by /// @p feedback_selector. /// /// @param[in] plant The system to be controlled. This must not be `nullptr`. /// @param[in] feedback_selector The matrix that selects which part of the /// plant's full state is fed back to the PID controller. For semantic details /// of this parameter, see this class's description. /// @param[in] Kp the proportional constant. /// @param[in] Ki the integral constant. /// @param[in] Kd the derivative constant. /// @param[in] state_output_port_index identifies the output port on the /// plant that contains the (full) state information. /// @param[in] plant_input_port_index identifies the input port on the plant /// that takes in the input (computed as the output of the PID controller). /// /// @pydrake_mkdoc_identifier{7args_double_gains} PidControlledSystem(std::unique_ptr<System<T>> plant, const MatrixX<double>& feedback_selector, double Kp, double Ki, double Kd, int state_output_port_index = 0, int plant_input_port_index = 0); /// A constructor where the gains are vector values and some of the plant's /// output is part of the feedback signal as specified by /// @p feedback_selector. /// /// @param[in] plant The system to be controlled. This must not be `nullptr`. /// @param[in] feedback_selector The matrix that selects which part of the /// plant's full state is fed back to the PID controller. For semantic details /// of this parameter, see this class's description. /// @param[in] Kp the proportional vector constant. /// @param[in] Ki the integral vector constant. /// @param[in] Kd the derivative vector constant. /// @param[in] state_output_port_index identifies the output port on the /// plant that contains the (full) state information. /// @param[in] plant_input_port_index identifies the input port on the plant /// that takes in the input (computed as the output of the PID controller). /// /// @pydrake_mkdoc_identifier{7args_vector_gains} PidControlledSystem(std::unique_ptr<System<T>> plant, const MatrixX<double>& feedback_selector, const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd, int state_output_port_index = 0, int plant_input_port_index = 0); ~PidControlledSystem() override; System<T>* plant() { return plant_; } /// @return the input port for the feed forward control input. const InputPort<T>& get_control_input_port() const { return this->get_input_port(0); } /// @return the input port for the desired position/velocity state. const InputPort<T>& get_state_input_port() const { return this->get_input_port(1); } const OutputPort<T>& get_state_output_port() const { return this->get_output_port(state_output_port_index_); } /// The return type of ConnectController. struct ConnectResult { /// The feed forward control input. const InputPort<T>& control_input_port; /// The feedback state input. const InputPort<T>& state_input_port; }; /// Creates a PidController and uses @p builder to connect @p plant_input and /// @p plant_output from an existing plant. The controlled states are selected /// by @p feedback_selector. static ConnectResult ConnectController( const InputPort<T>& plant_input, const OutputPort<T>& plant_output, const MatrixX<double>& feedback_selector, const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd, DiagramBuilder<T>* builder); /// Creates a PidController and uses @p builder to connect @p plant_input and /// @p plant_output from an existing plant. The plant's full state is used for /// feedback. static ConnectResult ConnectController( const InputPort<T>& plant_input, const OutputPort<T>& plant_output, const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd, DiagramBuilder<T>* builder); /// Creates a PidController with input saturation and uses @p builder to /// connect @p plant_input and @p plant_output from an existing plant. The /// controlled states are selected by @p feedback_selector. The output of /// the PidController is clipped to be within the specified bounds. Note /// that using input limits along with integral gain constant may cause the /// integrator to windup. static ConnectResult ConnectControllerWithInputSaturation( const InputPort<T>& plant_input, const OutputPort<T>& plant_output, const MatrixX<double>& feedback_selector, const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd, const VectorX<T>& min_plant_input, const VectorX<T>& max_plant_input, DiagramBuilder<T>* builder); /// Creates a PidController with input saturation and uses @p builder to /// connect @p plant_input and @p plant_output from an existing plant. The /// plant's full state is used for feedback. The output of the PidController /// is clipped to be within the specified bounds. Note that using input /// limits along with integral gain constant may cause the integrator to /// windup. static ConnectResult ConnectControllerWithInputSaturation( const InputPort<T>& plant_input, const OutputPort<T>& plant_output, const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd, const VectorX<T>& min_plant_input, const VectorX<T>& max_plant_input, DiagramBuilder<T>* builder); private: // A helper function for the constructors. This is necessary to avoid seg // faults caused by simultaneously moving the plant and calling methods on // the plant when one constructor delegates to another constructor. void Initialize(std::unique_ptr<System<T>> plant, const MatrixX<double>& feedback_selector, const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd); System<T>* plant_{nullptr}; const int state_output_port_index_; const int plant_input_port_index_; }; } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/finite_horizon_linear_quadratic_regulator.cc
#include "drake/systems/controllers/finite_horizon_linear_quadratic_regulator.h" #include <algorithm> #include <limits> #include <memory> #include <utility> #include <vector> #include "drake/common/drake_assert.h" #include "drake/common/is_approx_equal_abstol.h" #include "drake/math/autodiff.h" #include "drake/math/autodiff_gradient.h" #include "drake/math/matrix_util.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/analysis/simulator_config_functions.h" #include "drake/systems/framework/leaf_system.h" #include "drake/systems/framework/scalar_conversion_traits.h" namespace drake { namespace systems { namespace controllers { using trajectories::PiecewisePolynomial; using trajectories::Trajectory; namespace { // Implements the *time-reversed* Riccati differential equation. When this // system evaluates the contained system/cost at time t, it will always replace // t=-t. class RiccatiSystem : public LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(RiccatiSystem); RiccatiSystem(const System<double>& system, const Context<double>& context, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const Eigen::MatrixXd>& R, const Trajectory<double>& x0, const Trajectory<double>& u0, const FiniteHorizonLinearQuadraticRegulatorOptions& options) : system_(System<double>::ToAutoDiffXd(system)), input_port_( system_->get_input_port_selection(options.input_port_index)), context_(system_->CreateDefaultContext()), num_states_(context_->num_total_states()), num_inputs_(input_port_->size()), Q_(Q), R_(R), Rinv_(R.inverse()), N_(options.N ? *options.N : Eigen::MatrixXd::Zero(num_states_, num_inputs_)), x0_(x0), u0_(u0), options_(options) { if (input_port_->get_data_type() == PortDataType::kAbstractValued) { throw std::logic_error( "The specified input port is abstract-valued, but " "FiniteHorizonLinearQuadraticRegulator only supports vector-valued " "input ports. Did you perhaps forget to pass a non-default " "`options.input_port_index`?"); } DRAKE_DEMAND(input_port_->get_data_type() == PortDataType::kVectorValued); DRAKE_DEMAND(context_->has_only_continuous_state()); DRAKE_DEMAND(num_states_ > 0); DRAKE_DEMAND(num_inputs_ > 0); const double kSymmetryTolerance = 1e-8; DRAKE_DEMAND(Q.rows() == num_states_ && Q.cols() == num_states_); DRAKE_DEMAND(math::IsPositiveDefinite(Q, 0.0, kSymmetryTolerance)); DRAKE_DEMAND(R.rows() == num_inputs_ && R.cols() == num_inputs_); DRAKE_DEMAND(math::IsPositiveDefinite( R, std::numeric_limits<double>::epsilon(), kSymmetryTolerance)); DRAKE_DEMAND(x0_.rows() == num_states_ && x0_.cols() == 1); DRAKE_DEMAND(u0_.rows() == num_inputs_ && u0_.cols() == 1); // If use_square_root_method = true, then the state is P (vectorized), then // sx, then s0, where Sxx = PP'. Otherwise, the state is Sxx (vectorized), // followed by sx, then s0. this->DeclareContinuousState(num_states_ * num_states_ + num_states_ + 1); // Initialize autodiff. context_->SetTimeStateAndParametersFrom(context); system_->FixInputPortsFrom(system, context, context_.get()); } // Implement the (time-reversed) Riccati equation, as described in // http://underactuated.mit.edu/lqr.html#finite_horizon_derivation . void DoCalcTimeDerivatives( const Context<double>& context, ContinuousState<double>* derivatives) const override { // Unpack the state. const Eigen::VectorXd S_vectorized = context.get_continuous_state_vector().CopyToVector(); const Eigen::VectorBlock<const Eigen::VectorXd> sx = S_vectorized.segment(num_states_ * num_states_, num_states_); // Allocate a vectorized version of the derivatives, and map into it. Eigen::VectorXd minus_Sdot_vectorized = S_vectorized; Eigen::VectorBlock<Eigen::VectorXd> minus_sxdot = minus_Sdot_vectorized.segment(num_states_ * num_states_, num_states_); double& minus_s0dot = minus_Sdot_vectorized[S_vectorized.size() - 1]; // Get (time-varying) linearization of the plant. const double system_time = -context.get_time(); context_->SetTime(system_time); auto autodiff_args = math::InitializeAutoDiffTuple(x0_.value(system_time), u0_.value(system_time)); context_->SetContinuousState(std::get<0>(autodiff_args)); input_port_->FixValue(context_.get(), std::get<1>(autodiff_args)); const VectorX<AutoDiffXd> autodiff_xdot0 = system_->EvalTimeDerivatives(*context_).CopyToVector(); const Eigen::MatrixXd AB = math::ExtractGradient(autodiff_xdot0); const Eigen::Ref<const Eigen::MatrixXd>& A = AB.leftCols(num_states_); const Eigen::Ref<const Eigen::MatrixXd>& B = AB.rightCols(num_inputs_); const Eigen::VectorXd c = math::ExtractValue(autodiff_xdot0) - x0_.EvalDerivative(system_time, 1); // Desired trajectories relative to the nominal. const Eigen::VectorXd xd0 = options_.xd ? (options_.xd->value(system_time) - x0_.value(system_time)).eval() : Eigen::VectorXd::Zero(num_states_); const Eigen::VectorXd ud0 = options_.ud ? (options_.ud->value(system_time) - u0_.value(system_time)).eval() : Eigen::VectorXd::Zero(num_inputs_); // Compute the Riccati dynamics. Eigen::MatrixXd Sxx; if (options_.use_square_root_method) { const Eigen::Map<const Eigen::MatrixXd> P(S_vectorized.data(), num_states_, num_states_); Sxx = P * P.transpose(); const Eigen::MatrixXd PinvT = P.inverse().transpose(); Eigen::Map<Eigen::MatrixXd> minus_Pdot(minus_Sdot_vectorized.data(), num_states_, num_states_); minus_Pdot = A.transpose() * P - 0.5 * (N_ + Sxx * B) * Rinv_ * (B.transpose() * P + N_.transpose() * PinvT) + 0.5 * Q_ * PinvT; } else { Sxx = Eigen::Map<const Eigen::MatrixXd>(S_vectorized.data(), num_states_, num_states_); Eigen::Map<Eigen::MatrixXd> minus_Sxxdot( minus_Sdot_vectorized.data(), num_states_, num_states_); minus_Sxxdot = Sxx * A + A.transpose() * Sxx - (N_ + Sxx * B) * Rinv_ * (N_ + Sxx * B).transpose() + Q_; } const Eigen::VectorXd qx = -Q_ * xd0 - N_ * ud0; const Eigen::VectorXd ru_plus_BTsx = -R_ * ud0 - N_.transpose() * xd0 + B.transpose() * sx; minus_sxdot = qx - (N_ + Sxx * B) * Rinv_ * ru_plus_BTsx + A.transpose() * sx + Sxx * c; minus_s0dot = xd0.dot(Q_ * xd0) + ud0.dot(R_ * ud0) + 2 * xd0.dot(N_ * ud0) - ru_plus_BTsx.dot(Rinv_ * ru_plus_BTsx) + 2.0 * sx.dot(c); derivatives->SetFromVector(minus_Sdot_vectorized); } // TODO(russt): It would be more elegant to think of S and K as an output of // the RiccatiSystem, but we don't (yet) have a way to get the dense // integration results of an output port. // Takes a time-reversed dense solution for this Riccati system, applies the // time-reversal, and unwraps the vectorized solution into its matrix // components. void MakeSTrajectories( const PiecewisePolynomial<double>& riccati_solution, FiniteHorizonLinearQuadraticRegulatorResult* result) const { auto Sxx = std::make_unique<PiecewisePolynomial<double>>( riccati_solution.Block(0, 0, num_states_ * num_states_, 1)); Sxx->Reshape(num_states_, num_states_); if (options_.use_square_root_method) { result->S = std::make_unique<PiecewisePolynomial<double>>( *Sxx * (Sxx->Transpose())); } else { result->S = std::move(Sxx); } result->sx = std::make_unique<PiecewisePolynomial<double>>( riccati_solution.Block(num_states_ * num_states_, 0, num_states_, 1)); result->s0 = std::make_unique<PiecewisePolynomial<double>>(riccati_solution.Block( num_states_ * num_states_ + num_states_, 0, 1, 1)); } // Given a result structure already populated with the S and sx trajectories // (already time-reversed and reshaped), constructs the K and k0 trajectories. // Since derivatives are not easily available for B(t), we form a piecewise // cubic polynomial approximation of the elements of Kx and k0 using Lagrange // interpolating polynomials. Cubic seems natural, as the default "dense // output" from the integrators is a cubic hermite spline; if we had // considered K as an output from a simulation it seems natural to interpolate // K with the same order approximation. void MakeKTrajectories( FiniteHorizonLinearQuadraticRegulatorResult* result) const { const std::vector<double>& breaks = dynamic_cast<PiecewisePolynomial<double>&>(*result->S) .get_segment_times(); auto Kx = std::make_unique<PiecewisePolynomial<double>>(); auto k0 = std::make_unique<PiecewisePolynomial<double>>(); // TODO(russt): I believe there is a sampling theorem that should give me // the optimal sampling times for the fixed-degree polynomial over the // finite time interval. Find it and use it here. const std::vector<double> scaled_sample_times = {0.0, 1. / 3., 2. / 3., 1.}; const int num_samples = scaled_sample_times.size(); std::vector<double> times(num_samples); std::vector<Eigen::MatrixXd> Kx_samples(num_samples); std::vector<Eigen::MatrixXd> k0_samples(num_samples); for (size_t i = 0; i < breaks.size() - 1; ++i) { int j_start = 0; if (i > 0) { // Then my first sample is the last sample from the previous segment. times[0] = times[num_samples - 1]; Kx_samples[0] = Kx_samples[num_samples - 1]; k0_samples[0] = k0_samples[num_samples - 1]; j_start = 1; } for (int j = j_start; j < num_samples; ++j) { const double time = scaled_sample_times[j] * breaks[i + 1] + (1.0 - scaled_sample_times[j]) * breaks[i]; times[j] = time; // Compute B. context_->SetTime(time); context_->SetContinuousState(x0_.value(time).cast<AutoDiffXd>().eval()); input_port_->FixValue(context_.get(), math::InitializeAutoDiff(u0_.value(time))); const VectorX<AutoDiffXd> autodiff_xdot0 = system_->EvalTimeDerivatives(*context_).CopyToVector(); const Eigen::MatrixXd B = math::ExtractGradient(autodiff_xdot0); // Desired trajectories relative to the nominal. const Eigen::VectorXd xd0 = options_.xd ? (options_.xd->value(time) - x0_.value(time)).eval() : Eigen::VectorXd::Zero(num_states_); const Eigen::VectorXd ud0 = options_.ud ? (options_.ud->value(time) - u0_.value(time)).eval() : Eigen::VectorXd::Zero(num_inputs_); Kx_samples[j] = Rinv_ * (N_ + result->S->value(time) * B).transpose(); k0_samples[j] = -ud0 + Rinv_ * (-N_.transpose() * xd0 + B.transpose() * result->sx->value(time)); } Kx->ConcatenateInTime( PiecewisePolynomial<double>::LagrangeInterpolatingPolynomial( times, Kx_samples)); k0->ConcatenateInTime( PiecewisePolynomial<double>::LagrangeInterpolatingPolynomial( times, k0_samples)); } result->K = std::move(Kx); result->k0 = std::move(k0); } private: const std::unique_ptr<const System<AutoDiffXd>> system_; const InputPort<AutoDiffXd>* const input_port_; // Note: Use a mutable context here to avoid reallocating on every call to // e.g. CalcTimeDerivatives. WARNING: this means that evaluation of the // RiccatiSystem is not thread safe, but since the implementation is internal // to this file, there are no entry points that would allow multi-threaded // execution with the same RiccatiSystem instance. // Note: This context_ is for system_, not `this`. const std::unique_ptr<Context<AutoDiffXd>> context_; const int num_states_; const int num_inputs_; const Eigen::Ref<const Eigen::MatrixXd>& Q_; const Eigen::Ref<const Eigen::MatrixXd>& R_; const Eigen::MatrixXd Rinv_; const Eigen::MatrixXd N_; const Trajectory<double>& x0_; const Trajectory<double>& u0_; const FiniteHorizonLinearQuadraticRegulatorOptions& options_; }; } // namespace FiniteHorizonLinearQuadraticRegulatorResult FiniteHorizonLinearQuadraticRegulator( const System<double>& system, const Context<double>& context, double t0, double tf, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const Eigen::MatrixXd>& R, const FiniteHorizonLinearQuadraticRegulatorOptions& options) { // Most argument consistency checks are handled by RiccatiSystem, but that // System doesn't need to understand the time range, so we perform (only) // those checks here. system.ValidateContext(context); DRAKE_DEMAND(system.num_input_ports() > 0); DRAKE_DEMAND(tf > t0); const int num_states = context.num_total_states(); std::unique_ptr<PiecewisePolynomial<double>> x0; if (options.x0) { DRAKE_DEMAND(options.x0->start_time() <= t0); DRAKE_DEMAND(options.x0->end_time() >= tf); DRAKE_DEMAND(options.x0->has_derivative()); } else { // Make a constant trajectory with the state from context. x0 = std::make_unique<PiecewisePolynomial<double>>( context.get_continuous_state_vector().CopyToVector()); } if (options.use_square_root_method && !options.Qf) { throw std::logic_error( "options.Qf is required when options.use_square_root_method is set to " "'true'."); } std::unique_ptr<PiecewisePolynomial<double>> u0; if (options.u0) { DRAKE_DEMAND(options.u0->start_time() <= t0); DRAKE_DEMAND(options.u0->end_time() >= tf); } else { // Make a constant trajectory with the input from context. u0 = std::make_unique<PiecewisePolynomial<double>>( system.get_input_port_selection(options.input_port_index) ->Eval(context)); } RiccatiSystem riccati(system, context, Q, R, options.x0 ? *options.x0 : *x0, options.u0 ? *options.u0 : *u0, options); // Simulator doesn't support integrating backwards in time, so simulate the // time-reversed Riccati equation from -tf to -t0, and reverse it after the // fact. Simulator<double> simulator(riccati); ApplySimulatorConfig(options.simulator_config, &simulator); // Set the initial conditions (the Riccati solution at tf). if (options.Qf) { const double kSymmetryTolerance = 1e-8; DRAKE_DEMAND(options.Qf->rows() == num_states && options.Qf->cols() == num_states); Eigen::VectorXd S_vectorized = Eigen::VectorXd::Zero(num_states * num_states + num_states + 1); if (options.use_square_root_method) { // We require Qf = Qfᵀ ≻ 0. DRAKE_DEMAND(math::IsSymmetric(*options.Qf, kSymmetryTolerance)); const double kEigenvalueTolerance = 1e-8; // We use the SelfAdjointEigenSolver both to check PSD and to get the // sqrt. The eigenvalue check is adopted from math::IsPositiveDefinite. Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigensolver(*options.Qf); DRAKE_THROW_UNLESS(eigensolver.info() == Eigen::Success); const double max_abs_eigenvalue = eigensolver.eigenvalues().cwiseAbs().maxCoeff(); if (eigensolver.eigenvalues().minCoeff() < kEigenvalueTolerance * std::max(1., max_abs_eigenvalue)) { throw std::logic_error( "The SQRT method solution to the Riccati equation requires that Qf " "is strictly positive definite. To use a positive semi-definite " "Qf, set `options.use_square_root_method` to `false`."); } Eigen::Map<Eigen::MatrixXd> P(S_vectorized.data(), num_states, num_states); P = eigensolver.operatorSqrt(); } else { // Qf = Qfᵀ ≽ 0 is sufficient. DRAKE_DEMAND( math::IsPositiveDefinite(*options.Qf, 0.0, kSymmetryTolerance)); Eigen::Map<Eigen::MatrixXd> Sxx(S_vectorized.data(), num_states, num_states); Sxx = *options.Qf; } if (options.xd) { Eigen::VectorBlock<Eigen::VectorXd> sx = S_vectorized.segment(num_states * num_states, num_states); double& s0 = S_vectorized[S_vectorized.size() - 1]; const Eigen::VectorXd xd0 = options.xd->value(tf) - (options.x0 ? options.x0->value(tf) : x0->value(tf)); sx = -(*options.Qf) * xd0; s0 = xd0.dot((*options.Qf) * xd0); } simulator.get_mutable_context().SetContinuousState(S_vectorized); } simulator.get_mutable_context().SetTime(-tf); simulator.Initialize(); IntegratorBase<double>& integrator = simulator.get_mutable_integrator(); integrator.StartDenseIntegration(); simulator.AdvanceTo(-t0); FiniteHorizonLinearQuadraticRegulatorResult result; result.x0 = options.x0 ? options.x0->Clone() : std::move(x0); result.u0 = options.u0 ? options.u0->Clone() : std::move(u0); std::unique_ptr<PiecewisePolynomial<double>> riccati_solution = integrator.StopDenseIntegration(); riccati_solution->ReverseTime(); riccati.MakeSTrajectories(*riccati_solution, &result); riccati.MakeKTrajectories(&result); return result; } namespace { // Implements the (time-varying) linear controller described by a // FiniteHorizonLinearQuadraticRegulatorResult. // TODO(russt): Consider removing this class entirely and using // TrajectoryAffineSystem instead, once we support enough Trajectory algebra // (including adding and multiplying PiecewisePolynomial trajectories with // different segment times). template <typename T> class Controller final : public LeafSystem<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Controller) // Constructs the controller, and assumes ownership of the required components // of the FiniteHorizonLinearQuadraticRegulatorResult. This is appropriate, // since the class is internal to this .cc file and is only ever constructed // via a Make*Regulator() workflow which will discard the result structure. Controller(std::unique_ptr<trajectories::Trajectory<double>> x0, std::unique_ptr<trajectories::Trajectory<double>> u0, std::unique_ptr<trajectories::Trajectory<double>> K, std::unique_ptr<trajectories::Trajectory<double>> k0) : LeafSystem<T>(SystemTypeTag<Controller>()), x0_(std::move(x0)), u0_(std::move(u0)), K_(std::move(K)), k0_(std::move(k0)) { this->DeclareVectorInputPort("plant_state", K_->cols()); this->DeclareVectorOutputPort( "command", K_->rows(), &Controller::CalcOutput, {this->time_ticket(), this->input_port_ticket(InputPortIndex(0))}); } // Scalar-type converting copy constructor. See @ref system_scalar_conversion. template <typename U> explicit Controller(const Controller<U>& other) : Controller(other.x0_->Clone(), other.u0_->Clone(), other.K_->Clone(), other.k0_->Clone()) {} private: template <typename U> friend class Controller; // Calculate the (time-varying) output. void CalcOutput(const Context<T>& context, BasicVector<T>* output) const { // Note: The stored trajectories are always double, even when T != double. const double t = ExtractDoubleOrThrow(context.get_time()); const auto& x = this->get_input_port(0).Eval(context); output->get_mutable_value() = u0_->value(t) - K_->value(t) * (x - x0_->value(t)) - k0_->value(t); } std::unique_ptr<trajectories::Trajectory<double>> x0_; std::unique_ptr<trajectories::Trajectory<double>> u0_; std::unique_ptr<trajectories::Trajectory<double>> K_; std::unique_ptr<trajectories::Trajectory<double>> k0_; }; } // namespace std::unique_ptr<System<double>> MakeFiniteHorizonLinearQuadraticRegulator( const System<double>& system, const Context<double>& context, double t0, double tf, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const Eigen::MatrixXd>& R, const FiniteHorizonLinearQuadraticRegulatorOptions& options) { FiniteHorizonLinearQuadraticRegulatorResult result = FiniteHorizonLinearQuadraticRegulator(system, context, t0, tf, Q, R, options); return std::make_unique<Controller<double>>( std::move(result.x0), std::move(result.u0), std::move(result.K), std::move(result.k0)); } } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/inverse_dynamics.cc
#include "drake/systems/controllers/inverse_dynamics.h" #include <utility> #include <vector> using drake::multibody::MultibodyForces; using drake::multibody::MultibodyPlant; namespace drake { namespace systems { namespace controllers { template <typename T> InverseDynamics<T>::InverseDynamics( std::unique_ptr<multibody::MultibodyPlant<T>> owned_plant, const MultibodyPlant<T>* plant, const InverseDynamicsMode mode, const Context<T>* plant_context) : LeafSystem<T>(SystemTypeTag<InverseDynamics>{}), owned_plant_(std::move(owned_plant)), plant_(owned_plant_ ? owned_plant_.get() : plant), mode_(mode), q_dim_(plant_->num_positions()), v_dim_(plant_->num_velocities()) { // Check that only one of owned_plant and plant where set. DRAKE_DEMAND(owned_plant_ == nullptr || plant == nullptr); DRAKE_DEMAND(plant_ != nullptr); DRAKE_THROW_UNLESS(plant_->is_finalized()); if (plant_context != nullptr) { plant_->ValidateContext(*plant_context); } estimated_state_ = this->DeclareInputPort("estimated_state", kVectorValued, q_dim_ + v_dim_) .get_index(); // We declare the all_input_ports ticket so that GetDirectFeedthrough does // not try to cast to Symbolic for feedthrough evaluation. generalized_force_ = this->DeclareVectorOutputPort("generalized_force", v_dim_, &InverseDynamics<T>::CalcOutputForce, {this->all_input_ports_ticket()}) .get_index(); std::unique_ptr<Context<T>> model_plant_context = plant_context == nullptr ? plant_->CreateDefaultContext() : plant_context->Clone(); // Gravity compensation mode requires velocities to be zero. if (this->is_pure_gravity_compensation()) { plant_->SetVelocities(model_plant_context.get(), VectorX<T>::Zero(plant_->num_velocities())); } // Declare cache entry for the multibody plant context. plant_context_cache_index_ = this->DeclareCacheEntry("plant_context_cache", *model_plant_context, &InverseDynamics<T>::SetMultibodyContext, {this->input_port_ticket(estimated_state_)}) .cache_index(); // Declare external forces cache entry and desired acceleration input port if // this is doing inverse dynamics. if (!this->is_pure_gravity_compensation()) { external_forces_cache_index_ = this->DeclareCacheEntry( "external_forces_cache", MultibodyForces<T>(*plant_), &InverseDynamics<T>::CalcMultibodyForces, {this->cache_entry_ticket(plant_context_cache_index_)}) .cache_index(); desired_acceleration_ = this->DeclareInputPort("desired_acceleration", kVectorValued, v_dim_) .get_index(); } } template <typename T> InverseDynamics<T>::InverseDynamics(const MultibodyPlant<T>* plant, const InverseDynamicsMode mode, const Context<T>* plant_context) : InverseDynamics(nullptr, plant, mode, plant_context) {} template <typename T> InverseDynamics<T>::InverseDynamics( std::unique_ptr<multibody::MultibodyPlant<T>> plant, const InverseDynamicsMode mode, const Context<T>* plant_context) : InverseDynamics(std::move(plant), nullptr, mode, plant_context) {} template <typename T> template <typename U> typename InverseDynamics<T>::ScalarConversionData InverseDynamics<T>::ScalarConvertHelper(const InverseDynamics<U>& other) { // Convert plant. auto this_plant = systems::System<U>::template ToScalarType<T>(*other.plant_); auto this_plant_context = this_plant->CreateDefaultContext(); // Create context and connect required port. auto other_context = other.CreateDefaultContext(); const int num_states = other.get_input_port_estimated_state().size(); other.get_input_port_estimated_state().FixValue( other_context.get(), Eigen::Matrix<U, Eigen::Dynamic, 1>::Zero(num_states)); // Convert plant context. const auto& other_plant_context = other.get_cache_entry(other.plant_context_cache_index_) .template Eval<Context<U>>(*other_context); this_plant_context->SetStateAndParametersFrom(other_plant_context); InverseDynamicsMode mode = other.is_pure_gravity_compensation() ? kGravityCompensation : kInverseDynamics; return ScalarConversionData{std::move(this_plant), mode, std::move(this_plant_context)}; } template <typename T> template <typename U> InverseDynamics<T>::InverseDynamics(const InverseDynamics<U>& other) : InverseDynamics(ScalarConvertHelper(other)) {} template <typename T> InverseDynamics<T>::InverseDynamics(ScalarConversionData&& data) : InverseDynamics(std::move(data.plant), data.mode, data.plant_context.get()) {} template <typename T> InverseDynamics<T>::~InverseDynamics() = default; template <typename T> void InverseDynamics<T>::SetMultibodyContext(const Context<T>& context, Context<T>* plant_context) const { const VectorX<T>& x = get_input_port_estimated_state().Eval(context); if (this->is_pure_gravity_compensation()) { // Velocities remain zero, as set in the constructor, for pure gravity // compensation mode. const VectorX<T> q = x.head(plant_->num_positions()); plant_->SetPositions(plant_context, q); } else { // Set the plant positions and velocities. plant_->SetPositionsAndVelocities(plant_context, x); } } template <typename T> void InverseDynamics<T>::CalcMultibodyForces( const Context<T>& context, MultibodyForces<T>* cache_value) const { const auto& plant_context = this->get_cache_entry(plant_context_cache_index_) .template Eval<Context<T>>(context); plant_->CalcForceElementsContribution(plant_context, cache_value); } template <typename T> void InverseDynamics<T>::CalcOutputForce(const Context<T>& context, BasicVector<T>* output) const { const auto& plant_context = this->get_cache_entry(plant_context_cache_index_) .template Eval<Context<T>>(context); if (this->is_pure_gravity_compensation()) { output->get_mutable_value() = -plant_->CalcGravityGeneralizedForces(plant_context); } else { const auto& external_forces = this->get_cache_entry(external_forces_cache_index_) .template Eval<MultibodyForces<T>>(context); // Compute inverse dynamics. const VectorX<T>& desired_vd = get_input_port_desired_acceleration().Eval(context); output->get_mutable_value() = plant_->CalcInverseDynamics(plant_context, desired_vd, external_forces); } } } // namespace controllers } // namespace systems } // namespace drake DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::controllers::InverseDynamics)
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/dynamic_programming.h
#pragma once #include <list> #include <memory> #include <set> #include <utility> #include <variant> #include "drake/common/symbolic/expression.h" #include "drake/math/barycentric.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/vector_system.h" #include "drake/systems/primitives/barycentric_system.h" namespace drake { namespace systems { namespace controllers { /// Consolidates the many possible options to be passed to the dynamic /// programming algorithms. struct DynamicProgrammingOptions { DynamicProgrammingOptions() = default; /// A value between (0,1] that discounts future rewards. /// @see FittedValueIteration. double discount_factor{1.}; /// For algorithms that rely on approximations of the state-dynamics /// (as in FittedValueIteration), this is a list of state dimensions for /// which the state space maximum value should be "wrapped around" to /// ensure that all values are in the range [low, high). The classic example /// is for angles that are wrapped around at 2π. struct PeriodicBoundaryCondition { PeriodicBoundaryCondition(int state_index, double low, double high); int state_index{-1}; double low{0.}; double high{2.*M_PI}; }; std::list<struct PeriodicBoundaryCondition> periodic_boundary_conditions; /// Value iteration methods converge when the value function stops /// changing (typically evaluated with the l∞ norm). This value sets that /// threshold. double convergence_tol = 1e-4; /// If callable, this method is invoked during each major iteration of the /// dynamic programming algorithm, in order to facilitate e.g. graphical /// inspection/debugging of the results. /// /// @note The first call happens at iteration 1 (after the value iteration /// has run once), not zero. std::function<void( int iteration, const math::BarycentricMesh<double>& state_mesh, const Eigen::RowVectorXd& cost_to_go, const Eigen::MatrixXd& policy)> visualization_callback{nullptr}; /// For systems with multiple input ports, we must specify which input port is /// being used in the control design. @see systems::InputPortSelection. std::variant<systems::InputPortSelection, InputPortIndex> input_port_index{ systems::InputPortSelection::kUseFirstInputIfItExists}; /// (Advanced) Boolean which, if true, allows this algorithm to optimize /// without considering the dynamics of any non-continuous states. This is /// helpful for optimizing systems that might have some additional /// book-keeping variables in their state. Only use this if you are sure that /// the dynamics of the additional state variables cannot impact the dynamics /// of the continuous states. @default false. bool assume_non_continuous_states_are_fixed{false}; }; /// Implements Fitted Value Iteration on a (triangulated) Barycentric Mesh, /// which designs a state-feedback policy to minimize the infinite-horizon cost /// ∑ γⁿ g(x[n],u[n]), where γ is the discount factor in @p options. /// /// For background, and a description of this algorithm, see /// http://underactuated.csail.mit.edu/underactuated.html?chapter=dp . /// It currently requires that the system to be optimized has only continuous /// state and it is assumed to be time invariant. This code makes a /// discrete-time approximation (using @p time_step) for the value iteration /// update. /// /// @param simulator contains the reference to the System being optimized and to /// a Context for that system, which may contain non-default Parameters, etc. /// The @p simulator is run for @p time_step seconds from every point on the /// mesh in order to approximate the dynamics; all of the simulation parameters /// (integrator, etc) are relevant during that evaluation. /// /// @param cost_function is the continuous-time instantaneous cost. This /// implementation of the discrete-time formulation above uses the approximation /// g(x,u) = time_step*cost_function(x,u). /// @param state_grid defines the mesh on the state space used to represent /// the cost-to-go function and the resulting policy. /// @param input_grid defines the discrete action space used in the value /// iteration update. /// @param time_step a time in seconds used for the discrete-time approximation. /// @param options optional DynamicProgrammingOptions structure. /// /// @return a std::pair containing the resulting policy, implemented as a /// BarycentricMeshSystem, and the RowVectorXd J that defines the expected /// cost-to-go on a BarycentricMesh using @p state_grid. The policy has a /// single vector input (which is the continuous state of the system passed /// in through @p simulator) and a single vector output (which is the input /// of the system passed in through @p simulator). /// /// @ingroup control std::pair<std::unique_ptr<BarycentricMeshSystem<double>>, Eigen::RowVectorXd> FittedValueIteration( Simulator<double>* simulator, const std::function<double(const Context<double>& context)>& cost_function, const math::BarycentricMesh<double>::MeshGrid& state_grid, const math::BarycentricMesh<double>::MeshGrid& input_grid, double time_step, const DynamicProgrammingOptions& options = DynamicProgrammingOptions()); // TODO(russt): Handle the specific case where system is control affine and the // cost function is quadratic positive-definite. (Adds requirements on the // system and cost function (e.g. autodiff/symbolic), and doesn't need the // input_grid argument). // TODO(russt): Implement more general FittedValueIteration methods as the // function approximation tools become available. /// Implements the Linear Programming approach to approximate dynamic /// programming. It optimizes the linear program /// /// maximize ∑ Jₚ(x). /// subject to ∀x, ∀u, Jₚ(x) ≤ g(x,u) + γJₚ(f(x,u)), /// /// where g(x,u) is the one-step cost, Jₚ(x) is a (linearly) parameterized /// cost-to-go function with parameter vector p, and γ is the discount factor in /// @p options. /// /// For background, and a description of this algorithm, see /// http://underactuated.csail.mit.edu/underactuated.html?chapter=dp . /// It currently requires that the system to be optimized has only continuous /// state and it is assumed to be time invariant. This code makes a /// discrete-time approximation (using @p time_step) for the value iteration /// update. /// /// @param simulator contains the reference to the System being optimized and to /// a Context for that system, which may contain non-default Parameters, etc. /// The @p simulator is run for @p time_step seconds from every pair of /// input/state sample points in order to approximate the dynamics; all of /// the simulation parameters (integrator, etc) are relevant during that /// evaluation. /// /// @param cost_function is the continuous-time instantaneous cost. This /// implementation of the discrete-time formulation above uses the approximation /// g(x,u) = time_step*cost_function(x,u). /// /// @param linearly_parameterized_cost_to_go_function must define a function /// to approximate the cost-to-go, which takes the state vector as the first /// input and the parameter vector as the second input. This can be any /// function of the form /// Jₚ(x) = ∑ pᵢ φᵢ(x). /// This algorithm will pass in a VectorX of symbolic::Variable in order to /// set up the linear program. /// /// @param state_samples is a list of sample states (one per column) at which /// to apply the optimization constraints and the objective. /// /// @param input_samples is a list of inputs (one per column) which are /// evaluated *at every sample point*. /// @param time_step a time in seconds used for the discrete-time approximation. /// @param options optional DynamicProgrammingOptions structure. /// /// @return params the VectorXd of parameters that optimizes the /// supplied cost-to-go function. /// /// @ingroup control_systems Eigen::VectorXd LinearProgrammingApproximateDynamicProgramming( Simulator<double>* simulator, const std::function<double(const Context<double>& context)>& cost_function, const std::function<symbolic::Expression( const Eigen::Ref<const Eigen::VectorXd>& state, const VectorX<symbolic::Variable>& parameters)>& linearly_parameterized_cost_to_go_function, int num_parameters, const Eigen::Ref<const Eigen::MatrixXd>& state_samples, const Eigen::Ref<const Eigen::MatrixXd>& input_samples, double time_step, const DynamicProgrammingOptions& options = DynamicProgrammingOptions()); // TODO(russt): could easily provide a version of LPADP that accepts the same // inputs as the barycentric fitted value iteration, by creating samples at // all of the mesh points, and returns a RowVectorXd for the cost function // values. I could lambda the cost_to_go_function. } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/dynamic_programming.cc
#include "drake/systems/controllers/dynamic_programming.h" #include <limits> #include <utility> #include <vector> #include "drake/common/text_logging.h" #include "drake/math/wrap_to.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/solve.h" #include "drake/systems/analysis/simulator.h" namespace drake { namespace systems { namespace controllers { DynamicProgrammingOptions::PeriodicBoundaryCondition::PeriodicBoundaryCondition( int state_index_in, double low_in, double high_in) : state_index(state_index_in), low(low_in), high(high_in) { DRAKE_DEMAND(low_in < high_in); } std::pair<std::unique_ptr<BarycentricMeshSystem<double>>, Eigen::RowVectorXd> FittedValueIteration( Simulator<double>* simulator, const std::function<double(const Context<double>& context)>& cost_function, const math::BarycentricMesh<double>::MeshGrid& state_grid, const math::BarycentricMesh<double>::MeshGrid& input_grid, double time_step, const DynamicProgrammingOptions& options) { DRAKE_DEMAND(options.discount_factor > 0. && options.discount_factor <= 1.); const int state_size = state_grid.size(); const int input_size = input_grid.size(); DRAKE_DEMAND(state_size > 0); DRAKE_DEMAND(input_size > 0); const auto& system = simulator->get_system(); auto& context = simulator->get_mutable_context(); math::BarycentricMesh<double> state_mesh(state_grid); math::BarycentricMesh<double> input_mesh(input_grid); const int num_states = state_mesh.get_num_mesh_points(); const int num_inputs = input_mesh.get_num_mesh_points(); const int num_state_indices = state_mesh.get_num_interpolants(); // TODO(russt): handle discrete state. DRAKE_DEMAND(context.has_only_continuous_state() || options.assume_non_continuous_states_are_fixed); DRAKE_DEMAND(context.num_continuous_states() == state_size); const InputPort<double>* input_port = system.get_input_port_selection(options.input_port_index); DRAKE_DEMAND(input_port != nullptr); DRAKE_DEMAND(input_port->size() == input_size); // Verify that the input port is not abstract valued. if (input_port->get_data_type() == PortDataType::kAbstractValued) { throw std::logic_error( "The specified input port is abstract-valued, but FittedValueIteration " "only supports vector-valued input ports. Did you perhaps forget to " "pass a non-default `options.input_port_index`?"); } DRAKE_DEMAND(time_step > 0.); // TODO(russt): check that the system is time-invariant. // Make sure all periodic boundary conditions are in range. for (const auto& b : options.periodic_boundary_conditions) { DRAKE_DEMAND(b.state_index >= 0 && b.state_index < state_size); DRAKE_DEMAND(b.low < b.high); DRAKE_DEMAND(b.low >= *(state_grid[b.state_index].begin())); DRAKE_DEMAND(b.high <= *(state_grid[b.state_index].rbegin())); } // The transition probabilities are represented as a sparse matrix, // where Tind[input](:,state) is a list of non-zero indexes into the // state_mesh, and T[input](:,state) is the associated list of coefficients. // cost[input](j) is the cost of taking action input from state mesh index j. std::vector<Eigen::MatrixXi> Tind(num_inputs); std::vector<Eigen::MatrixXd> T(num_inputs); std::vector<Eigen::RowVectorXd> cost(num_inputs); drake::log()->info("Computing transition and cost matrices."); auto& sim_state = context.get_mutable_continuous_state_vector(); Eigen::VectorXd input_vec(input_mesh.get_input_size()); Eigen::VectorXd state_vec(state_mesh.get_input_size()); Eigen::VectorXi Tind_tmp(num_state_indices); Eigen::VectorXd T_tmp(num_state_indices); for (int input = 0; input < num_inputs; input++) { Tind[input].resize(num_state_indices, num_states); T[input].resize(num_state_indices, num_states); cost[input].resize(num_states); input_mesh.get_mesh_point(input, &input_vec); input_port->FixValue(&context, input_vec); for (int state = 0; state < num_states; state++) { context.SetTime(0.0); sim_state.SetFromVector(state_mesh.get_mesh_point(state)); simulator->Initialize(); cost[input](state) = time_step * cost_function(context); simulator->AdvanceTo(time_step); state_vec = sim_state.CopyToVector(); for (const auto& b : options.periodic_boundary_conditions) { state_vec[b.state_index] = math::wrap_to(state_vec[b.state_index], b.low, b.high); } state_mesh.EvalBarycentricWeights(state_vec, &Tind_tmp, &T_tmp); Tind[input].col(state) = Tind_tmp; T[input].col(state) = T_tmp; } } drake::log()->info("Done computing transition and cost matrices."); // Perform value iteration loop. Eigen::RowVectorXd J = Eigen::RowVectorXd::Zero(num_states); Eigen::RowVectorXd Jnext(num_states); Eigen::MatrixXd Pi(input_mesh.get_input_size(), num_states); drake::log()->info("Running value iteration."); double max_diff = std::numeric_limits<double>::infinity(); int iteration = 0; while (max_diff > options.convergence_tol) { for (int state = 0; state < num_states; state++) { Jnext(state) = std::numeric_limits<double>::infinity(); int best_input = 0; for (int input = 0; input < num_inputs; input++) { // Q(x,u) = g(x,u) + γ J(f(x,u)). double Q = cost[input](state); for (int index = 0; index < num_state_indices; index++) { Q += options.discount_factor * T[input](index, state) * J(Tind[input](index, state)); } // Cost-to-go: J = minᵤ Q(x,u). // Policy: π(x) = argminᵤ Q(x,u). if (Q < Jnext(state)) { Jnext(state) = Q; best_input = input; } } Pi.col(state) = input_mesh.get_mesh_point(best_input); } max_diff = (J - Jnext).lpNorm<Eigen::Infinity>(); J = Jnext; iteration++; if (options.visualization_callback) { options.visualization_callback(iteration, state_mesh, J, Pi); } } drake::log()->info("Value iteration converged to requested tolerance."); // Create the policy. auto policy = std::make_unique<BarycentricMeshSystem<double>>(state_mesh, Pi); return std::make_pair(std::move(policy), J); } Eigen::VectorXd LinearProgrammingApproximateDynamicProgramming( Simulator<double>* simulator, const std::function<double(const Context<double>& context)>& cost_function, const std::function< symbolic::Expression(const Eigen::Ref<const Eigen::VectorXd>& state, const VectorX<symbolic::Variable>& parameters)>& linearly_parameterized_cost_to_go_function, int num_parameters, const Eigen::Ref<const Eigen::MatrixXd>& state_samples, const Eigen::Ref<const Eigen::MatrixXd>& input_samples, double time_step, const DynamicProgrammingOptions& options) { // discount_factor needs to be < 1 to avoid unbounded solutions (J = J* + ∞). DRAKE_DEMAND(options.discount_factor > 0. && options.discount_factor <= 1.); DRAKE_DEMAND(num_parameters > 0); const int state_size = state_samples.rows(); const int input_size = input_samples.rows(); const int num_states = state_samples.cols(); const int num_inputs = input_samples.cols(); DRAKE_DEMAND(state_size > 0); DRAKE_DEMAND(input_size > 0); const auto& system = simulator->get_system(); auto& context = simulator->get_mutable_context(); // TODO(russt): handle discrete state. DRAKE_DEMAND(context.has_only_continuous_state()); DRAKE_DEMAND(context.num_continuous_states() == state_size); DRAKE_DEMAND(context.num_input_ports() == 1); DRAKE_DEMAND(system.num_total_inputs() == input_size); DRAKE_DEMAND(time_step > 0.); // TODO(russt): check that the system is time-invariant. // TODO(russt): implement wrapping (API doesn't provide enough info yet). // Make sure all periodic boundary conditions are in range. for (const auto& b : options.periodic_boundary_conditions) { DRAKE_DEMAND(b.state_index >= 0 && b.state_index < state_size); DRAKE_DEMAND(b.low < b.high); } drake::log()->info( "Computing one-step dynamics and setting up the linear program."); solvers::MathematicalProgram prog; const solvers::VectorXDecisionVariable params = prog.NewContinuousVariables(num_parameters, "a"); // Alias the function name for readability below. const auto& J = linearly_parameterized_cost_to_go_function; // Maximize ∑ J. for (int state = 0; state < num_states; state++) { prog.AddLinearCost(-J(state_samples.col(state), params)); } // ∀x, ∀u, J(x) ≤ cost(x,u) + γJ(f(x,u)). auto& sim_state = context.get_mutable_continuous_state_vector(); Eigen::VectorXd state_vec(state_size); Eigen::VectorXd next_state_vec(state_size); for (int input = 0; input < num_inputs; input++) { system.get_input_port(0).FixValue(&context, input_samples.col(input)); for (int state = 0; state < num_states; state++) { context.SetTime(0.0); state_vec = state_samples.col(state); sim_state.SetFromVector(state_vec); simulator->Initialize(); const double cost = time_step * cost_function(context); simulator->AdvanceTo(time_step); next_state_vec = sim_state.CopyToVector(); for (const auto& b : options.periodic_boundary_conditions) { next_state_vec[b.state_index] = math::wrap_to(next_state_vec[b.state_index], b.low, b.high); } const symbolic::Formula f = (J(state_vec, params) <= cost + options.discount_factor * J(next_state_vec, params)); // Filter out constraints that are trivially true (because // AddConstraint throws). if (!symbolic::is_true(f)) { prog.AddLinearConstraint(f); } } } drake::log()->info("Solving linear program."); const solvers::MathematicalProgramResult result = Solve(prog); if (!result.is_success()) { drake::log()->error("No solution found. SolutionResult = " + to_string(result.get_solution_result())); } drake::log()->info("Done solving linear program."); return result.GetSolution(params); } } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/inverse_dynamics_controller.h
#pragma once #include <memory> #include <stdexcept> #include <string> #include "drake/common/default_scalars.h" #include "drake/common/drake_copyable.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/controllers/inverse_dynamics.h" #include "drake/systems/controllers/pid_controller.h" #include "drake/systems/controllers/state_feedback_controller_interface.h" #include "drake/systems/framework/diagram.h" namespace drake { namespace systems { namespace controllers { // N.B. Inheritance order must remain fixed for pydrake (#9243). /** * A state feedback controller that uses a PidController to generate desired * accelerations, which are then converted into torques using InverseDynamics. * More specifically, the output of this controller is: * <pre> * force = inverse_dynamics(q, v, vd_command), where * vd_command = kp(q_d - q) + kd(v_d - v) + ki int(q_d - q) + vd_d. * </pre> * Here `q` and `v` stand for the generalized position and velocity, and `vd` * is the generalized acceleration. The subscript `_d` indicates desired * values, and `vd_command` indicates the acceleration command (which includes * the stabilization terms) passed to the inverse dynamics computation. * * @system * name: InverseDynamicsController * input_ports: * - estimated_state * - desired_state * - <span style="color:gray">desired_acceleration</span> * output_ports: * - generalized_force * @endsystem * * @note As an alternative to adding a separate controller system to your * diagram, you can model gravity compensation with PD controllers using * MultibodyPlant APIs. Refer to MultibodyPlant::set_gravity_enabled() as an * alternative to modeling gravity compensation. To model PD controlled * actuators, refer to @ref mbp_actuation "Actuation". * * The desired acceleration port shown in <span style="color:gray">gray</span> * may be absent, depending on the arguments passed to the constructor. * * Note that this class assumes the robot is fully actuated, its position and * velocity have the same dimension, and it does not have a floating base. If * violated, the program will abort. This controller was not designed for * closed-loop systems: the controller accounts for neither constraint forces * nor actuator forces applied at loop constraints. Use on such systems is not * recommended. * * @see InverseDynamics for an accounting of all forces incorporated into the * inverse dynamics computation. * * @tparam_default_scalar * @ingroup control_systems */ template <typename T> class InverseDynamicsController final : public Diagram<T>, public StateFeedbackControllerInterface<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(InverseDynamicsController) /** * Constructs an inverse dynamics controller for the given `plant` model. * The %InverseDynamicsController holds an internal, non-owned reference to * the MultibodyPlant object so you must ensure that `plant` has a longer * lifetime than `this` %InverseDynamicsController. * @param plant The model of the plant for control. * @param kp Position gain. * @param ki Integral gain. * @param kd Velocity gain. * @param has_reference_acceleration If true, there is an extra BasicVector * input port for `vd_d`. If false, `vd_d` is treated as zero, and no extra * input port is declared. * @param plant_context The context of the `plant` that can be used to * override the plant's default parameters. Note that this will be copied at * time of construction, so there are no lifetime constraints. * @pre `plant` has been finalized (plant.is_finalized() returns `true`). * Also, `plant` and `plant_context` must be compatible. * @throws std::exception if * - The plant is not finalized (see MultibodyPlant::Finalize()). * - The plant is not compatible with the plant context. * - The number of generalized velocities is not equal to the number of * generalized positions. * - The model is not fully actuated. * - Vector kp, ki and kd do not all have the same size equal to the number * of generalized positions. */ InverseDynamicsController( const multibody::MultibodyPlant<T>& plant, const VectorX<double>& kp, const VectorX<double>& ki, const VectorX<double>& kd, bool has_reference_acceleration, const Context<T>* plant_context = nullptr); /** * Constructs an inverse dynamics controller and takes the ownership of the * input `plant`. * * @exclude_from_pydrake_mkdoc{This overload is not bound.} */ InverseDynamicsController(std::unique_ptr<multibody::MultibodyPlant<T>> plant, const VectorX<double>& kp, const VectorX<double>& ki, const VectorX<double>& kd, bool has_reference_acceleration, const Context<T>* plant_context = nullptr); // Scalar-converting copy constructor. See @ref system_scalar_conversion. template <typename U> explicit InverseDynamicsController(const InverseDynamicsController<U>& other); ~InverseDynamicsController() override; /** * Sets the integral part of the PidController to @p value. * @p value must be a column vector of the appropriate size. */ void set_integral_value(Context<T>* context, const Eigen::Ref<const VectorX<T>>& value) const; /** * Returns the input port for the reference acceleration. */ const InputPort<T>& get_input_port_desired_acceleration() const { DRAKE_THROW_UNLESS(has_reference_acceleration_); DRAKE_DEMAND(desired_acceleration_.is_valid()); return Diagram<T>::get_input_port(desired_acceleration_); } /** * Returns the input port for the estimated state. */ const InputPort<T>& get_input_port_estimated_state() const final { return this->get_input_port(estimated_state_); } /** * Returns the input port for the desired state. */ const InputPort<T>& get_input_port_desired_state() const final { return this->get_input_port(desired_state_); } /** * Returns the output port for computed control. */ const OutputPort<T>& get_output_port_control() const final { return this->get_output_port(generalized_force_); } /** * Returns a constant pointer to the MultibodyPlant used for control. */ const multibody::MultibodyPlant<T>* get_multibody_plant_for_control() const { return multibody_plant_for_control_; } private: void SetUp(std::unique_ptr<multibody::MultibodyPlant<T>> owned_plant, const VectorX<double>& kp, const VectorX<double>& ki, const VectorX<double>& kd, const Context<T>* plant_context); const multibody::MultibodyPlant<T>* multibody_plant_for_control_{nullptr}; PidController<T>* pid_{nullptr}; const bool has_reference_acceleration_{false}; InputPortIndex estimated_state_; InputPortIndex desired_state_; InputPortIndex desired_acceleration_; OutputPortIndex generalized_force_; }; } // namespace controllers } // namespace systems } // namespace drake DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::systems::controllers::InverseDynamicsController)
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/state_feedback_controller_interface.h
#pragma once #include "drake/common/drake_copyable.h" #include "drake/systems/framework/input_port.h" #include "drake/systems/framework/output_port.h" namespace drake { namespace systems { namespace controllers { /** * Interface for state feedback controllers. This class needs to be extended by * concrete implementations. It provides named accessors to actual and desired * state input ports and control output port. */ template <typename T> class StateFeedbackControllerInterface { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(StateFeedbackControllerInterface) /** * Returns the input port for the estimated state. */ virtual const InputPort<T>& get_input_port_estimated_state() const = 0; /** * Returns the input port for the desired state. */ virtual const InputPort<T>& get_input_port_desired_state() const = 0; /** * Returns the output port for computed control. */ virtual const OutputPort<T>& get_output_port_control() const = 0; protected: StateFeedbackControllerInterface() {} virtual ~StateFeedbackControllerInterface() {} }; } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/pid_controlled_system.cc
#include "drake/systems/controllers/pid_controlled_system.h" #include "drake/common/default_scalars.h" #include "drake/common/drake_assert.h" #include "drake/systems/primitives/saturation.h" namespace drake { namespace systems { namespace controllers { template <typename T> PidControlledSystem<T>::PidControlledSystem(std::unique_ptr<System<T>> plant, double Kp, double Ki, double Kd, int state_output_port_index, int plant_input_port_index) : state_output_port_index_(state_output_port_index), plant_input_port_index_{plant_input_port_index} { const int input_size = plant->get_input_port(plant_input_port_index_).size(); const Eigen::VectorXd Kp_v = Eigen::VectorXd::Ones(input_size) * Kp; const Eigen::VectorXd Ki_v = Eigen::VectorXd::Ones(input_size) * Ki; const Eigen::VectorXd Kd_v = Eigen::VectorXd::Ones(input_size) * Kd; const MatrixX<double> selector = MatrixX<double>::Identity( plant->get_input_port(plant_input_port_index_).size() * 2, plant->get_input_port(plant_input_port_index_).size() * 2); Initialize(std::move(plant), selector, Kp_v, Ki_v, Kd_v); } template <typename T> PidControlledSystem<T>::PidControlledSystem(std::unique_ptr<System<T>> plant, const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd, int state_output_port_index, int plant_input_port_index) : PidControlledSystem( std::move(plant), MatrixX<double>::Identity(2 * Kp.size(), 2 * Kp.size()), Kp, Ki, Kd, state_output_port_index, plant_input_port_index) {} template <typename T> PidControlledSystem<T>::PidControlledSystem( std::unique_ptr<System<T>> plant, const MatrixX<double>& feedback_selector, double Kp, double Ki, double Kd, int state_output_port_index, int plant_input_port_index) : state_output_port_index_(state_output_port_index), plant_input_port_index_{plant_input_port_index} { const int input_size = plant->get_input_port(plant_input_port_index_).size(); const Eigen::VectorXd Kp_v = Eigen::VectorXd::Ones(input_size) * Kp; const Eigen::VectorXd Ki_v = Eigen::VectorXd::Ones(input_size) * Ki; const Eigen::VectorXd Kd_v = Eigen::VectorXd::Ones(input_size) * Kd; Initialize(std::move(plant), feedback_selector, Kp_v, Ki_v, Kd_v); } template <typename T> PidControlledSystem<T>::PidControlledSystem( std::unique_ptr<System<T>> plant, const MatrixX<double>& feedback_selector, const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd, int state_output_port_index, int plant_input_port_index) : state_output_port_index_(state_output_port_index), plant_input_port_index_{plant_input_port_index} { Initialize(std::move(plant), feedback_selector, Kp, Ki, Kd); } template <typename T> void PidControlledSystem<T>::Initialize( std::unique_ptr<System<T>> plant, const MatrixX<double>& feedback_selector, const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd) { DRAKE_DEMAND(plant != nullptr); DiagramBuilder<T> builder; plant_ = builder.template AddSystem(std::move(plant)); DRAKE_ASSERT(plant_->num_input_ports() >= 1); DRAKE_ASSERT(plant_->num_output_ports() >= 1); // state_output_port_index_ will be checked by the get_output_port call below. auto input_ports = ConnectController(plant_->get_input_port(plant_input_port_index_), plant_->get_output_port(state_output_port_index_), feedback_selector, Kp, Ki, Kd, &builder); builder.ExportInput(input_ports.control_input_port, "feedforward_control"); builder.ExportInput(input_ports.state_input_port, "desired_state"); for (int i=0; i < plant_->num_output_ports(); i++) { const auto& port = plant_->get_output_port(i); builder.ExportOutput(port, port.get_name()); } builder.BuildInto(this); } template <typename T> typename PidControlledSystem<T>::ConnectResult PidControlledSystem<T>::ConnectController( const InputPort<T>& plant_input, const OutputPort<T>& plant_output, const MatrixX<double>& feedback_selector, const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd, DiagramBuilder<T>* builder) { auto controller = builder->template AddSystem<PidController<T>>( feedback_selector, Kp, Ki, Kd); auto plant_input_adder = builder->template AddSystem<Adder<T>>(2, plant_input.size()); builder->Connect(plant_output, controller->get_input_port_estimated_state()); builder->Connect(controller->get_output_port_control(), plant_input_adder->get_input_port(0)); builder->Connect(plant_input_adder->get_output_port(), plant_input); return ConnectResult{ plant_input_adder->get_input_port(1), controller->get_input_port_desired_state()}; } template <typename T> typename PidControlledSystem<T>::ConnectResult PidControlledSystem<T>::ConnectController( const InputPort<T>& plant_input, const OutputPort<T>& plant_output, const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd, DiagramBuilder<T>* builder) { return ConnectController(plant_input, plant_output, MatrixX<double>::Identity(plant_output.size(), plant_output.size()), Kp, Ki, Kd, builder); } template <typename T> typename PidControlledSystem<T>::ConnectResult PidControlledSystem<T>::ConnectControllerWithInputSaturation( const InputPort<T>& plant_input, const OutputPort<T>& plant_output, const MatrixX<double>& feedback_selector, const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd, const VectorX<T>& min_plant_input, const VectorX<T>& max_plant_input, DiagramBuilder<T>* builder) { auto saturation = builder->template AddSystem<Saturation<T>>( min_plant_input, max_plant_input); builder->Connect(saturation->get_output_port(), plant_input); return PidControlledSystem<T>::ConnectController(saturation->get_input_port(), plant_output, feedback_selector, Kp, Ki, Kd, builder); } template <typename T> typename PidControlledSystem<T>::ConnectResult PidControlledSystem<T>::ConnectControllerWithInputSaturation( const InputPort<T>& plant_input, const OutputPort<T>& plant_output, const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd, const VectorX<T>& min_plant_input, const VectorX<T>& max_plant_input, DiagramBuilder<T>* builder) { return ConnectControllerWithInputSaturation(plant_input, plant_output, MatrixX<double>::Identity(plant_output.size(), plant_output.size()), Kp, Ki, Kd, min_plant_input, max_plant_input, builder); } template <typename T> PidControlledSystem<T>::~PidControlledSystem() {} } // namespace controllers } // namespace systems } // namespace drake DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_NONSYMBOLIC_SCALARS( class ::drake::systems::controllers::PidControlledSystem)
0
/home/johnshepherd/drake/systems
/home/johnshepherd/drake/systems/controllers/linear_model_predictive_controller.cc
#include "drake/systems/controllers/linear_model_predictive_controller.h" #include <memory> #include <utility> #include "drake/common/eigen_types.h" #include "drake/planning/trajectory_optimization/direct_transcription.h" #include "drake/solvers/solve.h" namespace drake { namespace systems { namespace controllers { using planning::trajectory_optimization::DirectTranscription; using solvers::VectorXDecisionVariable; template <typename T> LinearModelPredictiveController<T>::LinearModelPredictiveController( std::unique_ptr<systems::System<double>> model, std::unique_ptr<systems::Context<double>> base_context, const Eigen::MatrixXd& Q, const Eigen::MatrixXd& R, double time_period, double time_horizon) : state_input_index_( this->DeclareVectorInputPort(kUseDefaultName, Q.cols()).get_index()), control_output_index_( this->DeclareVectorOutputPort( kUseDefaultName, R.cols(), &LinearModelPredictiveController<T>::CalcControl) .get_index()), model_(std::move(model)), base_context_(std::move(base_context)), num_states_(model_->CreateDefaultContext()->get_discrete_state(0).size()), num_inputs_(model_->get_input_port().size()), Q_(Q), R_(R), time_period_(time_period), time_horizon_(time_horizon) { DRAKE_DEMAND(time_period_ > 0.); DRAKE_DEMAND(time_horizon_ > 0.); // Check that the model is SISO model_->get_input_port(); model_->get_output_port(); // Check that the model has discrete states belonging to a single group. const auto model_context = model_->CreateDefaultContext(); DRAKE_DEMAND(model_context->num_discrete_state_groups() == 1); DRAKE_DEMAND(model_context->num_continuous_states() == 0); DRAKE_DEMAND(model_context->num_abstract_states() == 0); // Check that the provided x0, u0, Q, R are consistent with the model. DRAKE_DEMAND(num_states_ > 0 && num_inputs_ > 0); DRAKE_DEMAND(Q.rows() == num_states_ && Q.cols() == num_states_); DRAKE_DEMAND(R.rows() == num_inputs_ && R.cols() == num_inputs_); // N.B. A Cholesky decomposition exists if and only if it is positive // semidefinite, however it turns out that Eigen's algorithm for checking this // is incomplete: it only succeeds on *strictly* positive definite // matrices. We exploit the fact here to check for strict // positive-definiteness of R. Eigen::LLT<Eigen::MatrixXd> R_cholesky(R); if (R_cholesky.info() != Eigen::Success) { throw std::runtime_error("R must be positive definite"); } // TODO(jwnimmer-tri) This seems like a misunderstood attempt at implementing // discrete dynamics. The intent *appears* to be that SetupAndSolveQp should // be run once every time_step. However, both because its result is NOT stored // as state and because the output is direct-feedthrough from the input, we do // not actually embody any kind of discrete dynamics. Anytime a user evaluates // the output port after the input port has changed, we'll redo the QP, even // when the current time is not an integer multiple of the step. this->DeclarePeriodicDiscreteUpdateEvent( time_period_, 0.0, &LinearModelPredictiveController<T>::DoNothingButPretendItWasSomething); if (base_context_ != nullptr) { linear_model_ = Linearize(*model_, *base_context_); } } template <typename T> void LinearModelPredictiveController<T>::CalcControl( const Context<T>& context, BasicVector<T>* control) const { const VectorX<T>& current_state = get_state_port().Eval(context); const Eigen::VectorXd current_input = SetupAndSolveQp(*base_context_, current_state); const VectorX<T> input_ref = model_->get_input_port().Eval(*base_context_); control->SetFromVector(current_input + input_ref); // TODO(jadecastro) Implement the time-varying case. } template <typename T> EventStatus LinearModelPredictiveController<T>::DoNothingButPretendItWasSomething( const Context<T>&, DiscreteValues<T>*) const { return EventStatus::Succeeded(); } template <typename T> VectorX<T> LinearModelPredictiveController<T>::SetupAndSolveQp( const Context<T>& base_context, const VectorX<T>& current_state) const { DRAKE_DEMAND(linear_model_ != nullptr); const int kNumSampleTimes = static_cast<int>(time_horizon_ / time_period_ + 0.5); DirectTranscription dirtran(linear_model_.get(), *base_context_, kNumSampleTimes); auto& prog = dirtran.prog(); const auto state_error = dirtran.state(); const auto input_error = dirtran.input(); dirtran.AddRunningCost(state_error.transpose() * Q_ * state_error + input_error.transpose() * R_ * input_error); const VectorX<T> state_ref = base_context.get_discrete_state().get_vector().CopyToVector(); prog.AddLinearConstraint(dirtran.initial_state() == current_state - state_ref); const auto result = Solve(prog); DRAKE_DEMAND(result.is_success()); return dirtran.GetInputSamples(result).col(0); } template class LinearModelPredictiveController<double>; } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/controllers
/home/johnshepherd/drake/systems/controllers/stub/zmp_planner.h
#pragma once #include "drake/common/drake_deprecated.h" #include "drake/planning/locomotion/zmp_planner.h" namespace drake { namespace systems { namespace controllers { using ZmpPlanner DRAKE_DEPRECATED("2024-08-01", "Use drake/planning/locomotion/zmp_planner.h instead.") = drake::planning::ZmpPlanner; } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/controllers
/home/johnshepherd/drake/systems/controllers/test_utilities/BUILD.bazel
load("//tools/lint:lint.bzl", "add_lint_tests") load( "//tools/skylark:drake_cc.bzl", "drake_cc_googletest", "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 = [ ":compute_torque", ], ) drake_cc_library( name = "compute_torque", testonly = 1, hdrs = ["compute_torque.h"], deps = [ "//multibody/plant", "//systems/framework", ], ) add_lint_tests(enable_clang_format_lint = False)
0
/home/johnshepherd/drake/systems/controllers
/home/johnshepherd/drake/systems/controllers/test_utilities/compute_torque.h
#pragma once #include <vector> #include "drake/common/eigen_types.h" #include "drake/multibody/plant/multibody_plant.h" namespace drake { namespace systems { namespace controllers_test { // Computes torque predicted by inverse dynamics for use with inverse dynamics // and inverse dynamics controller testing. VectorX<double> ComputeTorque( const multibody::MultibodyPlant<double>& plant, const VectorX<double>& q, const VectorX<double>& v, const VectorX<double>& vd_d, systems::Context<double>* context) { // Populate the context. plant.SetPositions(context, q); plant.SetVelocities(context, v); // Compute inverse dynamics. multibody::MultibodyForces<double> external_forces(plant); plant.CalcForceElementsContribution(*context, &external_forces); return plant.CalcInverseDynamics(*context, vd_d, external_forces); } } // namespace controllers_test } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/controllers
/home/johnshepherd/drake/systems/controllers/test/inverse_dynamics_controller_test.cc
#include "drake/systems/controllers/inverse_dynamics_controller.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/multibody/parsing/parser.h" #include "drake/systems/controllers/test_utilities/compute_torque.h" using drake::multibody::MultibodyPlant; using Eigen::VectorXd; namespace drake { namespace systems { namespace controllers { namespace { class InverseDynamicsControllerTest : public ::testing::Test { protected: void SetPidGains(VectorX<double>* kp, VectorX<double>* ki, VectorX<double>* kd) { *kp << 1, 2, 3, 4, 5, 6, 7; *ki << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7; *kd = *kp / 2.; } void ConfigTestAndCheck(InverseDynamicsController<double>* test_sys, const VectorX<double>& kp, const VectorX<double>& ki, const VectorX<double>& kd, const Context<double>* robot_context = nullptr) { EXPECT_EQ(test_sys->get_output_port().get_index(), 0); auto inverse_dynamics_context = test_sys->CreateDefaultContext(); auto output = test_sys->AllocateOutput(); const MultibodyPlant<double>& robot_plant = *test_sys->get_multibody_plant_for_control(); // Sets current state and reference state and acceleration values. const int dim = robot_plant.num_positions(); VectorX<double> q(dim), v(dim), q_r(dim), v_r(dim), vd_r(dim); q << 0.3, 0.2, 0.1, 0, -0.1, -0.2, -0.3; v = q * 3; q_r = (q + VectorX<double>::Constant(dim, 0.1)) * 2.; v_r.setZero(); vd_r << 1, 2, 3, 4, 5, 6, 7; // Connects inputs. VectorX<double> state_input(robot_plant.num_positions() + robot_plant.num_velocities()); state_input << q, v; VectorX<double> reference_state_input(robot_plant.num_positions() + robot_plant.num_velocities()); reference_state_input << q_r, v_r; VectorX<double> reference_acceleration_input(robot_plant.num_velocities()); reference_acceleration_input << vd_r; test_sys->get_input_port_estimated_state().FixValue( inverse_dynamics_context.get(), state_input); test_sys->get_input_port_desired_state().FixValue( inverse_dynamics_context.get(), reference_state_input); test_sys->get_input_port_desired_acceleration().FixValue( inverse_dynamics_context.get(), reference_acceleration_input); // Sets integrated position error. VectorX<double> q_int(dim); q_int << -1, -2, -3, -4, -5, -6, -7; test_sys->set_integral_value(inverse_dynamics_context.get(), q_int); // Computes output. test_sys->CalcOutput(*inverse_dynamics_context, output.get()); // The results should equal to this. VectorX<double> vd_d = (kp.array() * (q_r - q).array()).matrix() + (kd.array() * (v_r - v).array()).matrix() + (ki.array() * q_int.array()).matrix() + vd_r; std::unique_ptr<Context<double>> workspace_context = robot_context == nullptr ? robot_plant.CreateDefaultContext() : robot_context->Clone(); VectorX<double> expected_torque = controllers_test::ComputeTorque( robot_plant, q, v, vd_d, workspace_context.get()); // Checks the expected and computed gravity torque. const BasicVector<double>* output_vector = output->get_vector_data(0); EXPECT_TRUE(CompareMatrices(expected_torque, output_vector->get_value(), 1e-10, MatrixCompareType::absolute)); } }; // Tests the computed torque from InverseDynamicsController matches hand // derived results for the kuka iiwa arm at a given state (q, v), when // asked to track reference state (q_r, v_r) and reference acceleration (vd_r). // This test verifies the case that inverse dynamics controller only references // the input robot plant. TEST_F(InverseDynamicsControllerTest, TestTorqueWithReferencedPlant) { auto robot = std::make_unique<MultibodyPlant<double>>(0.0); multibody::Parser(robot.get()) .AddModelsFromUrl( "package://drake_models/iiwa_description/sdf/" "iiwa14_no_collision.sdf"); robot->WeldFrames(robot->world_frame(), robot->GetFrameByName("iiwa_link_0")); robot->Finalize(); // Sets pid gains. const int dim = robot->num_positions(); VectorX<double> kp(dim), ki(dim), kd(dim); SetPidGains(&kp, &ki, &kd); auto dut = std::make_unique<InverseDynamicsController<double>>( *robot, kp, ki, kd, true /* expose reference acceleration port */); ConfigTestAndCheck(dut.get(), kp, ki, kd); // Test with custom context. auto custom_context = robot->CreateDefaultContext(); const auto& iiwa_link_7 = robot->GetBodyByName("iiwa_link_7"); iiwa_link_7.SetMass(custom_context.get(), 10.0); dut = std::make_unique<InverseDynamicsController<double>>( *robot, kp, ki, kd, true, custom_context.get()); ConfigTestAndCheck(dut.get(), kp, ki, kd, custom_context.get()); } // Tests the computed torque. This test is similar to the previous test. The // difference is that the inverse dynamics controller is created by owning the // input robot plant. TEST_F(InverseDynamicsControllerTest, TestTorqueWithOwnedPlant) { auto robot = std::make_unique<MultibodyPlant<double>>(0.0); multibody::Parser(robot.get()) .AddModelsFromUrl( "package://drake_models/iiwa_description/sdf/" "iiwa14_no_collision.sdf"); robot->WeldFrames(robot->world_frame(), robot->GetFrameByName("iiwa_link_0")); robot->Finalize(); // Sets pid gains. const int dim = robot->num_positions(); VectorX<double> kp(dim), ki(dim), kd(dim); SetPidGains(&kp, &ki, &kd); auto dut = std::make_unique<InverseDynamicsController<double>>( std::move(robot), kp, ki, kd, true /* expose reference acceleration port */); ConfigTestAndCheck(dut.get(), kp, ki, kd); } // Tests the computed torque. This test is similar to the previous test. The // difference is that a custom robot context is used. TEST_F(InverseDynamicsControllerTest, TestTorqueWithOwnedPlantAndCustomContext) { auto robot = std::make_unique<MultibodyPlant<double>>(0.0); multibody::Parser(robot.get()) .AddModelsFromUrl( "package://drake_models/iiwa_description/sdf/" "iiwa14_no_collision.sdf"); robot->WeldFrames(robot->world_frame(), robot->GetFrameByName("iiwa_link_0")); robot->Finalize(); // Sets pid gains. const int dim = robot->num_positions(); VectorX<double> kp(dim), ki(dim), kd(dim); SetPidGains(&kp, &ki, &kd); // Create custom context. auto custom_context = robot->CreateDefaultContext(); const auto& iiwa_link_7 = robot->GetBodyByName("iiwa_link_7"); iiwa_link_7.SetMass(custom_context.get(), 10.0); auto dut = std::make_unique<InverseDynamicsController<double>>( std::move(robot), kp, ki, kd, true, custom_context.get()); ConfigTestAndCheck(dut.get(), kp, ki, kd, custom_context.get()); } GTEST_TEST(AdditionalInverseDynamicsTest, ScalarConversion) { auto mbp = std::make_unique<MultibodyPlant<double>>(0.0); multibody::Parser(mbp.get()).AddModelsFromUrl( "package://drake_models/iiwa_description/sdf/iiwa14_no_collision.sdf"); mbp->WeldFrames(mbp->world_frame(), mbp->GetFrameByName("iiwa_link_0")); mbp->Finalize(); const int num_states = mbp->num_multibody_states(); const int dim = mbp->num_positions(); VectorXd kp = VectorXd::Constant(dim, 0.12), ki = VectorXd::Constant(dim, 0.34), kd = VectorXd::Constant(dim, 0.56); InverseDynamicsController<double> idc(*mbp, kp, ki, kd, true); // Test AutoDiffXd. auto idc_ad = System<double>::ToAutoDiffXd<Diagram>(idc); // Note: With the current scalar conversion support, we can get a // unique_ptr<Diagram<T>> but not a unique_ptr<InverseDynamicsController<T>>. // Check the multibody plant. EXPECT_EQ(idc_ad->get_input_port(0).size(), num_states); // Check the PID gains. const auto* pid_ad = dynamic_cast<const PidController<AutoDiffXd>*>( &idc_ad->GetSubsystemByName("pid")); ASSERT_NE(pid_ad, nullptr); EXPECT_TRUE(CompareMatrices(pid_ad->get_Kp_vector(), kp)); EXPECT_TRUE(CompareMatrices(pid_ad->get_Ki_vector(), ki)); EXPECT_TRUE(CompareMatrices(pid_ad->get_Kd_vector(), kd)); // Check has_reference_acceleration. EXPECT_EQ(idc_ad->num_input_ports(), 3); // Test Expression. auto idc_sym = idc.ToSymbolic(); EXPECT_EQ(idc_sym->get_input_port(0).size(), num_states); InverseDynamicsController<double> idc_with_ownership(std::move(mbp), kp, ki, kd, true); // Test AutoDiffXd. idc_ad = System<double>::ToAutoDiffXd<Diagram>(idc_with_ownership); // Note: With the current scalar conversion support, we can get a // unique_ptr<Diagram<T>> but not a unique_ptr<InverseDynamicsController<T>>. // Check the multibody plant. EXPECT_EQ(idc_ad->get_input_port(0).size(), num_states); // Check the PID gains. pid_ad = dynamic_cast<const PidController<AutoDiffXd>*>( &idc_ad->GetSubsystemByName("pid")); ASSERT_NE(pid_ad, nullptr); EXPECT_TRUE(CompareMatrices(pid_ad->get_Kp_vector(), kp)); EXPECT_TRUE(CompareMatrices(pid_ad->get_Ki_vector(), ki)); EXPECT_TRUE(CompareMatrices(pid_ad->get_Kd_vector(), kd)); // Check has_reference_acceleration. EXPECT_EQ(idc_ad->num_input_ports(), 3); // Test Expression. idc_sym = idc_with_ownership.ToSymbolic(); EXPECT_EQ(idc_sym->get_input_port(0).size(), num_states); } } // namespace } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/controllers
/home/johnshepherd/drake/systems/controllers/test/dynamic_programming_test.cc
#include "drake/systems/controllers/dynamic_programming.h" #include <cmath> #include <gtest/gtest.h> #include "drake/common/find_resource.h" #include "drake/common/proto/call_python.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/math/barycentric.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/controllers/linear_quadratic_regulator.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/primitives/integrator.h" #include "drake/systems/primitives/linear_system.h" namespace drake { namespace systems { namespace controllers { namespace { // Minimum-time problem for the single integrator (which has a trivial solution, // that can be achieved exactly on a mesh when time_step=1). // ẋ = u, u ∈ {-1,0,1}. // g(x,u) = 0 if x == 0, 1 otherwise. // The optimal solution is: J(x) = |x|. GTEST_TEST(FittedValueIterationTest, SingleIntegrator) { const int kNumStates = 1; Integrator<double> sys(kNumStates); Simulator<double> simulator(sys); // minimum time cost function (1 for all non-zero states). const auto cost_function = [](const Context<double>& context) { double x = context.get_continuous_state()[0]; return (std::abs(x) > 0.1) ? 1. : 0.; }; const math::BarycentricMesh<double>::MeshGrid state_grid( {{-4., -3., -2., -1., 0., 1., 2., 3., 4.}}); const math::BarycentricMesh<double>::MeshGrid input_grid({{-1., 0., 1.}}); const double time_step = 1.0; std::unique_ptr<BarycentricMeshSystem<double>> policy; Eigen::RowVectorXd cost_to_go_values; std::tie(policy, cost_to_go_values) = FittedValueIteration( &simulator, cost_function, state_grid, input_grid, time_step); // Optimal cost-to-go is |x|. Eigen::RowVectorXd J_expected(static_cast<int>(state_grid[0].size())); J_expected << 4., 3., 2., 1., 0., 1., 2., 3., 4.; EXPECT_TRUE(CompareMatrices(cost_to_go_values, J_expected, 1e-8)); // Optimal policy is 1 if x < 0, 0 if x = 0, -1 if x > 0. EXPECT_EQ(policy->get_output_port().size(), 1); auto context = policy->CreateDefaultContext(); auto output = policy->get_output_port().Allocate(); for (const double x : state_grid[0]) { policy->get_input_port().FixValue(context.get(), x); policy->get_output_port().Calc(*context, output.get()); double y = output->get_value<BasicVector<double>>()[0]; EXPECT_EQ(y, (x < 0) - (x > 0)); // implements -sgn(x). } } // Single integrator minimum time problem, but with the goal at -3, and the // state wrapped on itself. GTEST_TEST(FittedValueIterationTest, PeriodicBoundary) { const int kNumStates = 1; Integrator<double> sys(kNumStates); Simulator<double> simulator(sys); // minimum time cost function (1 for all non-zero states). const auto cost_function = [](const Context<double>& context) { double x = context.get_continuous_state()[0]; return (std::abs(x + 3.) > 0.1) ? 1. : 0.; }; const math::BarycentricMesh<double>::MeshGrid state_grid( {{-4., -3., -2., -1., 0., 1., 2., 3., 4.}}); const math::BarycentricMesh<double>::MeshGrid input_grid({{-1., 0., 1.}}); const double time_step = 1.0; DynamicProgrammingOptions options; options.periodic_boundary_conditions.push_back( DynamicProgrammingOptions::PeriodicBoundaryCondition(0, -4., 4.)); std::unique_ptr<BarycentricMeshSystem<double>> policy; Eigen::RowVectorXd cost_to_go_values; std::tie(policy, cost_to_go_values) = FittedValueIteration( &simulator, cost_function, state_grid, input_grid, time_step, options); // Optimal cost-to-go is |x|. Eigen::RowVectorXd J_expected(static_cast<int>(state_grid[0].size())); J_expected << 1., 0., 1., 2., 3., 4., 3., 2., 1.; EXPECT_TRUE(CompareMatrices(cost_to_go_values, J_expected, 1e-4)); } // Plot in Python. (Costs little here and is very useful for any future // debugging). void VisualizationCallback(int iteration, const math::BarycentricMesh<double>& state_mesh, const Eigen::RowVectorXd& cost_to_go, const Eigen::MatrixXd& policy) { Eigen::VectorXd Qbins(state_mesh.get_input_grid()[0].size()); Eigen::VectorXd Qdotbins(state_mesh.get_input_grid()[1].size()); Eigen::Map<const Eigen::MatrixXd> J(cost_to_go.data(), Qbins.size(), Qdotbins.size()); int i = 0; for (const double q : state_mesh.get_input_grid()[0]) { Qbins(i++) = q; } i = 0; for (const double qdot : state_mesh.get_input_grid()[1]) { Qdotbins(i++) = qdot; } using common::CallPython; CallPython("surf", Qbins, Qdotbins, J.transpose()); CallPython("xlabel", "q"); CallPython("ylabel", "qdot"); CallPython("title", "iteration " + std::to_string(iteration)); } // Linear quadratic regulator for the double integrator. // q̈ = u, g(x,u) = x'Qx + u'Ru. // Note: we only expect the numerical solution to be very approximate, due to // discretization errors. GTEST_TEST(FittedValueIteration, DoubleIntegrator) { Eigen::Matrix2d A; A << 0., 1., 0., 0.; const Eigen::Vector2d B{0., 1.}; const Eigen::Matrix2d C = Eigen::Matrix2d::Identity(); const Eigen::Vector2d D = Eigen::Vector2d::Zero(); LinearSystem<double> sys(A, B, C, D); const Eigen::Matrix2d Q = Eigen::Matrix2d::Identity(); const double R = 1.; Simulator<double> simulator(sys); // Quadratic regulator cost function. const auto cost_function = [&sys, &Q, &R](const Context<double>& context) { const Eigen::Vector2d x = context.get_continuous_state().CopyToVector(); const double u = sys.get_input_port().Eval(context)[0]; return x.dot(Q * x) + u * R * u; }; math::BarycentricMesh<double>::MeshGrid state_grid(2); for (double x = -3.; x <= 3.; x += .2) { state_grid[0].insert(x); } for (double xdot = -4.; xdot <= 4.; xdot += .2) { state_grid[1].insert(xdot); } math::BarycentricMesh<double>::MeshGrid input_grid(1); for (double u = -6.; u <= 6.; u += .5) { input_grid[0].insert(u); } const double time_step = .01; DynamicProgrammingOptions options; options.visualization_callback = VisualizationCallback; options.discount_factor = 1.; std::unique_ptr<BarycentricMeshSystem<double>> policy; Eigen::MatrixXd cost_to_go_values; std::tie(policy, cost_to_go_values) = FittedValueIteration( &simulator, cost_function, state_grid, input_grid, time_step, options); // Note: Compare against continuous time solution, even though we are solving // a discretized version. Confirmed in MATLAB (due to #8034) that cost-to-go // is equal to the 3rd decimal, using // sys = ss(A,B,eye(2),zero(2,1)) // dsys = c2d(sys,.01) // [K,S] = dlqr(dsys.A,dsys.B,Q*dt,R*dt) auto optimal = LinearQuadraticRegulator(A, B, Q, Vector1d(R)); math::BarycentricMesh<double> state_mesh(state_grid); for (double q = -2.5; q <= 2.5; q += 1.) { for (double qdot = -3.5; qdot <= 3.5; qdot += 1.) { const Eigen::Vector2d x{q, qdot}; const double J = x.dot(optimal.S * x); // Note: Magnitudes range from 0 to ~60. // We don't expect these solutions to be too similar (the differ mostly at // the positive and negative orthants, were the boundary effects have an // impact, but also on the total magnitude of the cost through, due to the // approximation on the grid and the (more importantly) the discretization // of actions. The matlab plots above are as expected, and this guard // will make sure they remain close. EXPECT_NEAR(state_mesh.Eval(cost_to_go_values, x)[0], J, 1. + .2 * J); } } } // Ensure that FittedValueIteration can be called on a MultibodyPlant/SceneGraph // combo. GTEST_TEST(FittedValueIteration, MultibodyPlant) { DiagramBuilder<double> builder; multibody::MultibodyPlant<double>* mbp; geometry::SceneGraph<double>* scene_graph; std::tie(mbp, scene_graph) = multibody::AddMultibodyPlantSceneGraph(&builder, 0.0); multibody::Parser(mbp, scene_graph) .AddModels(FindResourceOrThrow("drake/examples/pendulum/Pendulum.urdf")); mbp->Finalize(); // Export an input that we don't need, and export it first, just to test the // input_port_index option. builder.ExportInput(mbp->get_applied_generalized_force_input_port(), "extra_input"); builder.ExportInput(mbp->get_actuation_input_port(), "pendulum_input"); auto diagram = builder.Build(); Simulator<double> simulator(*diagram); const double time_step = 0.1; math::BarycentricMesh<double>::MeshGrid state_grid(2); math::BarycentricMesh<double>::MeshGrid input_grid(1); // Note: these meshes are intentionally small for this unit test. for (int i = 0; i < 5; i++) { state_grid[0].insert(2.0 * M_PI * i / 4); state_grid[1].insert(-10.0 + 4 * i); input_grid[0].insert(-2.5 + i / 2.0); } DynamicProgrammingOptions options; options.input_port_index = diagram->get_input_port(1).get_index(); options.assume_non_continuous_states_are_fixed = true; options.periodic_boundary_conditions = { DynamicProgrammingOptions::PeriodicBoundaryCondition(0, 0, 2 * M_PI)}; // Quadratic regulator cost function. const auto cost_function = [&diagram](const Context<double>& context) { const Eigen::Matrix2d Q = Eigen::Matrix2d::Identity(); const double R = 1.; const Eigen::Vector2d x = context.get_continuous_state().CopyToVector(); const double u = diagram->get_input_port(1).Eval(context)[0]; return x.dot(Q * x) + u * R * u; }; // Just check that it runs without error. options.discount_factor = 1.; options.convergence_tol = 1e4; FittedValueIteration(&simulator, cost_function, state_grid, input_grid, time_step, options); } // Minimum-time problem for the single integrator (which has a trivial solution, // that can be achieved exactly on a mesh when time_step=1). // ẋ = u, u ∈ {-1,0,1}. // g(x,u) = 0 if x == 0, 1 otherwise. // The optimal solution is: J(x) = |x|. GTEST_TEST(LinearProgrammingTest, SingleIntegrator) { const int kNumStates = 1; Integrator<double> sys(kNumStates); Simulator<double> simulator(sys); // minimum time cost function (1 for all non-zero states). const auto cost_function = [](const Context<double>& context) { double x = context.get_continuous_state()[0]; return (std::abs(x) > 0.1) ? 1. : 0.; }; const int kNumParameters = 1; const auto cost_to_go_function = []( const Eigen::Ref<const Eigen::VectorXd>& state, const VectorX<symbolic::Variable>& parameters) { using std::abs; return parameters[0] * abs(state[0]); }; Eigen::RowVectorXd state_samples(9); state_samples << -4., -3., -2., -1., 0., 1., 2., 3., 4.; const Eigen::RowVector3d input_samples{-1., 0., 1.}; const double time_step = 1.0; DynamicProgrammingOptions options; options.discount_factor = 1.; Eigen::VectorXd J = LinearProgrammingApproximateDynamicProgramming( &simulator, cost_function, cost_to_go_function, kNumParameters, state_samples, input_samples, time_step, options); // Optimal cost-to-go is |x|. EXPECT_NEAR(J[0], 1., 1e-6); } } // namespace } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/controllers
/home/johnshepherd/drake/systems/controllers/test/deprecated_zmp_planner_test.cc
#include <gtest/gtest.h> #include "drake/systems/controllers/zmp_planner.h" namespace drake { namespace systems { namespace controllers { namespace { GTEST_TEST(DeprecatedZmpPlannerTest, Simple) { ZmpPlanner dut; EXPECT_FALSE(dut.has_planned()); } } // namespace } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/controllers
/home/johnshepherd/drake/systems/controllers/test/linear_quadratic_regulator_test.cc
#include "drake/systems/controllers/linear_quadratic_regulator.h" #include <gtest/gtest.h> #include "drake/common/find_resource.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_no_throw.h" #include "drake/examples/acrobot/acrobot_plant.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/primitives/linear_system.h" namespace drake { namespace systems { namespace controllers { namespace { GTEST_TEST(TestLqr, TestException) { // A double integrator Eigen::Matrix2d A; A << 0, 1, 0, 0; const Eigen::Vector2d B(0, 1); Eigen::Matrix2d Q = Eigen::Matrix2d::Identity(); Eigen::Matrix<double, 1, 1> R = Eigen::MatrixXd::Identity(1, 1); Eigen::Vector2d N = Eigen::Vector2d::Zero(); DRAKE_EXPECT_NO_THROW(LinearQuadraticRegulator(A, B, Q, R, N)); DRAKE_EXPECT_NO_THROW(LinearQuadraticRegulator(A, B, Q, R)); // R is not positive definite, should throw exception. EXPECT_THROW(LinearQuadraticRegulator( A, B, Q, Eigen::Matrix<double, 1, 1>::Zero()), std::runtime_error); EXPECT_THROW(LinearQuadraticRegulator( A, B, Q, Eigen::Matrix<double, 1, 1>::Zero(), N), std::runtime_error); } void TestLqrAgainstKnownSolution( double tolerance, const Eigen::Ref<const Eigen::MatrixXd>& K_known, const Eigen::Ref<const Eigen::MatrixXd>& S_known, const Eigen::Ref<const Eigen::MatrixXd>& A, const Eigen::Ref<const Eigen::MatrixXd>& B, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const Eigen::MatrixXd>& R, const Eigen::Ref<const Eigen::MatrixXd>& N = Eigen::Matrix<double, 0, 0>::Zero()) { LinearQuadraticRegulatorResult result = LinearQuadraticRegulator(A, B, Q, R, N); EXPECT_TRUE(CompareMatrices(K_known, result.K, tolerance, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(S_known, result.S, tolerance, MatrixCompareType::absolute)); } void TestLqrLinearSystemAgainstKnownSolution( double tolerance, const LinearSystem<double>& sys, const Eigen::Ref<const Eigen::MatrixXd>& K_known, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const Eigen::MatrixXd>& R, const Eigen::Ref<const Eigen::MatrixXd>& N = Eigen::Matrix<double, 0, 0>::Zero()) { std::unique_ptr<LinearSystem<double>> linear_lqr = LinearQuadraticRegulator(sys, Q, R, N); int n = sys.A().rows(); int m = sys.B().cols(); EXPECT_TRUE(CompareMatrices(linear_lqr->A(), Eigen::Matrix<double, 0, 0>::Zero(), tolerance, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(linear_lqr->B(), Eigen::MatrixXd::Zero(0, n), tolerance, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(linear_lqr->C(), Eigen::MatrixXd::Zero(m, 0), tolerance, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(linear_lqr->D(), -K_known, tolerance, MatrixCompareType::absolute)); EXPECT_EQ(linear_lqr->time_period(), sys.time_period()); } void TestLqrAffineSystemAgainstKnownSolution( double tolerance, const LinearSystem<double>& sys, const Eigen::Ref<const Eigen::MatrixXd>& K_known, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const Eigen::MatrixXd>& R, const Eigen::Ref<const Eigen::MatrixXd>& N = Eigen::Matrix<double, 0, 0>::Zero()) { int n = sys.A().rows(); int m = sys.B().cols(); auto context = sys.CreateDefaultContext(); Eigen::VectorXd x0 = Eigen::VectorXd::Zero(n); Eigen::VectorXd u0 = Eigen::VectorXd::Zero(m); sys.get_input_port().FixValue(context.get(), u0); if (sys.time_period() == 0.0) { context->SetContinuousState(x0); } else { context->SetDiscreteState(0, x0); } std::unique_ptr<AffineSystem<double>> lqr = LinearQuadraticRegulator(sys, *context, Q, R, N); EXPECT_TRUE(CompareMatrices(lqr->A(), Eigen::Matrix<double, 0, 0>::Zero(), tolerance, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(lqr->B(), Eigen::MatrixXd::Zero(0, n), tolerance, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(lqr->f0(), Eigen::Matrix<double, 0, 1>::Zero(), tolerance, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(lqr->C(), Eigen::MatrixXd::Zero(m, 0), tolerance, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(lqr->D(), -K_known, tolerance, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(lqr->y0(), u0 + K_known * x0, tolerance, MatrixCompareType::absolute)); EXPECT_EQ(lqr->time_period(), sys.time_period()); } // Test if the LQR solution satisfies the HJB equality // minᵤ xᵀQx + uᵀRu + 2xᵀNu + 2xᵀS(Ax+Bu) = 0 void TestLqrWithHjb( const Eigen::Ref<const Eigen::MatrixXd>& A, const Eigen::Ref<const Eigen::MatrixXd>& B, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const Eigen::MatrixXd>& R, const Eigen::Ref<const Eigen::MatrixXd>& N = Eigen::MatrixXd(0, 0), const Eigen::Ref<const Eigen::MatrixXd>& F = Eigen::MatrixXd(0, 0)) { const auto lqr_result = LinearQuadraticRegulator(A, B, Q, R, N, F); const int nx = A.rows(); const int nu = B.cols(); // We first try to remove the constraint F*x = 0 by considering a new slack // variable y, where y is in the null-space of F, namely y = Pᵀx. We then // define the dynamics and cost using this new variable y. // minᵤ yᵀQy*y + uᵀRy*u + 2xᵀNy*u + 2xᵀSy(Ay*x+By*u) = 0 Eigen::MatrixXd Ay = A; Eigen::MatrixXd By = B; Eigen::MatrixXd Qy = Q; Eigen::MatrixXd Ry = R; Eigen::MatrixXd Ny = N.rows() == 0 ? Eigen::MatrixXd::Zero(nx, nu) : N; Eigen::MatrixXd P = Eigen::MatrixXd::Identity(nx, nx); if (F.rows() != 0) { // First find P Eigen::ColPivHouseholderQR<Eigen::MatrixXd> qr_F(F.transpose()); ASSERT_EQ(qr_F.info(), Eigen::Success); const Eigen::MatrixXd F_Q = qr_F.matrixQ(); P = F_Q.rightCols(nx - qr_F.rank()).transpose(); Ay = P * A * P.transpose(); By = P * B; Qy = P * Q * P.transpose(); Ry = R; Ny = P * Ny; } const Eigen::MatrixXd Pt = P.transpose(); const int ny = Pt.cols(); // The minimization over u on the quadratic function occurs where the gradient // w.r.t u is 0. Ru = −(ByᵀSy + Nyᵀ)y // Since u = -Kx, we have Ru = -R*K*x = -R*K*Pᵀy // Hence R*K*Pᵀ= ByᵀSy + Nyᵀ. where Sy = P*Sx*Pᵀ const Eigen::MatrixXd Sy = P * lqr_result.S * Pt; const double tol = 1E-9; EXPECT_TRUE(CompareMatrices(Ry * lqr_result.K * Pt, By.transpose() * Sy + Ny.transpose(), tol)); // Now make sure that by plugging in u = -Kx = -KPᵀy, the left hand side of // HJB is zero. const Eigen::MatrixXd Ky = lqr_result.K * Pt; EXPECT_TRUE(CompareMatrices(Qy + Ky.transpose() * Ry * Ky - Ny * Ky - Ky.transpose() * Ny.transpose() + Sy * Ay + Ay.transpose() * Sy - Sy * By * Ky - Ky.transpose() * By.transpose() * Sy, Eigen::MatrixXd::Zero(ny, ny), tol)); } GTEST_TEST(TestLqr, DoubleIntegrator) { // Double integrator dynamics: qddot = u, where q is the position coordinate. Eigen::Matrix2d A; Eigen::Vector2d B; A << 0, 1, 0, 0; B << 0, 1; LinearSystem<double> sys(A, B, Eigen::Matrix<double, 0, 2>::Zero(), Eigen::Matrix<double, 0, 1>::Zero()); // Trivial cost: Eigen::Matrix2d Q; Eigen::Matrix<double, 1, 1> R; Q << 1, 0, 0, 1; R << 1; // Analytical solution Eigen::Matrix<double, 1, 2> K; K << 1, std::sqrt(3); Eigen::Matrix<double, 2, 2> S; S << std::sqrt(3), 1, 1, std::sqrt(3); double tol = 1e-10; TestLqrAgainstKnownSolution(tol, K, S, A, B, Q, R); // Test LinearSystem version of the LQR TestLqrLinearSystemAgainstKnownSolution(tol, sys, K, Q, R); // Call it as a generic System (by passing in a Context). // Should get the same result, but as an affine system. TestLqrAffineSystemAgainstKnownSolution(tol, sys, K, Q, R); // A different cost function with the same Q and R, and an extra N = [1; 0]. Eigen::Vector2d N(1, 0); // Known solution K = Eigen::Vector2d(1, 1); S = Eigen::Matrix2d::Identity(); TestLqrAgainstKnownSolution(tol, K, S, A, B, Q, R, N); // Test LinearSystem version of the LQR TestLqrLinearSystemAgainstKnownSolution(tol, sys, K, Q, R, N); // Test AffineSystem version of the LQR TestLqrAffineSystemAgainstKnownSolution(tol, sys, K, Q, R, N); TestLqrWithHjb(A, B, Q, R, N); } GTEST_TEST(TestLqr, ConstrainedLinearSystem) { // Test the LQR for a constrained system // ẋ = Ax+Bu // Fx = 0 Eigen::Matrix3d A; // clang-format off A << 1, 0, 2, 0, 1, 3, 0, 2, -1; // clang-format on Eigen::Matrix<double, 3, 2> B; // clang-format off B << 1, 3, 0, 2, 1, -1; // clang-format on const Eigen::RowVector3d F(1, 2, -3); Eigen::Matrix3d Q; // clang-format off Q << 4, 0, 2, 0, 9, 3, 2, 3, 8; // clang-format on Eigen::Matrix2d R; // clang-format off R << 1, 3, 3, 10; // clang-format on Eigen::Matrix<double, 3, 2> N; N << 1, 0.5, 0.5, -1, 0, 1; TestLqrWithHjb(A, B, Q, R); TestLqrWithHjb(A, B, Q, R, N); TestLqrWithHjb(A, B, Q, R, Eigen::MatrixXd(0, 0), F); TestLqrWithHjb(A, B, Q, R, N, F); } GTEST_TEST(TestLqr, DiscreteDoubleIntegrator) { Eigen::Matrix2d A; Eigen::Vector2d B; A << 1, 1, 0, 1; B << 0, 1; // Trivial cost: Eigen::Matrix2d Q = Eigen::Matrix2d::Identity(); Vector1d R = Vector1d::Identity(); // Solution from dlqr in Matlab. Eigen::RowVector2d K; K << 0.422082440385453, 1.243928853903714; Eigen::Matrix2d S; // clang-format off S << 2.947122966707012, 2.369205407092467, 2.369205407092467, 4.613134260996183; // clang-format on LinearQuadraticRegulatorResult result = DiscreteTimeLinearQuadraticRegulator(A, B, Q, R); const double tol = 1e-10; EXPECT_TRUE(CompareMatrices(result.K, K, tol)); EXPECT_TRUE(CompareMatrices(result.S, S, tol)); LinearSystem<double> sys(A, B, Eigen::Matrix<double, 0, 2>::Zero(), Eigen::Matrix<double, 0, 1>::Zero(), 0.1); // Test LinearSystem version of the LQR TestLqrLinearSystemAgainstKnownSolution(tol, sys, K, Q, R); // Test AffineSystem version of the LQR TestLqrAffineSystemAgainstKnownSolution(tol, sys, K, Q, R); } // Adds test coverage for calling LQR from a LeafSystem and from a // MultibodyPlant. GTEST_TEST(TestLqr, AcrobotTest) { const examples::acrobot::AcrobotPlant<double> plant; auto context = plant.CreateDefaultContext(); // Set nominal state to the upright fixed point. examples::acrobot::AcrobotState<double>& state = plant.get_mutable_state(context.get()); state.set_theta1(M_PI); state.set_theta2(0.0); state.set_theta1dot(0.0); state.set_theta2dot(0.0); plant.GetInputPort("elbow_torque").FixValue(context.get(), 0.0); const Eigen::Matrix4d Q = Eigen::Vector4d(10.0, 10.0, 1.0, 1.0).asDiagonal(); const Vector1d R(1); const auto controller = LinearQuadraticRegulator(plant, *context, Q, R); // Confirm that I get the same result by linearizing explicitly. const auto linear_system = Linearize(plant, *context); const auto lqr_result = LinearQuadraticRegulator( linear_system->A(), linear_system->B(), Q, R); EXPECT_TRUE(CompareMatrices(-lqr_result.K, controller->D(), 1e-12)); // Confirm that I get the same result via MultibodyPlant. multibody::MultibodyPlant<double> mbp(0.0); multibody::Parser(&mbp).AddModels( FindResourceOrThrow("drake/examples/acrobot/Acrobot.urdf")); mbp.Finalize(); auto mbp_context = mbp.CreateDefaultContext(); mbp.SetPositions(mbp_context.get(), Eigen::Vector2d(M_PI, 0)); mbp.get_actuation_input_port().FixValue(mbp_context.get(), 0.0); const auto mbp_controller = LinearQuadraticRegulator( mbp, *mbp_context, Q, R, Eigen::Matrix<double, 4, 1>::Zero(), mbp.get_actuation_input_port().get_index()); EXPECT_TRUE(CompareMatrices(mbp_controller->D(), controller->D(), 1e-9)); } } // namespace } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/controllers
/home/johnshepherd/drake/systems/controllers/test/joint_stiffness_controller_test.cc
#include "drake/systems/controllers/joint_stiffness_controller.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/multibody/parsing/parser.h" namespace drake { namespace systems { namespace controllers { namespace { using Eigen::Vector2d; using Eigen::Vector4d; using Eigen::VectorXd; using multibody::MultibodyPlant; GTEST_TEST(JointStiffnessControllerTest, SimpleDoublePendulum) { DiagramBuilder<double> builder; auto plant = builder.AddSystem<MultibodyPlant>(0.0); multibody::Parser(plant).AddModelsFromUrl( "package://drake/multibody/benchmarks/acrobot/double_pendulum.urdf"); plant->WeldFrames(plant->world_frame(), plant->GetFrameByName("base")); plant->Finalize(); Vector2d kp{0.3, 0.4}, kd{0.1, 0.2}; auto controller = builder.AddSystem<JointStiffnessController>(*plant, kp, kd); EXPECT_EQ(&controller->get_multibody_plant(), plant); builder.Connect(plant->get_state_output_port(), controller->get_input_port_estimated_state()); builder.Connect(controller->get_output_port(), plant->get_actuation_input_port()); builder.ExportInput(controller->get_input_port_desired_state(), "desired_state"); auto diagram = builder.Build(); auto context = diagram->CreateDefaultContext(); auto& plant_context = plant->GetMyMutableContextFromRoot(context.get()); auto& controller_context = controller->GetMyMutableContextFromRoot(context.get()); Vector4d x{-0.7, 0.1, 0.5, 0.4}, x_d{-0.75, 0.3, 0.02, -0.5}; plant->SetPositionsAndVelocities(&plant_context, x); diagram->get_input_port().FixValue(context.get(), x_d); // We expect the controller to cancel gravity and damping, and add the // stiffness terms. const double kDamping = 0.1; // must match double_pendulum.urdf VectorXd tau_expected = -plant->CalcGravityGeneralizedForces(plant_context) + kDamping * x.tail<2>() + (kp.array() * (x_d.head<2>() - x.head<2>()).array() + kd.array() * (x_d.tail<2>() - x.tail<2>()).array()) .matrix(); VectorXd tau = controller->get_output_port().Eval(controller_context); EXPECT_TRUE(CompareMatrices(tau, tau_expected, 1e-14)); } GTEST_TEST(JointStiffnessControllerTest, ScalarConversion) { auto mbp = std::make_unique<MultibodyPlant<double>>(0.0); multibody::Parser(mbp.get()).AddModelsFromUrl( "package://drake_models/iiwa_description/sdf/iiwa14_no_collision.sdf"); mbp->WeldFrames(mbp->world_frame(), mbp->GetFrameByName("iiwa_link_0")); mbp->Finalize(); const int num_states = mbp->num_multibody_states(); const int num_q = mbp->num_positions(); VectorXd kp = VectorXd::Constant(num_q, 0.12), kd = VectorXd::Constant(num_q, 0.34); JointStiffnessController<double> controller(*mbp, kp, kd); // Test AutoDiffXd. auto controller_ad = systems::System<double>::ToAutoDiffXd(controller); // Check the multibody plant. EXPECT_EQ(controller_ad->get_input_port_estimated_state().size(), num_states); // Test Expression. auto controller_sym = systems::System<double>::ToSymbolic(controller); EXPECT_EQ(controller_sym->get_input_port_estimated_state().size(), num_states); JointStiffnessController<double> controller_with_ownership(std::move(mbp), kp, kd); // Test AutoDiffXd. controller_ad = systems::System<double>::ToAutoDiffXd(controller_with_ownership); // Check the multibody plant. EXPECT_EQ(controller_ad->get_input_port_estimated_state().size(), num_states); // Test Expression. controller_sym = systems::System<double>::ToSymbolic(controller_with_ownership); EXPECT_EQ(controller_sym->get_input_port_estimated_state().size(), num_states); } } // namespace } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/controllers
/home/johnshepherd/drake/systems/controllers/test/inverse_dynamics_test.cc
#include "drake/systems/controllers/inverse_dynamics.h" #include <memory> #include <stdexcept> #include <string> #include <gtest/gtest.h> #include "drake/common/drake_assert.h" #include "drake/common/eigen_types.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/multibody/math/spatial_algebra.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/tree/multibody_tree.h" #include "drake/systems/controllers/test_utilities/compute_torque.h" #include "drake/systems/framework/basic_vector.h" #include "drake/systems/framework/fixed_input_port_value.h" using drake::multibody::MultibodyPlant; using Eigen::VectorXd; using std::make_unique; namespace drake { namespace systems { namespace controllers { namespace { class InverseDynamicsTest : public ::testing::Test { protected: void Init(std::unique_ptr<MultibodyPlant<double>> plant, const InverseDynamics<double>::InverseDynamicsMode mode, std::unique_ptr<Context<double>> plant_context = nullptr) { multibody_plant_ = std::move(plant); multibody_context_ = (plant_context == nullptr) ? multibody_plant_->CreateDefaultContext() : std::move(plant_context); inverse_dynamics_ = make_unique<InverseDynamics<double>>( multibody_plant_.get(), mode, multibody_context_.get()); FinishInit(mode); } void FinishInit(const InverseDynamics<double>::InverseDynamicsMode mode) { inverse_dynamics_context_ = inverse_dynamics_->CreateDefaultContext(); output_ = inverse_dynamics_->AllocateOutput(); // Checks that the system has no state. EXPECT_TRUE(inverse_dynamics_context_->is_stateless()); // Checks that the number of input and output ports are as desired. if (mode == InverseDynamics<double>::kGravityCompensation) { EXPECT_EQ(inverse_dynamics_->num_input_ports(), 1); } else { EXPECT_EQ(inverse_dynamics_->num_input_ports(), 2); } EXPECT_EQ(inverse_dynamics_->num_output_ports(), 1); } void CheckGravityTorque(const Eigen::VectorXd& position) { CheckTorque(position, VectorXd::Zero(num_velocities()), VectorXd::Zero(num_velocities())); } void CheckTorque(const Eigen::VectorXd& position, const Eigen::VectorXd& velocity, const Eigen::VectorXd& acceleration_desired) { // Desired acceleration. VectorXd vd_d = VectorXd::Zero(num_velocities()); if (!inverse_dynamics_->is_pure_gravity_compensation()) { vd_d = acceleration_desired; } VectorXd state_input(num_positions() + num_velocities()); state_input << position, velocity; inverse_dynamics_->get_input_port_estimated_state().FixValue( inverse_dynamics_context_.get(), state_input); if (!inverse_dynamics_->is_pure_gravity_compensation()) { inverse_dynamics_->get_input_port_desired_acceleration().FixValue( inverse_dynamics_context_.get(), vd_d); } // Hook input of the expected size. inverse_dynamics_->CalcOutput(*inverse_dynamics_context_, output_.get()); // Compute the expected torque. VectorXd expected_torque; ASSERT_TRUE(multibody_plant_.get()); ASSERT_TRUE(multibody_context_); expected_torque = controllers_test::ComputeTorque( *multibody_plant_, position, velocity, vd_d, multibody_context_.get()); // Checks the expected and computed gravity torque. const BasicVector<double>* output_vector = output_->get_vector_data(0); EXPECT_TRUE(CompareMatrices(expected_torque, output_vector->get_value(), 1e-10, MatrixCompareType::absolute)); } // Determines whether gravity is modeled by checking the generalized forces // due to gravity. bool GravityModeled(const VectorXd& q) const { multibody_plant_->SetPositions(multibody_context_.get(), q); // Verify that gravitational forces are nonzero (validating that the tree // is put into the proper configuration and gravity is modeled). const VectorXd tau_g = multibody_plant_->CalcGravityGeneralizedForces(*multibody_context_); return tau_g.norm() > std::numeric_limits<double>::epsilon(); } private: int num_positions() const { DRAKE_DEMAND(multibody_plant_.get() != nullptr); return multibody_plant_->num_positions(); } int num_velocities() const { DRAKE_DEMAND(multibody_plant_.get() != nullptr); return multibody_plant_->num_velocities(); } std::unique_ptr<MultibodyPlant<double>> multibody_plant_; std::unique_ptr<InverseDynamics<double>> inverse_dynamics_; std::unique_ptr<Context<double>> inverse_dynamics_context_; std::unique_ptr<Context<double>> multibody_context_; std::unique_ptr<SystemOutput<double>> output_; }; // Tests that inverse dynamics returns the expected torque for a given state and // desired acceleration for the iiwa arm. TEST_F(InverseDynamicsTest, InverseDynamicsTest) { auto mbp = std::make_unique<MultibodyPlant<double>>(0.0); multibody::Parser(mbp.get()).AddModelsFromUrl( "package://drake_models/iiwa_description/sdf/iiwa14_no_collision.sdf"); mbp->WeldFrames(mbp->world_frame(), mbp->GetFrameByName("iiwa_link_0")); // Add gravitational forces, finalize the model, and transfer ownership. mbp->mutable_gravity_field().set_gravity_vector(-9.8 * Vector3<double>::UnitZ()); mbp->Finalize(); Init(std::move(mbp), InverseDynamics<double>::InverseDynamicsMode::kInverseDynamics); Eigen::VectorXd q = Eigen::VectorXd::Zero(7); Eigen::VectorXd v = Eigen::VectorXd::Zero(7); Eigen::VectorXd vd_d = Eigen::VectorXd::Zero(7); for (int i = 0; i < 7; ++i) { q[i] = i * 0.1 - 0.3; v[i] = i - 3; vd_d[i] = i - 3; } // Check that gravity is modeled. EXPECT_TRUE(GravityModeled(q)); CheckTorque(q, v, vd_d); } // Tests that inverse dynamics returns the expected torque for a given state and // desired acceleration for the iiwa arm with a custom context. TEST_F(InverseDynamicsTest, InverseDynamicsWithCustomContextTest) { auto mbp = std::make_unique<MultibodyPlant<double>>(0.0); multibody::Parser(mbp.get()).AddModelsFromUrl( "package://drake_models/iiwa_description/sdf/iiwa14_no_collision.sdf"); mbp->WeldFrames(mbp->world_frame(), mbp->GetFrameByName("iiwa_link_0")); mbp->Finalize(); // Create custom context. auto custom_context = mbp->CreateDefaultContext(); const auto& iiwa_link_7 = mbp->GetBodyByName("iiwa_link_7"); iiwa_link_7.SetMass(custom_context.get(), 10.0); // Transfer ownership. Init(std::move(mbp), InverseDynamics<double>::InverseDynamicsMode::kInverseDynamics, std::move(custom_context)); Eigen::VectorXd q = Eigen::VectorXd::Zero(7); Eigen::VectorXd v = Eigen::VectorXd::Zero(7); Eigen::VectorXd vd_d = Eigen::VectorXd::Zero(7); for (int i = 0; i < 7; ++i) { q[i] = i * 0.1 - 0.3; v[i] = i - 3; vd_d[i] = i - 3; } // Check torques with the custom context. CheckTorque(q, v, vd_d); } // Tests that the expected value of the gravity compensating torque and the // value computed by the InverseDynamics in pure gravity compensation mode // for a given joint configuration of the KUKA IIWA Arm are identical. TEST_F(InverseDynamicsTest, GravityCompensationTest) { auto mbp = std::make_unique<MultibodyPlant<double>>(0.0); const std::string url = "package://drake_models/iiwa_description/sdf/iiwa14_no_collision.sdf"; multibody::Parser(mbp.get()).AddModelsFromUrl(url); mbp->WeldFrames(mbp->world_frame(), mbp->GetFrameByName("iiwa_link_0")); mbp->mutable_gravity_field().set_gravity_vector(Vector3<double>::Zero()); // Finalize the model and transfer ownership. mbp->Finalize(); Init(std::move(mbp), InverseDynamics<double>::InverseDynamicsMode::kGravityCompensation); // Defines an arbitrary robot position vector. Eigen::VectorXd robot_position = Eigen::VectorXd::Zero(7); robot_position << 0.01, -0.01, 0.01, 0.5, 0.01, -0.01, 0.01; // Verify that gravity is *not* modeled. EXPECT_FALSE(GravityModeled(robot_position)); // Re-initialize the model so we can add gravity. mbp = std::make_unique<MultibodyPlant<double>>(0.0); multibody::Parser(mbp.get()).AddModelsFromUrl(url); mbp->WeldFrames(mbp->world_frame(), mbp->GetFrameByName("iiwa_link_0")); // Add gravitational forces, finalize the model, and transfer ownership. mbp->mutable_gravity_field().set_gravity_vector(-9.8 * Vector3<double>::UnitZ()); mbp->Finalize(); Init(std::move(mbp), InverseDynamics<double>::InverseDynamicsMode::kGravityCompensation); // Verify that gravity is modeled. EXPECT_TRUE(GravityModeled(robot_position)); CheckGravityTorque(robot_position); } GTEST_TEST(AdditionalInverseDynamicsTest, ScalarConversion) { auto mbp = std::make_unique<MultibodyPlant<double>>(0.0); multibody::Parser(mbp.get()).AddModelsFromUrl( "package://drake_models/iiwa_description/sdf/iiwa14_no_collision.sdf"); mbp->WeldFrames(mbp->world_frame(), mbp->GetFrameByName("iiwa_link_0")); mbp->Finalize(); const int num_states = mbp->num_multibody_states(); InverseDynamics<double> id(mbp.get()); // Test AutoDiffXd. auto id_ad = systems::System<double>::ToAutoDiffXd(id); // Check the multibody plant. EXPECT_EQ(id_ad->get_input_port_estimated_state().size(), num_states); // Check the mode. EXPECT_FALSE(id_ad->is_pure_gravity_compensation()); // Test Expression. auto id_sym = systems::System<double>::ToSymbolic(id); EXPECT_EQ(id_sym->get_input_port_estimated_state().size(), num_states); EXPECT_FALSE(id_sym->is_pure_gravity_compensation()); // Create custom context. auto custom_context = mbp->CreateDefaultContext(); const auto& iiwa_link_7 = mbp->GetBodyByName("iiwa_link_7"); iiwa_link_7.SetMass(custom_context.get(), 10.0); auto mbp_copy = drake::multibody::MultibodyPlant<double>::Clone(*mbp); InverseDynamics<double> id_with_modified_mass( std::move(mbp), InverseDynamics<double>::kGravityCompensation, custom_context.get()); // Test AutoDiffXd. id_ad = systems::System<double>::ToAutoDiffXd(id_with_modified_mass); // Check the multibody plant. EXPECT_EQ(id_ad->get_input_port_estimated_state().size(), num_states); // Check the mode. EXPECT_TRUE(id_ad->is_pure_gravity_compensation()); // Test Expression. id_sym = systems::System<double>::ToSymbolic(id_with_modified_mass); EXPECT_EQ(id_sym->get_input_port_estimated_state().size(), num_states); EXPECT_TRUE(id_sym->is_pure_gravity_compensation()); // Test AutoDiffXd to double. auto id_double = systems::System<AutoDiffXd>::ToScalarType<double>(*id_ad); // Check the multibody plant. EXPECT_EQ(id_double->get_input_port_estimated_state().size(), num_states); // Check the mode. EXPECT_TRUE(id_double->is_pure_gravity_compensation()); // Check gravity torque with custom context. custom_context = mbp_copy->CreateDefaultContext(); iiwa_link_7.SetMass(custom_context.get(), 10.0); Eigen::VectorXd robot_position = Eigen::VectorXd::Zero(7); robot_position << 0.01, -0.01, 0.01, 0.5, 0.01, -0.01, 0.01; VectorXd state_input(14); state_input << robot_position, Eigen::VectorXd::Zero(7); auto id_double_context = id_double->CreateDefaultContext(); id_double->get_input_port_estimated_state().FixValue(id_double_context.get(), state_input); auto output = id_double->AllocateOutput(); id_double->CalcOutput(*id_double_context, output.get()); VectorXd expected_torque; expected_torque = controllers_test::ComputeTorque( *mbp_copy, robot_position, Eigen::VectorXd::Zero(7), Eigen::VectorXd::Zero(7), custom_context.get()); auto output_vector = output->get_vector_data(0); EXPECT_TRUE(CompareMatrices(expected_torque, output_vector->get_value(), 1e-14, MatrixCompareType::absolute)); } } // namespace } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/controllers
/home/johnshepherd/drake/systems/controllers/test/pid_controller_test.cc
#include "drake/systems/controllers/pid_controller.h" #include <memory> #include <string> #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/systems/framework/basic_vector.h" #include "drake/systems/framework/fixed_input_port_value.h" using std::make_unique; namespace drake { namespace systems { namespace controllers { namespace { typedef Eigen::Matrix<double, 3, 1, Eigen::DontAlign> Vector3d; class PidControllerTest : public ::testing::Test { protected: void SetUp() override { context_ = controller_.CreateDefaultContext(); output_ = controller_.AllocateOutput(); derivatives_ = controller_.AllocateTimeDerivatives(); // State: VectorX<double> vec0 = VectorX<double>::Zero(port_size_ * 2); controller_.get_input_port(0).FixValue(context_.get(), vec0); // Desired state: VectorX<double> vec1(port_size_ * 2); vec1 << error_signal_, error_rate_signal_; controller_.get_input_port(1).FixValue(context_.get(), vec1); } const int port_size_{3}; const VectorX<double> kp_{VectorX<double>::Ones(port_size_) * 2.0}; const VectorX<double> ki_{VectorX<double>::Ones(port_size_) * 3.0}; const VectorX<double> kd_{VectorX<double>::Ones(port_size_) * 1.0}; PidController<double> controller_{kp_, ki_, kd_}; std::unique_ptr<Context<double>> context_; std::unique_ptr<SystemOutput<double>> output_; std::unique_ptr<ContinuousState<double>> derivatives_; // Error = estimated - desired. Vector3d error_signal_{1.0, 2.0, 3.0}; Vector3d error_rate_signal_{1.3, 0.9, 3.14}; }; TEST_F(PidControllerTest, PortNames) { EXPECT_EQ(controller_.GetInputPort("estimated_state").get_index(), controller_.get_input_port_estimated_state().get_index()); EXPECT_EQ(controller_.GetInputPort("desired_state").get_index(), controller_.get_input_port_desired_state().get_index()); EXPECT_EQ(controller_.GetOutputPort("control").get_index(), controller_.get_output_port_control().get_index()); } // Tests getter methods for controller constants. TEST_F(PidControllerTest, Getters) { ASSERT_EQ(kp_, controller_.get_Kp_vector()); ASSERT_EQ(ki_, controller_.get_Ki_vector()); ASSERT_EQ(kd_, controller_.get_Kd_vector()); DRAKE_EXPECT_NO_THROW(controller_.get_Kp_singleton()); DRAKE_EXPECT_NO_THROW(controller_.get_Ki_singleton()); DRAKE_EXPECT_NO_THROW(controller_.get_Kd_singleton()); } TEST_F(PidControllerTest, GetterVectors) { const Eigen::Vector2d kp{1.0, 2.0}; const Eigen::Vector2d ki{1.0, 2.0}; const Eigen::Vector2d kd{1.0, 2.0}; PidController<double> controller{kp, ki, kd}; DRAKE_EXPECT_NO_THROW(controller.get_Kp_vector()); DRAKE_EXPECT_NO_THROW(controller.get_Ki_vector()); DRAKE_EXPECT_NO_THROW(controller.get_Kd_vector()); ASSERT_EQ(kp, controller.get_Kp_vector()); ASSERT_EQ(ki, controller.get_Ki_vector()); ASSERT_EQ(kd, controller.get_Kd_vector()); EXPECT_THROW(controller.get_Kp_singleton(), std::runtime_error); } TEST_F(PidControllerTest, GetterVectorKi) { const Eigen::Vector2d kp{1.0, 2.0}; const Eigen::Vector2d ki{1.0, 2.0}; const Eigen::Vector2d kd{1.0, 2.0}; PidController<double> controller{kp, ki, kd}; EXPECT_THROW(controller.get_Ki_singleton(), std::runtime_error); } TEST_F(PidControllerTest, GetterVectorKd) { const Eigen::Vector2d kp{1.0, 2.0}; const Eigen::Vector2d ki{1.0, 2.0}; const Eigen::Vector2d kd{1.0, 2.0}; PidController<double> controller{kp, ki, kd}; EXPECT_THROW(controller.get_Kd_singleton(), std::runtime_error); } // Evaluates the output and asserts correctness. TEST_F(PidControllerTest, CalcOutput) { ASSERT_NE(nullptr, context_); ASSERT_NE(nullptr, output_); // Evaluates the output. controller_.CalcOutput(*context_, output_.get()); ASSERT_EQ(1, output_->num_ports()); const BasicVector<double>* output_vector = output_->get_vector_data(0); EXPECT_EQ(3, output_vector->size()); EXPECT_EQ((kp_.array() * error_signal_.array() + kd_.array() * error_rate_signal_.array()) .matrix(), output_vector->get_value()); // Initializes the integral to a non-zero value. A more interesting example. VectorX<double> integral_value(port_size_); integral_value << 3.0, 2.0, 1.0; controller_.set_integral_value(context_.get(), integral_value); controller_.CalcOutput(*context_, output_.get()); EXPECT_EQ((kp_.array() * error_signal_.array() + ki_.array() * integral_value.array() + kd_.array() * error_rate_signal_.array()) .matrix(), output_vector->get_value()); } // Evaluates derivatives and asserts correctness. TEST_F(PidControllerTest, CalcTimeDerivatives) { ASSERT_NE(nullptr, context_); ASSERT_NE(nullptr, derivatives_); // Evaluates the derivatives. controller_.CalcTimeDerivatives(*context_, derivatives_.get()); ASSERT_EQ(3, derivatives_->size()); ASSERT_EQ(0, derivatives_->get_generalized_position().size()); ASSERT_EQ(0, derivatives_->get_generalized_velocity().size()); ASSERT_EQ(3, derivatives_->get_misc_continuous_state().size()); EXPECT_EQ(error_signal_, derivatives_->CopyToVector()); } TEST_F(PidControllerTest, DirectFeedthrough) { // When the proportional or derivative gain is nonzero, there is direct // feedthrough from both the state and error inputs to the output. EXPECT_TRUE(controller_.HasAnyDirectFeedthrough()); EXPECT_TRUE(controller_.HasDirectFeedthrough(0, 0)); EXPECT_TRUE(controller_.HasDirectFeedthrough(1, 0)); // When the gains are all zero, there is no direct feedthrough from any // input to any output. const VectorX<double> zero{VectorX<double>::Zero(port_size_)}; PidController<double> zero_controller(zero, zero, zero); EXPECT_FALSE(zero_controller.HasAnyDirectFeedthrough()); } TEST_F(PidControllerTest, ToAutoDiff) { std::unique_ptr<System<AutoDiffXd>> clone = controller_.ToAutoDiffXd(); ASSERT_NE(clone, nullptr); const auto* const downcast = dynamic_cast<PidController<AutoDiffXd>*>(clone.get()); ASSERT_NE(downcast, nullptr); EXPECT_EQ(downcast->get_Kp_vector(), kp_); EXPECT_EQ(downcast->get_Ki_vector(), ki_); EXPECT_EQ(downcast->get_Kd_vector(), kd_); } GTEST_TEST(PidConstructorTest, TestThrow) { // Gains size mismatch. EXPECT_THROW(PidController<double>(VectorX<double>(2), VectorX<double>(3), VectorX<double>(3)), std::logic_error); // State projection row != 2 * |kp|. EXPECT_THROW(PidController<double>(MatrixX<double>(5, 2), VectorX<double>(3), VectorX<double>(3), VectorX<double>(3)), std::logic_error); // Output projection col != |kp| EXPECT_THROW(PidController<double>(MatrixX<double>(6, 2), MatrixX<double>(3, 2), VectorX<double>(3), VectorX<double>(3), VectorX<double>(3)), std::logic_error); } // Tests the full version with non identity P_input and P_output. GTEST_TEST(PidIOProjectionTest, Test) { const int num_full_q = 3; const int num_controlled_q = 2; const int num_control = 3; std::srand(1234); const VectorX<double> kp = VectorX<double>::Random(num_controlled_q); const VectorX<double> kd = VectorX<double>::Random(num_controlled_q); const VectorX<double> ki = VectorX<double>::Random(num_controlled_q); MatrixX<double> P_input = MatrixX<double>::Random(2 * num_controlled_q, 2 * num_full_q); MatrixX<double> P_output = MatrixX<double>::Random(num_control, num_controlled_q); PidController<double> dut(P_input, P_output, kp, ki, kd); auto context = dut.CreateDefaultContext(); auto output = dut.AllocateOutput(); VectorX<double> x = VectorX<double>::Random(2 * num_full_q); VectorX<double> x_d = VectorX<double>::Random(2 * num_controlled_q); VectorX<double> integral = VectorX<double>::Random(num_controlled_q); // State: dut.get_input_port(0).FixValue(context.get(), x); // Desired state: dut.get_input_port(1).FixValue(context.get(), x_d); // Integral: dut.set_integral_value(context.get(), integral); dut.CalcOutput(*context, output.get()); VectorX<double> x_err = x_d - P_input * x; auto q_err = x_err.head(num_controlled_q); auto v_err = x_err.tail(num_controlled_q); VectorX<double> output_expected = (kp.array() * q_err.array()).matrix() + (kd.array() * v_err.array()).matrix() + (ki.array() * integral.array()).matrix(); output_expected = P_output * output_expected; EXPECT_TRUE(CompareMatrices(output_expected, output->get_vector_data(0)->get_value(), 1e-12, MatrixCompareType::absolute)); } } // namespace } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/controllers
/home/johnshepherd/drake/systems/controllers/test/pid_controlled_system_test.cc
#include "drake/systems/controllers/pid_controlled_system.h" #include <memory> #include <gtest/gtest.h> #include "drake/common/eigen_types.h" #include "drake/common/test_utilities/expect_no_throw.h" #include "drake/systems/framework/diagram.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/framework/leaf_system.h" #include "drake/systems/primitives/constant_vector_source.h" #include "drake/systems/primitives/saturation.h" namespace drake { namespace systems { namespace controllers { namespace { // This is the parent class of the two test plants defined below. class TestPlant : public LeafSystem<double> { public: TestPlant() {} double GetInputValue(const Context<double>& context) { return get_input_port(0).Eval(context)[0]; } }; // A plant with an input port zero of size 1 and an output port zero of size 2. // This is the minimum sized output port zero relative to the size of its input // port zero, meaning all of the elements in its output port zero are fed back // to the PID controller. A diagram of the resulting PidControlledSystem is // given below, where X is the desired state of the plant and Q is the actual // state of the plant. // // 2 +---------------+ // X ---/--->| | 1 +-----------+ 2 // | PidController |--/-->| TestPlant |---/---+---> Q // +-->| | +-----------+ | // | +---------------+ | // | | // +----------------------------------------------+ // class TestPlantWithMinOutputs : public TestPlant { public: TestPlantWithMinOutputs() { DeclareVectorInputPort(kUseDefaultName, 1); DeclareVectorOutputPort(kUseDefaultName, 2, &TestPlantWithMinOutputs::CalcOutputVector, {this->nothing_ticket()}); } void CalcOutputVector(const Context<double>&, BasicVector<double>* output) const { BasicVector<double>& output_vector = *output; output_vector[0] = 1.; output_vector[1] = 0.1; } }; // A plant with an input port one of size 1 and an output port zero of size 6. // The plant's output port zero has four elements that should not be fed back // to the PID controller. A feedback selector system is used to determine which // two elements of the plant's output port zero are fed back to the PID // controller. A diagram of the resulting PidControlledSystem is given below, // where X is the desired state of the plant and Q is the actual state of the // plant. // // 2 +---------------+ // X ---/--->| | 1 +-----------+ 6 // | PidController |--/-->| TestPlant |---/---+---> Q // +-->| | +-----------+ | // | +---------------+ | // | | // | 2 +------------------+ | // +----------/-----------| FeedbackSelector |----+ // +------------------+ // class TestPlantWithMoreOutputs : public TestPlant { public: TestPlantWithMoreOutputs() { DeclareVectorInputPort(kUseDefaultName, 1); DeclareVectorOutputPort(kUseDefaultName, 6, &TestPlantWithMoreOutputs::CalcOutputVector, {this->nothing_ticket()}); } void CalcOutputVector(const Context<double>&, BasicVector<double>* output) const { BasicVector<double>& output_vector = *output; output_vector[0] = 1.; output_vector[1] = 0.1; output_vector[2] = 3.14; output_vector[3] = 6.89; output_vector[4] = 90.37; output_vector[5] = 498.9; } }; class TestPlantWithMoreOutputPorts : public TestPlant { public: TestPlantWithMoreOutputPorts() { // Declare some empty plant input port. DeclareVectorInputPort(kUseDefaultName, 0); DeclareVectorInputPort(kUseDefaultName, 1); // Declare some non-state output port. DeclareVectorOutputPort( kUseDefaultName, 3, &TestPlantWithMoreOutputPorts::CalcNonStateOutputVector, {this->nothing_ticket()}); DeclareVectorOutputPort( kUseDefaultName, 2, &TestPlantWithMoreOutputPorts::CalcStateOutputVector, {this->nothing_ticket()}); } void CalcNonStateOutputVector(const Context<double>&, BasicVector<double>* output) const { BasicVector<double>& output_vector = *output; output_vector[0] = 2.; output_vector[1] = 0.2; output_vector[2] = 0.02; } void CalcStateOutputVector(const Context<double>&, BasicVector<double>* output) const { BasicVector<double>& output_vector = *output; output_vector[0] = 43.; output_vector[1] = 0.68; } }; class PidControlledSystemTest : public ::testing::Test { protected: // Instantiates a PidControlledSystem based on the supplied plant and // feedback selector. Verifies that the output of the PID controller is // correct relative to the hard-coded input and gain values. void DoPidControlledSystemTest( std::unique_ptr<TestPlant> plant, const MatrixX<double>& feedback_selector) { DiagramBuilder<double> builder; const Vector1d input(1.); const Eigen::Vector2d state(1.1, 0.2); auto input_source = builder.AddSystem<ConstantVectorSource>(input); input_source->set_name("input"); auto state_source = builder.AddSystem<ConstantVectorSource>(state); state_source->set_name("state"); auto controller = builder.AddSystem<PidControlledSystem>( std::move(plant), feedback_selector, Kp_, Ki_, Kd_); builder.Connect(input_source->get_output_port(), controller->get_input_port(0)); builder.Connect(state_source->get_output_port(), controller->get_input_port(1)); builder.ExportOutput(controller->get_output_port(0)); diagram_ = builder.Build(); auto context = diagram_->CreateDefaultContext(); auto output = diagram_->AllocateOutput(); const systems::Context<double>& plant_context = diagram_->GetSubsystemContext(*controller->plant(), *context); diagram_->CalcOutput(*context, output.get()); const BasicVector<double>* output_vec = output->get_vector_data(0); const double pid_input = dynamic_cast<TestPlant*>(controller->plant()) ->GetInputValue(plant_context); EXPECT_EQ(pid_input, input[0] + (state[0] - output_vec->get_value()[0]) * Kp_(0) + (state[1] - output_vec->get_value()[1]) * Kd_(0)); } const Vector1d Kp_{2}; const Vector1d Ki_{0}; const Vector1d Kd_{0.1}; std::unique_ptr<Diagram<double>> diagram_; }; // Tests that the PidController preserves the names of the plant. TEST_F(PidControlledSystemTest, ExistingNamesRespected) { auto plant = std::make_unique<TestPlantWithMinOutputs>(); plant->set_name("my awesome plant!"); auto plant_ptr = plant.get(); const int state_size = plant->get_output_port(0).size(); PidControlledSystem<double> controller( std::move(plant), MatrixX<double>::Identity(state_size, state_size), Kp_, Ki_, Kd_); EXPECT_EQ("my awesome plant!", plant_ptr->get_name()); } // Tests a plant where the size of output port zero is twice the size of input // port zero. TEST_F(PidControlledSystemTest, SimplePidControlledSystem) { // Our test plant is just a multiplexer which takes the input and outputs it // twice. auto plant = std::make_unique<TestPlantWithMinOutputs>(); const int state_size = plant->get_output_port(0).size(); DoPidControlledSystemTest(std::move(plant), MatrixX<double>::Identity(state_size, state_size)); } // Tests a plant where the size of output port zero is more than twice the size // of input port zero. TEST_F(PidControlledSystemTest, PlantWithMoreOutputs) { auto plant = std::make_unique<TestPlantWithMoreOutputs>(); const int plant_output_size = plant->get_output_port(0).size(); const int controller_feedback_size = plant->get_input_port(0).size() * 2; // Selects the first two signals from the plant's output port zero as the // feedback for the controller. MatrixX<double> feedback_selector_matrix(controller_feedback_size, plant_output_size); EXPECT_EQ(feedback_selector_matrix.rows(), 2); EXPECT_EQ(feedback_selector_matrix.cols(), 6); feedback_selector_matrix << 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0; DoPidControlledSystemTest(std::move(plant), feedback_selector_matrix); } // Tests that additional output ports of the plant are exposed through the // new diagram. TEST_F(PidControlledSystemTest, PlantWithMoreOutputPorts) { auto plant = std::make_unique<TestPlantWithMoreOutputPorts>(); const int state_output_port_index = 1; const int plant_input_port_index = 1; PidControlledSystem<double> system(std::move(plant), Kp_, Ki_, Kd_, state_output_port_index, plant_input_port_index); EXPECT_EQ(system.num_output_ports(), 2); EXPECT_EQ(system.get_output_port(0).size(), 3); EXPECT_EQ(system.get_output_port(1).size(), 2); auto context = system.CreateDefaultContext(); auto output = system.AllocateOutput(); system.CalcOutput(*context, output.get()); EXPECT_EQ(output->get_vector_data(0)->GetAtIndex(1), 0.2); EXPECT_EQ(output->get_vector_data(1)->GetAtIndex(1), 0.68); } class ConnectControllerTest : public ::testing::Test { protected: void SetUp() override { auto plant_ptr = std::make_unique<TestPlantWithMinOutputs>(); feedback_selector_ = MatrixX<double>::Identity( plant_ptr->get_output_port(0).size(), plant_ptr->get_output_port(0).size()); plant_ = builder_.AddSystem(std::move(plant_ptr)); input_source_ = builder_.AddSystem<ConstantVectorSource>(plant_input_); state_source_ = builder_.AddSystem<ConstantVectorSource>(desired_state_); builder_.ExportOutput(plant_->get_output_port(0)); } void ConnectPidPorts( PidControlledSystem<double>::ConnectResult plant_pid_ports) { builder_.Connect(input_source_->get_output_port(), plant_pid_ports.control_input_port); builder_.Connect(state_source_->get_output_port(), plant_pid_ports.state_input_port); } double ComputePidInput() { auto standard_diagram = builder_.Build(); auto context = standard_diagram->CreateDefaultContext(); auto plant_output = standard_diagram->GetSubsystemByName(plant_->get_name()) .AllocateOutput(); auto& plant_context = standard_diagram->GetSubsystemContext(*plant_, *context); plant_->CalcOutput(plant_context, plant_output.get()); const BasicVector<double>* output_vec = plant_output->get_vector_data(0); const double pid_input = dynamic_cast<TestPlant*>(plant_)->GetInputValue(plant_context); output_position_ = output_vec->get_value()[0]; output_velocity_ = output_vec->get_value()[1]; return pid_input; } TestPlantWithMinOutputs* plant_; const Vector1d Kp{4}; const Vector1d Ki{0}; const Vector1d Kd{0.5}; DiagramBuilder<double> builder_; ConstantVectorSource<double>* input_source_ = nullptr; ConstantVectorSource<double>* state_source_ = nullptr; MatrixX<double> feedback_selector_; const Vector1d plant_input_{1.0}; const Eigen::Vector2d desired_state_{1.1, 0.2}; double output_position_{0.0}; double output_velocity_{0.0}; }; // Tests a plant where the controller is attached with the ConnectController // method. TEST_F(ConnectControllerTest, NonSaturatingController) { auto plant_pid_ports = PidControlledSystem<double>::ConnectController( plant_->get_input_port(0), plant_->get_output_port(0), feedback_selector_, Kp, Ki, Kd, &builder_); ConnectPidPorts(plant_pid_ports); const double pid_input = ComputePidInput(); double calculated_input = plant_input_[0] + (desired_state_[0] - output_position_) * Kp(0) + (desired_state_[1] - output_velocity_) * Kd(0); EXPECT_EQ(pid_input, calculated_input); } // Tests a plant where the controller is attached with the ConnectController // method and a Saturation in the input to the plant. TEST_F(ConnectControllerTest, SaturatingController) { // Sets the max input in the case of saturation_test. const double saturation_max = 0.5; auto plant_pid_ports = PidControlledSystem<double>::ConnectControllerWithInputSaturation( plant_->get_input_port(0), plant_->get_output_port(0), feedback_selector_, Kp, Ki, Kd, Vector1d(0.0) /* u_min */, Vector1d(saturation_max), &builder_); ConnectPidPorts(plant_pid_ports); const double pid_input = ComputePidInput(); double calculated_input = saturation_max; EXPECT_EQ(pid_input, calculated_input); } // Ensure that multiple plants can coexist in the same diagram (yes, // this was broken at one point). TEST_F(ConnectControllerTest, MultipleControllerTest) { auto plant_pid_ports = PidControlledSystem<double>::ConnectController( plant_->get_input_port(0), plant_->get_output_port(0), feedback_selector_, Kp, Ki, Kd, &builder_); ConnectPidPorts(plant_pid_ports); // Add another PidControlledSystem and confirm there's nothing that // prevents two plants from existing in the same diagram. SetUp(); auto second_plant_pid_ports = PidControlledSystem<double>::ConnectController( plant_->get_input_port(0), plant_->get_output_port(0), feedback_selector_, Kp, Ki, Kd, &builder_); ConnectPidPorts(second_plant_pid_ports); DRAKE_EXPECT_NO_THROW(builder_.Build()); } } // namespace } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/controllers
/home/johnshepherd/drake/systems/controllers/test/linear_model_predictive_controller_test.cc
#include "drake/systems/controllers/linear_model_predictive_controller.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/math/discrete_algebraic_riccati_equation.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/diagram.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/primitives/linear_system.h" namespace drake { namespace systems { namespace controllers { namespace { using math::DiscreteAlgebraicRiccatiEquation; class TestMpcWithDoubleIntegrator : public ::testing::Test { protected: void SetUp() override { const double kTimeStep = 0.1; // discrete time step. const double kTimeHorizon = 10.; // Time horizon. // A discrete approximation of a double integrator. Eigen::Matrix2d A; Eigen::Vector2d B; A << 1, 0.1, 0, 1; B << 0.005, 0.1; const auto C = Eigen::Matrix<double, 2, 2>::Identity(); const auto D = Eigen::Matrix<double, 2, 1>::Zero(); std::unique_ptr<LinearSystem<double>> system = std::make_unique<LinearSystem<double>>(A, B, C, D, kTimeStep); // Nominal, fixed reference condition. const Eigen::Vector2d x0 = Eigen::Vector2d::Zero(); const Vector1d u0 = Vector1d::Zero(); std::unique_ptr<Context<double>> system_context = system->CreateDefaultContext(); system->get_input_port().FixValue(system_context.get(), u0); system_context->SetDiscreteState(0, x0); dut_.reset(new LinearModelPredictiveController<double>( std::move(system), std::move(system_context), Q_, R_, kTimeStep, kTimeHorizon)); // Store another copy of the linear plant model. system_.reset(new LinearSystem<double>(A, B, C, D, kTimeStep)); } // Cost matrices. const Eigen::Matrix2d Q_ = Eigen::Matrix2d::Identity(); const Vector1d R_ = Vector1d::Constant(1.); std::unique_ptr<LinearModelPredictiveController<double>> dut_; std::unique_ptr<LinearSystem<double>> system_; }; TEST_F(TestMpcWithDoubleIntegrator, TestAgainstInfiniteHorizonSolution) { const double kTolerance = 1e-5; const Eigen::Matrix2d A = system_->A(); const Eigen::Matrix<double, 2, 1> B = system_->B(); // Analytical solution to the LQR problem. const Eigen::Matrix2d S = DiscreteAlgebraicRiccatiEquation(A, B, Q_, R_); const Eigen::Matrix<double, 1, 2> K = -(R_ + B.transpose() * S * B).inverse() * (B.transpose() * S * A); const Eigen::Matrix<double, 2, 1> x0 = Eigen::Vector2d::Ones(); auto context = dut_->CreateDefaultContext(); dut_->get_input_port(0).FixValue(context.get(), x0); std::unique_ptr<SystemOutput<double>> output = dut_->AllocateOutput(); dut_->CalcOutput(*context, output.get()); EXPECT_TRUE(CompareMatrices(K * x0, output->get_vector_data(0)->get_value(), kTolerance)); } namespace { // A discrete-time cubic polynomial system. template <typename T> class CubicPolynomialSystem final : public LeafSystem<T> { public: explicit CubicPolynomialSystem(double time_step) : LeafSystem<T>(SystemTypeTag<CubicPolynomialSystem>{}), time_step_(time_step) { this->DeclareInputPort(kUseDefaultName, kVectorValued, 1); this->DeclareVectorOutputPort(kUseDefaultName, 2, &CubicPolynomialSystem::OutputState, {this->all_state_ticket()}); this->DeclareDiscreteState(2); this->DeclarePeriodicDiscreteUpdateEvent( time_step, 0.0, &CubicPolynomialSystem<T>::CalcDiscreteUpdate); } template <typename U> CubicPolynomialSystem(const CubicPolynomialSystem<U>& other) : CubicPolynomialSystem(other.time_step_) {} private: template <typename> friend class CubicPolynomialSystem; // x1(k+1) = u(k) // x2(k+1) = -x1³(k) void CalcDiscreteUpdate( const Context<T>& context, DiscreteValues<T>* next_state) const { using std::pow; const T& x1 = context.get_discrete_state(0).get_value()[0]; const T& u = this->get_input_port(0).Eval(context)[0]; next_state->set_value(0, Vector2<T>{u, pow(x1, 3.)}); } void OutputState(const systems::Context<T>& context, BasicVector<T>* output) const { output->set_value(context.get_discrete_state(0).get_value()); } const double time_step_{0.}; }; } // namespace class TestMpcWithCubicSystem : public ::testing::Test { protected: const System<double>& GetSystemByName(std::string name, const Diagram<double>& diagram) { const System<double>* result{nullptr}; for (const System<double>* system : diagram.GetSystems()) { if (system->get_name() == name) result = system; } return *result; } void MakeTimeInvariantMpcController() { EXPECT_NE(nullptr, system_); auto context = system_->CreateDefaultContext(); // Set nominal input to zero. system_->get_input_port(0).FixValue(context.get(), 0.); // Set the nominal state. BasicVector<double>& x = context->get_mutable_discrete_state().get_mutable_vector(); x.SetFromVector(Eigen::Vector2d::Zero()); // Fixed point is zero. dut_.reset(new LinearModelPredictiveController<double>( std::move(system_), std::move(context), Q_, R_, time_step_, time_horizon_)); } void MakeControlledSystem(bool is_time_varying) { EXPECT_FALSE(is_time_varying); // TODO(jadecastro) Introduce tests for the // time-varying case. EXPECT_EQ(nullptr, diagram_); system_.reset(new CubicPolynomialSystem<double>(time_step_)); EXPECT_FALSE(system_->HasAnyDirectFeedthrough()); DiagramBuilder<double> builder; auto cubic_system = builder.AddSystem<CubicPolynomialSystem>(time_step_); cubic_system->set_name("cubic_system"); MakeTimeInvariantMpcController(); EXPECT_NE(nullptr, dut_); auto controller = builder.AddSystem(std::move(dut_)); controller->set_name("controller"); builder.Connect(cubic_system->get_output_port(0), controller->get_state_port()); builder.Connect(controller->get_control_port(), cubic_system->get_input_port(0)); diagram_ = builder.Build(); } void Simulate() { EXPECT_NE(nullptr, diagram_); EXPECT_EQ(nullptr, simulator_); simulator_.reset(new Simulator<double>(*diagram_)); const auto& cubic_system = GetSystemByName("cubic_system", *diagram_); Context<double>& cubic_system_context = diagram_->GetMutableSubsystemContext( cubic_system, &simulator_->get_mutable_context()); BasicVector<double>& x0 = cubic_system_context.get_mutable_discrete_state().get_mutable_vector(); // Set an initial condition near the fixed point. x0.SetFromVector(10. * Eigen::Vector2d::Ones()); simulator_->set_target_realtime_rate(1.); simulator_->Initialize(); simulator_->AdvanceTo(time_horizon_); } const double time_step_ = 0.1; const double time_horizon_ = 0.2; // Set up the quadratic cost matrices. const Eigen::Matrix2d Q_ = Eigen::Matrix2d::Identity(); const Vector1d R_ = Vector1d::Constant(1.); std::unique_ptr<Simulator<double>> simulator_; private: std::unique_ptr<LinearModelPredictiveController<double>> dut_; std::unique_ptr<CubicPolynomialSystem<double>> system_; std::unique_ptr<Diagram<double>> diagram_; }; TEST_F(TestMpcWithCubicSystem, TimeInvariantMpc) { const double kTolerance = 1e-10; MakeControlledSystem(false /* is NOT time-varying */); Simulate(); // Result should be deadbeat; expect convergence to within a tiny tolerance in // one step. Eigen::Vector2d result = simulator_->get_mutable_context().get_discrete_state(0).get_value(); EXPECT_TRUE(CompareMatrices(result, Eigen::Vector2d::Zero(), kTolerance)); } GTEST_TEST(TestMpcConstructor, ThrowIfRNotStrictlyPositiveDefinite) { const auto A = Eigen::Matrix<double, 2, 2>::Identity(); const auto B = Eigen::Matrix<double, 2, 2>::Identity(); const auto C = Eigen::Matrix<double, 2, 2>::Identity(); const auto D = Eigen::Matrix<double, 2, 2>::Zero(); std::unique_ptr<LinearSystem<double>> system = std::make_unique<LinearSystem<double>>(A, B, C, D, 1.); std::unique_ptr<Context<double>> context = system->CreateDefaultContext(); system->get_input_port().FixValue(context.get(), Eigen::Vector2d::Zero()); const Eigen::Matrix2d Q = Eigen::Matrix2d::Identity(); // Provide a positive-definite matrix (but not strict). Eigen::Matrix2d R = Eigen::Matrix2d::Identity(); R(0, 0) = 0.; // Expect the constructor to throw since R is not strictly positive definite. EXPECT_THROW(LinearModelPredictiveController<double>( std::move(system), std::move(context), Q, R, 1., 1.), std::runtime_error); } } // namespace } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/controllers
/home/johnshepherd/drake/systems/controllers/test/finite_horizon_linear_quadratic_regulator_test.cc
#include "drake/systems/controllers/finite_horizon_linear_quadratic_regulator.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/systems/controllers/linear_quadratic_regulator.h" #include "drake/systems/framework/test_utilities/scalar_conversion.h" #include "drake/systems/primitives/linear_system.h" #include "drake/systems/primitives/symbolic_vector_system.h" namespace drake { namespace systems { namespace controllers { namespace { // For a time-invariant system and cost, the LinearQuadraticRegulator should be // a stable fixed-point for the finite-horizon solution. GTEST_TEST(FiniteHorizonLQRTest, InfiniteHorizonTest) { // Double integrator dynamics: qddot = u, where q is the position coordinate. Eigen::Matrix2d A; Eigen::Vector2d B; A << 0, 1, 0, 0; B << 0, 1; LinearSystem<double> sys(A, B, Eigen::Matrix<double, 0, 2>::Zero(), Eigen::Matrix<double, 0, 1>::Zero()); Eigen::Matrix2d Q = Eigen::Matrix2d::Identity(); Vector1d R = Vector1d(4.12); Eigen::Vector2d N(2.2, 1.3); LinearQuadraticRegulatorResult lqr_result = LinearQuadraticRegulator(A, B, Q, R, N); const double t0 = 0; const double tf = 40.0; FiniteHorizonLinearQuadraticRegulatorOptions options; auto context = sys.CreateDefaultContext(); sys.get_input_port().FixValue(context.get(), 0.0); options.N = N; // Test that it converges towards the fixed point from zero final cost. FiniteHorizonLinearQuadraticRegulatorResult result = FiniteHorizonLinearQuadraticRegulator(sys, *context, t0, tf, Q, R, options); EXPECT_EQ(result.S->start_time(), t0); EXPECT_EQ(result.S->end_time(), tf); EXPECT_EQ(result.sx->start_time(), t0); EXPECT_EQ(result.sx->end_time(), tf); EXPECT_EQ(result.s0->start_time(), t0); EXPECT_EQ(result.s0->end_time(), tf); // Confirm that it's initialized to zero. EXPECT_TRUE(result.S->value(tf).isZero(1e-12)); EXPECT_TRUE(result.sx->value(tf).isZero(1e-12)); EXPECT_TRUE(result.s0->value(tf).isZero(1e-12)); // Confirm that it converges to the infinite-horizon solution. EXPECT_TRUE(CompareMatrices(result.S->value(t0), lqr_result.S, 1e-5)); EXPECT_TRUE(result.sx->value(t0).isZero(1e-12)); EXPECT_TRUE(result.s0->value(t0).isZero(1e-12)); EXPECT_EQ(result.K->start_time(), t0); EXPECT_EQ(result.K->end_time(), tf); EXPECT_TRUE(CompareMatrices(result.K->value(t0), lqr_result.K, 1e-5)); EXPECT_TRUE(result.k0->value(t0).isZero(1e-12)); EXPECT_TRUE(CompareMatrices(result.x0->value(t0), Eigen::Vector2d::Zero())); EXPECT_TRUE(CompareMatrices(result.x0->value(tf), Eigen::Vector2d::Zero())); EXPECT_TRUE(CompareMatrices(result.u0->value(t0), Vector1d::Zero())); EXPECT_TRUE(CompareMatrices(result.u0->value(tf), Vector1d::Zero())); // Test that the System version also works. const std::unique_ptr<System<double>> regulator = MakeFiniteHorizonLinearQuadraticRegulator(sys, *context, t0, tf, Q, R, options); auto regulator_context = regulator->CreateDefaultContext(); const Eigen::Vector2d x(.1, -.3); regulator->get_input_port(0).FixValue(regulator_context.get(), x); EXPECT_EQ(regulator->get_input_port(0).size(), 2); EXPECT_EQ(regulator->get_output_port(0).size(), 1); EXPECT_TRUE( CompareMatrices(regulator->get_output_port(0).Eval(*regulator_context), -lqr_result.K * x, 1e-5)); // Test that it stays at the fixed-point if initialized at the fixed point. options.Qf = lqr_result.S; result = FiniteHorizonLinearQuadraticRegulator(sys, *context, t0, t0 + 2.0, Q, R, options); EXPECT_TRUE(CompareMatrices(result.S->value(t0), lqr_result.S, 1e-12)); EXPECT_TRUE(CompareMatrices(result.K->value(t0), lqr_result.K, 1e-12)); // Already confirmed above that sx, s0, and k0 stay zero. // Test that the Square Root Method also maintains the fixed point. options.use_square_root_method = true; result = FiniteHorizonLinearQuadraticRegulator(sys, *context, t0, t0 + 2.0, Q, R, options); EXPECT_TRUE(CompareMatrices(result.S->value(t0), lqr_result.S, 1e-4)); EXPECT_TRUE(CompareMatrices(result.K->value(t0), lqr_result.K, 1e-4)); EXPECT_TRUE(CompareMatrices(result.x0->value(t0), Eigen::Vector2d::Zero())); EXPECT_TRUE(CompareMatrices(result.x0->value(tf), Eigen::Vector2d::Zero())); EXPECT_TRUE(CompareMatrices(result.u0->value(t0), Vector1d::Zero())); EXPECT_TRUE(CompareMatrices(result.u0->value(tf), Vector1d::Zero())); } // Verify that we can stabilize a non-zero fixed-point specified via the // nominal trajectory options. GTEST_TEST(FiniteHorizonLQRTest, NominalTrajectoryTest) { symbolic::Variable x("x"); symbolic::Variable u("u"); const auto system = SymbolicVectorSystemBuilder() .state(x) .input(u) .dynamics(-x + pow(x, 3) + u) .Build(); auto context = system->CreateDefaultContext(); system->get_input_port().FixValue(context.get(), 0.0); const Vector1d Q(1.0); const Vector1d R(1.0); FiniteHorizonLinearQuadraticRegulatorOptions options; // We can make any state a fixed point using u = x - x^3. for (const double x0 : std::vector<double>({-2, -1., 0., 1, 2})) { const Vector1d x0v(x0); const Vector1d u0v(x0 - std::pow(x0, 3)); context->SetContinuousState(x0v); system->get_input_port().FixValue(context.get(), u0v); auto linear_sys = Linearize(*system, *context); LinearQuadraticRegulatorResult lqr_result = LinearQuadraticRegulator( linear_sys->A(), linear_sys->B(), Q, R, Eigen::Matrix<double, 0, 0>()); // Test that it stays at the fixed-point if initialized at the fixed point. const double t0 = 2; const double tf = 2.3; options.Qf = lqr_result.S; trajectories::PiecewisePolynomial<double> x0_traj(x0v); options.x0 = &x0_traj; options.xd = &x0_traj; trajectories::PiecewisePolynomial<double> u0_traj(u0v); options.u0 = &u0_traj; FiniteHorizonLinearQuadraticRegulatorResult result = FiniteHorizonLinearQuadraticRegulator(*system, *context, t0, tf, Q, R, options); EXPECT_TRUE( CompareMatrices(result.S->value(t0), result.S->value(tf), 1e-12)); EXPECT_TRUE(CompareMatrices(result.S->value(t0), lqr_result.S, 1e-12)); EXPECT_TRUE(CompareMatrices(result.K->value(t0), lqr_result.K, 1e-12)); EXPECT_TRUE(CompareMatrices(result.x0->value(t0), x0v)); EXPECT_TRUE(CompareMatrices(result.x0->value(tf), x0v)); EXPECT_TRUE(CompareMatrices(result.u0->value(t0), u0v)); EXPECT_TRUE(CompareMatrices(result.u0->value(tf), u0v)); // Test that the System version also works. const std::unique_ptr<System<double>> regulator = MakeFiniteHorizonLinearQuadraticRegulator(*system, *context, t0, tf, Q, R, options); auto regulator_context = regulator->CreateDefaultContext(); const Vector1d xs(-.3); regulator->get_input_port(0).FixValue(regulator_context.get(), xs); EXPECT_EQ(regulator->get_input_port(0).size(), 1); EXPECT_EQ(regulator->get_output_port(0).size(), 1); EXPECT_TRUE( CompareMatrices(regulator->get_output_port(0).Eval(*regulator_context), u0v - lqr_result.K * (xs - x0v), 1e-5)); } } // Tests the affine terms by setting options.xd != options.x0. We can stabilize // the double integrator away from the origin, and the resulting solution should // be match the quadratic form from LQR, but shifted to the new desired fixed // point. GTEST_TEST(FiniteHorizonLQRTest, DoubleIntegratorWithNonZeroGoal) { // Double integrator dynamics: qddot = u, where q is the position coordinate. Eigen::Matrix2d A; Eigen::Vector2d B; A << 0, 1, 0, 0; B << 0, 1; LinearSystem<double> sys(A, B, Eigen::Matrix<double, 0, 2>::Zero(), Eigen::Matrix<double, 0, 1>::Zero()); Eigen::Matrix2d Q = Eigen::Matrix2d::Identity(); Vector1d R = Vector1d(4.12); Eigen::Vector2d N(2.2, 1.3); LinearQuadraticRegulatorResult lqr_result = LinearQuadraticRegulator(A, B, Q, R); const double t0 = 0; const double tf = 15.0; FiniteHorizonLinearQuadraticRegulatorOptions options; auto context = sys.CreateDefaultContext(); sys.get_input_port().FixValue(context.get(), 0.0); const Eigen::Vector2d xdv(2.87, 0); trajectories::PiecewisePolynomial<double> xd_traj(xdv); options.xd = &xd_traj; FiniteHorizonLinearQuadraticRegulatorResult result = FiniteHorizonLinearQuadraticRegulator(sys, *context, t0, tf, Q, R, options); // Confirm that it converges to the solution (the same quadratic form, but // shifted to the new origin): Sxx = lqr.S, sx = -Sxx*xd, s0 = xd'*Sxx*xd. EXPECT_TRUE(CompareMatrices(result.S->value(t0), lqr_result.S, 1e-5)); EXPECT_TRUE(CompareMatrices(result.sx->value(t0), -lqr_result.S * xdv, 1e-5)); EXPECT_TRUE(CompareMatrices(result.s0->value(t0), xdv.transpose() * lqr_result.S * xdv, 1e-5)); // The controller should be the same linear controller, but also shifted to // the new origin: Kx = lqr.K, k0 = -Kx*xdv. EXPECT_TRUE(CompareMatrices(result.K->value(t0), lqr_result.K, 1e-5)); EXPECT_TRUE(CompareMatrices(result.k0->value(t0), -lqr_result.K * xdv, 1e-5)); // Test that the System version also works. const std::unique_ptr<System<double>> regulator = MakeFiniteHorizonLinearQuadraticRegulator(sys, *context, t0, tf, Q, R, options); auto regulator_context = regulator->CreateDefaultContext(); const Eigen::Vector2d x(.1, -.3); regulator->get_input_port(0).FixValue(regulator_context.get(), x); EXPECT_TRUE( CompareMatrices(regulator->get_output_port(0).Eval(*regulator_context), -lqr_result.K * (x - xdv), 1e-5)); } // Tests the affine terms by solving LQR from a different coordinate system. // Given an affine system: xdot = Ax + Bu + c, with B invertible, we have a // fixed point at x0=0, B*u0 = -c. Normally, we would stabilize as a linear // system in relative to x0, u0 using LQR. Here we will leave the coordinate // system alone (x0=0, u0=0), but set B*ud = -c. The steady-state solution to // the finite-horizon LQR problem will contain non-zero affine terms in order // to get back to the offset form of this LQR controller. GTEST_TEST(FiniteHorizonLQRTest, AffineSystemTest) { Eigen::Matrix2d A; Eigen::Matrix2d B; Eigen::Vector2d c; A << 0, 1, 0, 0; B << 5, 6, 7, 8; c << 9, 10; AffineSystem<double> sys(A, B, c, Eigen::Matrix<double, 0, 2>(), Eigen::Matrix<double, 0, 2>(), Eigen::Matrix<double, 0, 1>()); Eigen::Matrix2d Q; Eigen::Matrix2d R; Eigen::Matrix2d N; Q << 0.8, 0.7, 0.7, 0.9; R << 1.4, 0.2, 0.2, 1.2; N << 0.1, 0.2, 0.3, 0.4; // Solve it again with the other interface to get access to S. LinearQuadraticRegulatorResult lqr_result = LinearQuadraticRegulator(A, B, Q, R, N); const double t0 = 0; const double tf = 70.0; FiniteHorizonLinearQuadraticRegulatorOptions options; auto context = sys.CreateDefaultContext(); sys.get_input_port().FixValue(context.get(), Eigen::Vector2d::Zero()); const Eigen::Vector2d udv = -B.inverse() * c; trajectories::PiecewisePolynomial<double> ud_traj(udv); options.ud = &ud_traj; options.N = N; options.Qf = lqr_result.S; FiniteHorizonLinearQuadraticRegulatorResult result = FiniteHorizonLinearQuadraticRegulator(sys, *context, t0, tf, Q, R, options); // The LQR x'Sx is the correct solution, because this is equivalent to solving // the in linear system in xbar=(x-x0), ubar=(u-0); and the LQR solution is // xbar'Sxbar, with x0=0. However, in the finite-horizon version, all of the // affine terms must be correct to cancel each other out. EXPECT_TRUE(CompareMatrices(result.S->value(t0), lqr_result.S, 2e-5)); EXPECT_TRUE(result.sx->value(t0).isZero(1e-5)); EXPECT_TRUE(result.s0->value(t0).isZero(1e-5)); // The LQR controller would be u0 - Kx, so Kx = lqr.K, k0 = -u0. EXPECT_TRUE(CompareMatrices(result.K->value(t0), lqr_result.K, 2e-4)); EXPECT_TRUE(CompareMatrices(result.k0->value(t0), -udv, 1e-5)); // Test that the System version also works. const std::unique_ptr<System<double>> regulator = MakeFiniteHorizonLinearQuadraticRegulator(sys, *context, t0, tf, Q, R, options); auto regulator_context = regulator->CreateDefaultContext(); const Eigen::Vector2d x(.1, -.3); regulator->get_input_port(0).FixValue(regulator_context.get(), x); EXPECT_TRUE( CompareMatrices(regulator->get_output_port(0).Eval(*regulator_context), udv - lqr_result.K * x, 4e-5)); // Test that the square root method also works. options.use_square_root_method = true; result = FiniteHorizonLinearQuadraticRegulator(sys, *context, t0, tf, Q, R, options); EXPECT_TRUE(CompareMatrices(result.S->value(t0), lqr_result.S, 1e-4)); EXPECT_TRUE(result.sx->value(t0).isZero(1e-5)); EXPECT_TRUE(result.s0->value(t0).isZero(1e-5)); EXPECT_TRUE(CompareMatrices(result.K->value(t0), lqr_result.K, 1e-4)); EXPECT_TRUE(CompareMatrices(result.k0->value(t0), -udv, 1e-4)); } // Ensures that we can scalar convert the System version of the regulator. GTEST_TEST(FiniteHorizonLQRTest, ResultSystemIsScalarConvertible) { Eigen::Matrix2d A; Eigen::Vector2d B; A << 0, 1, 0, 0; B << 0, 1; LinearSystem<double> sys(A, B, Eigen::Matrix<double, 0, 2>::Zero(), Eigen::Matrix<double, 0, 1>::Zero()); auto context = sys.CreateDefaultContext(); sys.get_input_port().FixValue(context.get(), 0.0); const double t0 = 0.0; Eigen::Matrix2d Q = Eigen::Matrix2d::Identity(); Vector1d R = Vector1d(1.0); const std::unique_ptr<System<double>> regulator = MakeFiniteHorizonLinearQuadraticRegulator(sys, *context, t0, t0 + 0.1, Q, R); EXPECT_TRUE(is_autodiffxd_convertible(*regulator, [&](const auto& converted) { EXPECT_EQ(converted.num_input_ports(), 1); EXPECT_EQ(converted.num_total_inputs(), 2); EXPECT_EQ(converted.num_output_ports(), 1); EXPECT_EQ(converted.num_total_outputs(), 1); })); EXPECT_TRUE(is_symbolic_convertible(*regulator)); } GTEST_TEST(FiniteHorizonLQRTest, SimulatorConfig) { // Double integrator dynamics: qddot = u, where q is the position coordinate. Eigen::Matrix2d A; Eigen::Vector2d B; A << 0, 1, 0, 0; B << 0, 1; LinearSystem<double> sys(A, B, Eigen::Matrix<double, 0, 2>::Zero(), Eigen::Matrix<double, 0, 1>::Zero()); Eigen::Matrix2d Q = Eigen::Matrix2d::Identity(); Vector1d R = Vector1d(4.12); const double t0 = 0; const double tf = 3.0; FiniteHorizonLinearQuadraticRegulatorOptions options; options.simulator_config.use_error_control = false; options.simulator_config.max_step_size = 0.1; auto context = sys.CreateDefaultContext(); sys.get_input_port().FixValue(context.get(), 0.0); FiniteHorizonLinearQuadraticRegulatorResult result = FiniteHorizonLinearQuadraticRegulator(sys, *context, t0, tf, Q, R, options); const trajectories::PiecewisePolynomial<double>* S = dynamic_cast<const trajectories::PiecewisePolynomial<double>*>( result.S.get()); ASSERT_NE(S, nullptr); EXPECT_EQ(S->get_number_of_segments(), 30); options.simulator_config.max_step_size = 0.2; result = FiniteHorizonLinearQuadraticRegulator(sys, *context, t0, tf, Q, R, options); S = dynamic_cast<const trajectories::PiecewisePolynomial<double>*>( result.S.get()); ASSERT_NE(S, nullptr); EXPECT_EQ(S->get_number_of_segments(), 15); } } // namespace } // namespace controllers } // namespace systems } // namespace drake
0
/home/johnshepherd/drake/systems/controllers
/home/johnshepherd/drake/systems/controllers/test/setpoint_test.cc
#include "drake/systems/controllers/setpoint.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" namespace drake { namespace systems { namespace controllers { // Test rotational difference between the desired and measured orientation. // They are both generated by rotating around the same vector, and they differ // in the angle of rotation. GTEST_TEST(testQPInverseDynamicsController, testPoseSetpoint) { // Desired values are specified with suffix "_d" const double ang_d = 0.3; const Vector3<double> vec_d = Vector3<double>(-0.3, 0.6, 0.9).normalized(); // Desired orientation const math::RigidTransform<double> pose_d(AngleAxis<double>(ang_d, vec_d), Vector3<double>::Zero()); // Set Kp to 1, and everything else to zeros, so the computed acceleration // is the rotation difference. CartesianSetpoint<double> setpoint(pose_d.GetAsIsometry3(), Vector6<double>::Zero(), Vector6<double>::Zero(), Vector6<double>::Constant(1), Vector6<double>::Zero()); math::RigidTransform<double> pose = pose_d; Vector6<double> acc, expected; expected.setZero(); for (double ang = ang_d; ang < ang_d + 2 * M_PI + 0.1; ang += 0.1) { pose.set_rotation(AngleAxis<double>(ang, vec_d)); acc = setpoint.ComputeTargetAcceleration( pose.GetAsIsometry3(), Vector6<double>::Zero()); double err = ang_d - ang; if (err > M_PI) err -= 2 * M_PI; else if (err < -M_PI) err += 2 * M_PI; expected.head<3>() = err * vec_d; EXPECT_TRUE( CompareMatrices(acc, expected, 1e-8, MatrixCompareType::absolute)); } } } // namespace controllers } // namespace systems } // namespace drake
0