openai / mujoco-py

MuJoCo is a physics engine for detailed, efficient rigid body simulations with contacts. mujoco-py allows using MuJoCo from Python 3.
Other
2.89k stars 813 forks source link

Can I access sensor values from Python? #184

Open manacoa opened 6 years ago

manacoa commented 6 years ago
    <sensor>
        <touch name="left_gripper_sensor" site="left_sensor_zone" />
        <touch name="right_gripper_sensor" site="left_sensor_zone" />       
    </sensor>

How can I access these sensor values from Python using mujoco_py ?

akshay-sophos commented 6 years ago

Does anyone know the answer to this? Looking into the wrapper I found get_sensor_senosordata(name), but it doesn't work https://github.com/openai/mujoco-py/blob/master/scripts/gen_wrappers.py

akshay-sophos commented 6 years ago

If you read sensors section in the MuJoCo documentation, they have written “ Instead their outputs are copied in the array mjData.sensordata and are available for user processing. “

So I created the following function in mujoco_env.py

def get_sensor_sensordata(self, body_name):
    return self.data.sensordata

Now you can call sensor = self.get_sensor_sensordata() Offcourse the bodyname doesn't matter. In your case the value that will be returned is {[sensorvalue(left_gripper)],[sensorvalue(right_gripper)]}.

It worked for me.

AndyCameronBloomfield commented 2 months ago

For anyone finding this way later as I did - the easiest way I found to obtain the sensor data is like this:

FX,FY,FZ = data.sensor('pink_sensor').data

In this example, the sensor is a framepos one which outputs three coordinates, hence I'm mapping it to three different variables. data.sensor('pink_sensor') would get you all the associated data and I'm accessing the 'data' part of that. For a sensor that outputs only one value you'd have something more like this:

F = data.sensor('pink_sensor').data

All the sensor data is actually getting written into an array called sensordata in the order that it's generated but the issue with that is if you have multiple things writing into that array you will need to know the index to find the values you want. I don't recommend this papproach because if you misestimate the size of your sensor's data output you can get really confused but if you know which index your data is at you can also do it like this:

FZ = data.sensordata[2]

Similar to the first solution, you can obtain the control input that has been given to an actuator with:

control = data.actuator('Test_PID').ctrl

Though I found that to set it you need to do something more like this:

MyActuator = data.actuator('Test_PID') MyActuator.ctrl = 10