Skip to content

Commit

Permalink
Add GetFreeVariables() overload to Expression (#22145)
Browse files Browse the repository at this point in the history
We have Expression::GetVariables() and Formula::GetFreeVariables().
In #22091, we could see that this difference (which is mostly
unnecessary) made the downstream code unnecessarily clunky. This
simple overload resolves it.
  • Loading branch information
RussTedrake authored Nov 11, 2024
1 parent d93b75b commit f859518
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 3 deletions.
2 changes: 2 additions & 0 deletions bindings/pydrake/symbolic/symbolic_py_monolith.cc
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,8 @@ void DefineSymbolicMonolith(py::module m) {
py::arg("env"), doc.Expression.EvaluatePartial.doc)
.def("GetVariables", &Expression::GetVariables,
doc.Expression.GetVariables.doc)
.def("GetFreeVariables", &Expression::GetFreeVariables,
doc.Expression.GetFreeVariables.doc)
.def(
"Substitute",
[](const Expression& self, const Variable& var, const Expression& e) {
Expand Down
2 changes: 2 additions & 0 deletions bindings/pydrake/symbolic/test/symbolic_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,8 @@ def test_get_variables(self):
vars = e_x.GetVariables()
self.assertEqual(len(vars), 1)
self.assertTrue(list(vars)[0].EqualTo(x))
vars2 = e_x.GetFreeVariables()
self.assertTrue(vars2.EqualTo(vars))

def test_get_variable_vector(self):
vars_ = sym.GetVariableVector([e_x, e_y])
Expand Down
4 changes: 4 additions & 0 deletions common/symbolic/expression/expression.h
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,10 @@ class Expression {
/** Collects variables in expression. */
[[nodiscard]] Variables GetVariables() const;

/** Same as GetVariables(); we provide this overload for compatibility with
* Formula. */
[[nodiscard]] Variables GetFreeVariables() const { return GetVariables(); }

/** Checks structural equality.
*
* Two expressions e1 and e2 are structurally equal when they have the same
Expand Down
7 changes: 4 additions & 3 deletions common/symbolic/expression/test/expression_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1925,13 +1925,14 @@ TEST_F(SymbolicExpressionTest, GetVariables) {
EXPECT_FALSE(vars1.include(var_z_));
EXPECT_EQ(vars1.size(), 2u);

const Variables vars2{(x_ * x_ * z_ - y_ * abs(x_) * log(x_ + y_) + cosh(x_) +
cosh(y_) + atan2(x_, y_))
.GetVariables()};
const Expression e = x_ * x_ * z_ - y_ * abs(x_) * log(x_ + y_) + cosh(x_) +
cosh(y_) + atan2(x_, y_);
const Variables vars2{e.GetVariables()};
EXPECT_TRUE(vars2.include(var_x_));
EXPECT_TRUE(vars2.include(var_y_));
EXPECT_TRUE(vars2.include(var_z_));
EXPECT_EQ(vars2.size(), 3u);
EXPECT_TRUE(e.GetFreeVariables() == vars2);
}

TEST_F(SymbolicExpressionTest, Swap) {
Expand Down

0 comments on commit f859518

Please sign in to comment.