RobotLocomotion / drake

Model-based design and verification for robotics.
https://drake.mit.edu
Other
3.35k stars 1.27k forks source link

Serialize symbolic object #17851

Open hongkai-dai opened 2 years ago

hongkai-dai commented 2 years ago

Sometimes I find that the symbolic computation takes a lot of time, and I would like to compute it for once, store the computed symbolic expression / polynomial on the hard disk, and then load that result in the future without re-computing it. I think this requires serializing the symbolic objects.

But I find it hard to even serialize a symbolic variable, whose ID depends on the global variable next_id https://github.com/RobotLocomotion/drake/blob/448ddd54c207b8c3700f47a6ee39da250484fc77/common/symbolic/expression/variable.cc#L27-L33. If I serialize a symbolic variable at one program A, and then deserialize the variable in another program B, the newly deserialized variable will confuse next_id in the second program B. Moreover, symbolic::Variable also has a shared_ptr<const string> name_. Is symbolic::Variable serializable?

cc @jwnimmer-tri

jwnimmer-tri commented 2 years ago

You just need to be careful when de-serializing.

Say that you serialize the variables as a dictionary from ID to name:

{
  11: a,
  22: b
}

And then serialize expressions using the variable IDs:

{
  e: {
    _tag: ExpressionAdd
    left: Var 11,
    right: Var 22,
  }
}

Then when de-serializing you create a map from SerializedId: Variable, to look up a given serialized ID to the Variable it was rehydrated into.

When de-serializing an expression, you'd look up the serialized ID to find the new Variable to use.

The new variables will have a different IDs, but that's OK. You just need to be careful about whether you're referring to an old (serialized) ID or a new (rehydrated) ID.