Search code examples
drake

Syntax explanation for Custom LeafSystem using TemplateSystem


I am trying to create a custom LeafSystem capable of converting between scalar types.

I have been trying to understand the following code so I can create my own:

@TemplateSystem.define("MySystem_")
def MySystem_(T):

    class Impl(LeafSystem_[T]):
        def _construct(self, value, converter=None):
            LeafSystem_[T].__init__(self, converter=converter)
            self.value = value

        def _construct_copy(self, other, converter=None):
            Impl._construct(self, other.value, converter=converter)

    return Impl

MySystem = MySystem_[None]  # Default instantiation.

I am not a strong python programmer so I apologize if some of these questions are python syntax questions rather than drake.

  1. I am unfamiliar with the following syntax and I am unsure what exactly this is doing: @TemplateSystem.define("MySystem_")
  2. Why is the Impl class contained in MySystem_?
  3. If I want to implement my own functions like I would in a normal LeafSystem would they be defined in Impl?
  4. I am also unsure how exactly the type conversion is being implemented. Lets say I define a system MySystem = MySystem_[float]. However I also want to use this system to create a DirectCollocation. Does DirectCollocation know how to call _construct_copy and convert it to an AutoDiffXd or do I need to type convert myself before hand?

Additionally, any examples that use TemplateSystem would help out a lot and seeing how they are used I think would clear up a lot of my confusion.


Solution

  • Just as a note - keep in mind that Python does not have an actual concept of "templates" in the same way as C++. Instead, we have custom-built Python components for Drake to more closely reflect the C++ API by mimicking templates, similar to things like cppyy.

    Explanation

    TBD. Will edit this in.

    References

    For docs on motivation for templates:

    Examples in Russ's course notes:

    If it helps, here are the unittests exercising the feature: