Skip to content

Commit

Permalink
[symbolic] Fix SparseMatrix<Expression> data loss (#18219)
Browse files Browse the repository at this point in the history
  • Loading branch information
jwnimmer-tri authored Oct 31, 2022
1 parent 679ef89 commit edb3c0a
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 0 deletions.
8 changes: 8 additions & 0 deletions common/symbolic/expression/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,14 @@ drake_cc_googletest(
],
)

drake_cc_googletest(
name = "sparse_test",
deps = [
":expression",
"//common/test_utilities:symbolic_test_util",
],
)

drake_cc_googletest(
name = "substitution_test",
deps = [
Expand Down
3 changes: 3 additions & 0 deletions common/symbolic/expression/boxed_cell.cc
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ void BoxedCell::ConstructCopy(const BoxedCell& other) {
}

void BoxedCell::AssignCopy(const BoxedCell& other) {
if (this == &other) {
return;
}
// Decrement the use_count of our currently-managed cell.
Release();
if (other.is_constant()) {
Expand Down
10 changes: 10 additions & 0 deletions common/symbolic/expression/test/boxed_cell_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,16 @@ TEST_F(BoxedCellTest, CopyAssignCellOntoCell) {
EXPECT_EQ(dut.cell().use_count(), 1);
}

TEST_F(BoxedCellTest, CopyAssignCellOntoSelf) {
BoxedCell dut;
dut.SetSharedCell(MakeVarCell());
BoxedCell& self = dut;
dut = self;
EXPECT_EQ(dut.get_kind(), ExpressionKind::Var);
EXPECT_TRUE(dut.trivially_equals(dut));
EXPECT_EQ(dut.cell().use_count(), 1);
}

TEST_F(BoxedCellTest, CopyAssignCellOntoConstant) {
auto original = std::make_unique<BoxedCell>();
original->SetSharedCell(MakeVarCell());
Expand Down
33 changes: 33 additions & 0 deletions common/symbolic/expression/test/sparse_test.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/* clang-format off to disable clang-format-includes */
#include "drake/common/symbolic/expression/all.h"
/* clang-format on */

#include <vector>

#include <Eigen/Sparse>
#include <gtest/gtest.h>

#include "drake/common/test_utilities/symbolic_test_util.h"

namespace drake {
namespace symbolic {
namespace {

using test::ExprEqual;

// This is a regression test for drake#18218.
GTEST_TEST(SymbolicMatricesTest, SparseMatrices) {
const Variable x("x");
std::vector<Eigen::Triplet<Expression>> triplets;
triplets.push_back(Eigen::Triplet<Expression>(1, 1, 1.1));
triplets.push_back(Eigen::Triplet<Expression>(2, 2, x*2.0));
Eigen::SparseMatrix<Expression> M(3, 3);
M.setFromTriplets(triplets.begin(), triplets.end());
EXPECT_PRED2(ExprEqual, M.coeff(0, 0), 0.0);
EXPECT_PRED2(ExprEqual, M.coeff(1, 1), 1.1);
EXPECT_PRED2(ExprEqual, M.coeff(2, 2), x*2.0);
}

} // namespace
} // namespace symbolic
} // namespace drake

0 comments on commit edb3c0a

Please sign in to comment.