mujoco icon indicating copy to clipboard operation
mujoco copied to clipboard

Engine error if mjcb_passive callback installed before model instantiation

Open tmplt opened this issue 1 year ago • 2 comments

On x86 Linux with mujoco 3.1.1, in a REPL, a passive force callback can be installed after model instantiation without issue:

>>> import mujoco
>>> def callback(model, data):
...     print("callback")
...
>>> model = mujoco.MjModel.from_xml_string('<mujoco/>')
>>> data = mujoco.MjData(model)
>>> mujoco.set_mjcb_passive(callback)
>>> mujoco.mj_step(model, data)
callback

But not before:

>>> import mujoco
>>> def callback(model, data):
...     print("callback")
... 
>>> mujoco.set_mjcb_passive(callback)
>>> model = mujoco.MjModel.from_xml_string('<mujoco/>')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Error: engine error: Python exception raised

tmplt avatar Jan 29 '24 19:01 tmplt

Is this somewhat related to #1014

I faced this issue as well when running the tutorial colab notebook, trying to define a callback in one of the basic examples. After re running a code cell (and thus reinstating the model) it would also result in this.

martijnhabers avatar Jan 30 '24 14:01 martijnhabers

This is probably because during mjModel construction we run an mj_step using an internal temporary mjData.

The callback implementation in callbacks.cc tries to find the Python objects corresponding to mjModel and mjData, and fails because that mjData wasn't created through Python, and MjModel is not finished construction.

I think our options are:

  1. Try to create temporary py::objects for the mjModel and mjData in this situation, to call the callback.
  2. Disable all callbacks during this internal run of mj_step.

nimrod-gileadi avatar Feb 06 '24 13:02 nimrod-gileadi