Skip to content

Commit f859518

Browse files
authored
Add GetFreeVariables() overload to Expression (#22145)
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.
1 parent d93b75b commit f859518

File tree

4 files changed

+12
-3
lines changed

4 files changed

+12
-3
lines changed

bindings/pydrake/symbolic/symbolic_py_monolith.cc

+2
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,8 @@ void DefineSymbolicMonolith(py::module m) {
354354
py::arg("env"), doc.Expression.EvaluatePartial.doc)
355355
.def("GetVariables", &Expression::GetVariables,
356356
doc.Expression.GetVariables.doc)
357+
.def("GetFreeVariables", &Expression::GetFreeVariables,
358+
doc.Expression.GetFreeVariables.doc)
357359
.def(
358360
"Substitute",
359361
[](const Expression& self, const Variable& var, const Expression& e) {

bindings/pydrake/symbolic/test/symbolic_test.py

+2
Original file line numberDiff line numberDiff line change
@@ -691,6 +691,8 @@ def test_get_variables(self):
691691
vars = e_x.GetVariables()
692692
self.assertEqual(len(vars), 1)
693693
self.assertTrue(list(vars)[0].EqualTo(x))
694+
vars2 = e_x.GetFreeVariables()
695+
self.assertTrue(vars2.EqualTo(vars))
694696

695697
def test_get_variable_vector(self):
696698
vars_ = sym.GetVariableVector([e_x, e_y])

common/symbolic/expression/expression.h

+4
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,10 @@ class Expression {
193193
/** Collects variables in expression. */
194194
[[nodiscard]] Variables GetVariables() const;
195195

196+
/** Same as GetVariables(); we provide this overload for compatibility with
197+
* Formula. */
198+
[[nodiscard]] Variables GetFreeVariables() const { return GetVariables(); }
199+
196200
/** Checks structural equality.
197201
*
198202
* Two expressions e1 and e2 are structurally equal when they have the same

common/symbolic/expression/test/expression_test.cc

+4-3
Original file line numberDiff line numberDiff line change
@@ -1925,13 +1925,14 @@ TEST_F(SymbolicExpressionTest, GetVariables) {
19251925
EXPECT_FALSE(vars1.include(var_z_));
19261926
EXPECT_EQ(vars1.size(), 2u);
19271927

1928-
const Variables vars2{(x_ * x_ * z_ - y_ * abs(x_) * log(x_ + y_) + cosh(x_) +
1929-
cosh(y_) + atan2(x_, y_))
1930-
.GetVariables()};
1928+
const Expression e = x_ * x_ * z_ - y_ * abs(x_) * log(x_ + y_) + cosh(x_) +
1929+
cosh(y_) + atan2(x_, y_);
1930+
const Variables vars2{e.GetVariables()};
19311931
EXPECT_TRUE(vars2.include(var_x_));
19321932
EXPECT_TRUE(vars2.include(var_y_));
19331933
EXPECT_TRUE(vars2.include(var_z_));
19341934
EXPECT_EQ(vars2.size(), 3u);
1935+
EXPECT_TRUE(e.GetFreeVariables() == vars2);
19351936
}
19361937

19371938
TEST_F(SymbolicExpressionTest, Swap) {

0 commit comments

Comments
 (0)