python_code
stringlengths 0
780k
| repo_name
stringlengths 7
38
| file_path
stringlengths 5
103
|
---|---|---|
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Helpers for modifying a walker to match mocap data."""
from dm_control import composer
from dm_control import mjcf
from dm_control.locomotion.mocap import mocap_pb2
from dm_control.locomotion.walkers import rescale
import numpy as np
class WalkerInfo:
"""Encapsulates routines that modify a walker to match mocap data."""
def __init__(self, proto):
"""Initializes this object.
Args:
proto: A `mocap_pb2.Walker` protocol buffer.
"""
self._proto = proto
def check_walker_is_compatible(self, walker):
"""Checks whether a given walker is compatible with this `WalkerInfo`."""
mocap_model = getattr(walker, 'mocap_walker_model', None)
if mocap_model is not None and mocap_model != self._proto.model:
model_type_name = list(mocap_pb2.Walker.Model.keys())[list(
mocap_pb2.Walker.Model.values()).index(self._proto.model)]
raise ValueError('Walker is not compatible with model type {!r}: got {}'
.format(model_type_name, walker))
def rescale_walker(self, walker):
"""Rescales a given walker to match the data in this `WalkerInfo`."""
self.check_walker_is_compatible(walker)
for subtree_info in self._proto.scaling.subtree:
body = walker.mjcf_model.find('body', subtree_info.body_name)
subtree_root = body.parent
if subtree_info.parent_length:
position_factor = subtree_info.parent_length / np.linalg.norm(body.pos)
else:
position_factor = subtree_info.size_factor
rescale.rescale_subtree(
subtree_root, position_factor, subtree_info.size_factor)
if self._proto.mass:
physics = mjcf.Physics.from_mjcf_model(walker.mjcf_model.root_model)
current_mass = physics.bind(walker.root_body).subtreemass
mass_factor = self._proto.mass / current_mass
for body in walker.root_body.find_all('body'):
inertial = getattr(body, 'inertial', None)
if inertial:
inertial.mass *= mass_factor
for geom in walker.root_body.find_all('geom'):
if geom.mass is not None:
geom.mass *= mass_factor
else:
current_density = geom.density if geom.density is not None else 1000
geom.density = current_density * mass_factor
def add_marker_sites(self, walker, size=0.01, rgba=(0., 0., 1., .3),
default_to_random_position=True, random_state=None):
"""Adds sites corresponding to mocap tracking markers."""
self.check_walker_is_compatible(walker)
random_state = random_state or np.random
sites = []
if self._proto.markers:
mocap_class = walker.mjcf_model.default.add('default', dclass='mocap')
mocap_class.site.set_attributes(type='sphere', size=(size,), rgba=rgba,
group=composer.SENSOR_SITES_GROUP)
for marker_info in self._proto.markers.marker:
body = walker.mjcf_model.find('body', marker_info.parent)
if not body:
raise ValueError('Walker model does not contain a body named {!r}'
.format(str(marker_info.parent)))
pos = marker_info.position
if not pos:
if default_to_random_position:
pos = random_state.uniform(-0.005, 0.005, size=3)
else:
pos = np.zeros(3)
sites.append(
body.add(
'site', name=str(marker_info.name), pos=pos, dclass=mocap_class))
walker.list_of_site_names = [site.name for site in sites]
return sites
| dm_control-main | dm_control/locomotion/mocap/walkers.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""File loader for DeepMind-preprocessed version of the CMU motion capture data.
The raw CMU point-cloud data is fitted onto the `dm_control.locomotion` CMU
Humanoid walker model and re-exported as an HDF5 file
(https://www.hdfgroup.org/solutions/hdf5/) that can be read by the
`dm_control.locomotion.mocap` package.
The original database is produced and hosted by Carnegie Mellon University at
http://mocap.cs.cmu.edu/, and may be copied, modified, or redistributed without
explicit permission (see http://mocap.cs.cmu.edu/faqs.php).
"""
import hashlib
import os
import requests
import tqdm
H5_FILENAME = {'2019': 'cmu_2019_08756c01.h5',
'2020': 'cmu_2020_dfe3e9e0.h5'}
H5_PATHS = {k: (os.path.join(os.path.dirname(__file__), v),
os.path.join('~/.dm_control', v))
for k, v in H5_FILENAME.items()}
H5_URL_BASE = 'https://storage.googleapis.com/dm_control/'
H5_URL = {'2019': H5_URL_BASE+'cmu_2019_08756c01.h5',
'2020': H5_URL_BASE+'cmu_2020_dfe3e9e0.h5'}
H5_BYTES = {'2019': 488143314,
'2020': 476559420}
H5_SHA256 = {
'2019': '08756c01cb4ac20da9918e70e85c32d4880c6c8c16189b02a18b79a5e79afa2b',
'2020': 'dfe3e9e0b08d32960bdafbf89e541339ca8908a9a5e7f4a2c986362890d72863'}
def _get_cached_file_path(version):
"""Returns the path to the cached data file if one exists."""
for path in H5_PATHS[version]:
expanded_path = os.path.expanduser(path)
try:
if os.path.getsize(expanded_path) != H5_BYTES[version]:
continue
with open(expanded_path, 'rb'):
return expanded_path
except IOError:
continue
return None
def _download_and_cache(version):
"""Downloads CMU data into one of the candidate paths in H5_PATHS."""
for path in H5_PATHS[version]:
expanded_path = os.path.expanduser(path)
try:
os.makedirs(os.path.dirname(expanded_path), exist_ok=True)
f = open(expanded_path, 'wb+')
except IOError:
continue
with f:
try:
_download_into_file(f, version)
except:
os.unlink(expanded_path)
raise
return expanded_path
raise IOError('cannot open file to write download data into, '
f'paths attempted: {H5_PATHS[version]}')
def _download_into_file(f, version, validate_hash=True):
"""Download the CMU data into a file object that has been opened for write."""
with requests.get(H5_URL[version], stream=True) as req:
req.raise_for_status()
total_bytes = int(req.headers['Content-Length'])
progress_bar = tqdm.tqdm(
desc='Downloading CMU mocap data', total=total_bytes,
unit_scale=True, unit_divisor=1024)
try:
for chunk in req.iter_content(chunk_size=102400):
if chunk:
f.write(chunk)
progress_bar.update(len(chunk))
finally:
progress_bar.close()
if validate_hash:
f.seek(0)
if hashlib.sha256(f.read()).hexdigest() != H5_SHA256[version]:
raise RuntimeError('downloaded file is corrupted')
def get_path_for_cmu(version='2020'):
"""Path to mocap data fitted to a version of the CMU Humanoid model."""
assert version in H5_FILENAME.keys()
path = _get_cached_file_path(version)
if path is None:
path = _download_and_cache(version)
return path
| dm_control-main | dm_control/locomotion/mocap/cmu_mocap_data.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
| dm_control-main | dm_control/locomotion/mocap/__init__.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Represents a motion-captured trajectory."""
import collections
import copy
from dm_control.locomotion.mocap import mocap_pb2
from dm_control.locomotion.mocap import props as mocap_props
from dm_control.locomotion.mocap import walkers as mocap_walkers
import numpy as np
STEP_TIME_TOLERANCE = 1e-4
_REPEATED_POSITION_FIELDS = ('end_effectors', 'appendages', 'body_positions')
_REPEATED_QUATERNION_FIELDS = ('body_quaternions',)
def _zero_out_velocities(timestep_proto):
out_proto = copy.deepcopy(timestep_proto)
for walker in out_proto.walkers:
walker.velocity[:] = np.zeros_like(walker.velocity)
walker.angular_velocity[:] = np.zeros_like(walker.angular_velocity)
walker.joints_velocity[:] = np.zeros_like(walker.joints_velocity)
for prop in out_proto.props:
prop.velocity[:] = np.zeros_like(prop.velocity)
prop.angular_velocity[:] = np.zeros_like(prop.angular_velocity)
return out_proto
class Trajectory:
"""Represents a motion-captured trajectory."""
def __init__(self, proto, start_time=None, end_time=None, start_step=None,
end_step=None, zero_out_velocities=True):
"""A wrapper around a mocap trajectory proto.
Args:
proto: proto representing the mocap trajectory.
start_time: Start time of the mocap trajectory if only a subset of the
underlying clip is desired. Defaults to the start of the full clip.
Cannot be used when start_step is provided.
end_time: End time of the mocap trajectory if only a subset of the
underlying clip is desired. Defaults to the end of the full clip.
Cannot be used when end_step is provided.
start_step: Like start_time but using time indices. Defaults to the start
of the full clip. Cannot be used when start_time is provided.
end_step: Like end_time but using time indices. Defaults to the start
of the full clip. Cannot be used when end_time is provided.
zero_out_velocities: Whether to zero out the velocities in the last time
step of the requested trajectory. Depending on the use-case it may be
beneficial to use a stable end pose.
"""
self._proto = proto
self._zero_out_velocities = zero_out_velocities
if (start_time and start_step) or (end_time and end_step):
raise ValueError(('Please specify either start and end times'
'or start and end steps but not both.'))
if start_step:
start_time = start_step * self._proto.dt
if end_step:
end_time = end_step * self._proto.dt
self._set_start_time(start_time or 0.)
self._set_end_time(end_time or (len(self._proto.timesteps)*self._proto.dt))
self._walkers_info = tuple(mocap_walkers.WalkerInfo(walker_proto)
for walker_proto in self._proto.walkers)
self._dict = None
def as_dict(self):
"""Return trajectory as dictionary."""
if self._dict is None:
self._dict = dict()
if self._proto.timesteps:
initial_timestep = self._proto.timesteps[0]
num_walkers = len(initial_timestep.walkers)
for i in range(num_walkers):
key_prefix = 'walker_{:d}/'.format(
i) if num_walkers > 1 else 'walker/'
for field in mocap_pb2.WalkerPose.DESCRIPTOR.fields:
field_name = field.name
def walker_field(timestep, i=i, field_name=field_name):
values = getattr(timestep.walkers[i], field_name)
if field_name in _REPEATED_POSITION_FIELDS:
values = np.reshape(values, (-1, 3))
elif field_name in _REPEATED_QUATERNION_FIELDS:
values = np.reshape(values, (-1, 4))
return np.array(values)
self._dict[key_prefix + field_name] = walker_field
num_props = len(initial_timestep.props)
for i in range(len(initial_timestep.props)):
key_prefix = 'prop_{:d}/'.format(i) if num_props > 1 else 'prop/'
for field in mocap_pb2.PropPose.DESCRIPTOR.fields:
field_name = field.name
def prop_field(timestep, i=i, field_name=field_name):
return np.array(getattr(timestep.props[i], field_name))
self._dict[key_prefix + field_name] = prop_field
self._create_all_items(self._dict)
for k in self._dict:
# make trajectory immutable by default
self._dict[k].flags.writeable = False # pytype: disable=attribute-error
return {k: v[self._start_step:self._end_step]
for k, v in self._dict.items()}
def _create_single_item(self, get_field_in_timestep):
if not self._proto.timesteps:
return np.empty((0))
for i, timestep in enumerate(self._proto.timesteps):
values = get_field_in_timestep(timestep)
if i == 0:
array = np.empty((len(self._proto.timesteps),) + values.shape)
array[i, :] = values
return array
def _create_all_items(self, dictionary):
for key, value in dictionary.items():
if callable(value):
dictionary[key] = self._create_single_item(value)
return dictionary
def _get_quantized_time(self, time):
if time == float('inf'):
return len(self._proto.timesteps) - 1
else:
divided_time = time / self._proto.dt
quantized_time = int(np.round(divided_time))
if np.abs(quantized_time - divided_time) > STEP_TIME_TOLERANCE:
raise ValueError('`time` should be a multiple of dt = {}: got {}'
.format(self._proto.dt, time))
return quantized_time
def _get_step_id(self, time):
quantized_time = self._get_quantized_time(time)
return np.clip(quantized_time + self._start_step,
self._start_step, self._end_step - 1)
def get_modified_trajectory(self, proto_modifier, random_state=None):
modified_proto = copy.deepcopy(self._proto)
if isinstance(proto_modifier, collections.abc.Iterable):
for proto_mod in proto_modifier:
proto_mod(modified_proto, random_state=random_state)
else:
proto_modifier(modified_proto, random_state=random_state)
return type(self)(modified_proto, self.start_time, self.end_time)
@property
def identifier(self):
return self._proto.identifier
@property
def start_time(self):
return self._start_step * self._proto.dt
def _set_start_time(self, new_value):
self._start_step = np.clip(self._get_quantized_time(new_value),
0, len(self._proto.timesteps) - 1)
@start_time.setter
def start_time(self, new_value):
self._set_start_time(new_value)
@property
def start_step(self):
return self._start_step
@start_step.setter
def start_step(self, new_value):
self._start_step = np.clip(int(new_value), 0,
len(self._proto.timesteps) - 1)
@property
def end_step(self):
return self._end_step
@end_step.setter
def end_step(self, new_value):
self._end_step = np.clip(int(new_value), 0,
len(self._proto.timesteps) - 1)
@property
def end_time(self):
return (self._end_step - 1) * self._proto.dt
@property
def clip_end_time(self):
"""Length of the full clip."""
return (len(self._proto.timesteps) -1) * self._proto.dt
def _set_end_time(self, new_value):
self._end_step = 1 + np.clip(self._get_quantized_time(new_value),
0, len(self._proto.timesteps) - 1)
if self._zero_out_velocities:
self._last_timestep = _zero_out_velocities(
self._proto.timesteps[self._end_step - 1])
else:
self._last_timestep = self._proto.timesteps[self._end_step - 1]
@end_time.setter
def end_time(self, new_value):
self._set_end_time(new_value)
@property
def duration(self):
return self.end_time - self.start_time
@property
def num_steps(self):
return self._end_step - self._start_step
@property
def dt(self):
return self._proto.dt
def configure_walkers(self, walkers):
try:
walkers = iter(walkers)
except TypeError:
walkers = iter((walkers,))
for walker, walker_info in zip(walkers, self._walkers_info):
walker_info.rescale_walker(walker)
walker_info.add_marker_sites(walker)
def create_props(self,
proto_modifier=None,
priority_friction=False,
prop_factory=None):
proto = self._proto
prop_factory = prop_factory or mocap_props.Prop
if proto_modifier is not None:
proto = copy.copy(proto)
proto_modifier(proto)
return tuple(
prop_factory(prop_proto, priority_friction=priority_friction)
for prop_proto in proto.props)
def get_timestep_data(self, time):
step_id = self._get_step_id(time)
if step_id == self._end_step - 1:
return self._last_timestep
else:
return self._proto.timesteps[step_id]
def set_walker_poses(self, physics, walkers):
timestep = self._proto.timesteps[self._get_step_id(physics.time())]
for walker, walker_timestep in zip(walkers, timestep.walkers):
walker.set_pose(physics,
position=walker_timestep.position,
quaternion=walker_timestep.quaternion)
physics.bind(walker.mocap_joints).qpos = walker_timestep.joints
def set_prop_poses(self, physics, props):
timestep = self._proto.timesteps[self._get_step_id(physics.time())]
for prop, prop_timestep in zip(props, timestep.props):
prop.set_pose(physics,
position=prop_timestep.position,
quaternion=prop_timestep.quaternion)
| dm_control-main | dm_control/locomotion/mocap/trajectory.py |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: mocap.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0bmocap.proto\x12\x1b\x64m_control.locomotion.mocap\"T\n\x06Marker\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06parent\x18\x02 \x01(\t\x12\x14\n\x08position\x18\x03 \x03(\x01\x42\x02\x10\x01\x12\x16\n\nquaternion\x18\x04 \x03(\x01\x42\x02\x10\x01\">\n\x07Markers\x12\x33\n\x06marker\x18\x01 \x03(\x0b\x32#.dm_control.locomotion.mocap.Marker\"O\n\x0eSubtreeScaling\x12\x11\n\tbody_name\x18\x01 \x01(\t\x12\x15\n\rparent_length\x18\x02 \x01(\x01\x12\x13\n\x0bsize_factor\x18\x03 \x01(\x01\"M\n\rWalkerScaling\x12<\n\x07subtree\x18\x01 \x03(\x0b\x32+.dm_control.locomotion.mocap.SubtreeScaling\"\xa2\x03\n\x06Walker\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x38\n\x05model\x18\x02 \x01(\x0e\x32).dm_control.locomotion.mocap.Walker.Model\x12;\n\x07scaling\x18\x03 \x01(\x0b\x32*.dm_control.locomotion.mocap.WalkerScaling\x12\x35\n\x07markers\x18\x04 \x01(\x0b\x32$.dm_control.locomotion.mocap.Markers\x12\x0c\n\x04mass\x18\x05 \x01(\x01\x12\x1a\n\x12\x65nd_effector_names\x18\x06 \x03(\t\x12\x17\n\x0f\x61ppendage_names\x18\x07 \x03(\t\"\x98\x01\n\x05Model\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0c\n\x08\x43MU_2019\x10\x01\x12\x17\n\x13RESERVED_MODEL_ID_2\x10\x02\x12\x17\n\x13RESERVED_MODEL_ID_3\x10\x03\x12\x0c\n\x08\x43MU_2020\x10\x04\x12\x17\n\x13RESERVED_MODEL_ID_5\x10\x05\x12\x17\n\x13RESERVED_MODEL_ID_6\x10\x06\"\x9b\x01\n\x04Prop\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x36\n\x05shape\x18\x02 \x01(\x0e\x32\'.dm_control.locomotion.mocap.Prop.Shape\x12\x10\n\x04size\x18\x03 \x03(\x01\x42\x02\x10\x01\x12\x0c\n\x04mass\x18\x04 \x01(\x01\"-\n\x05Shape\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\n\n\x06SPHERE\x10\x01\x12\x07\n\x03\x42OX\x10\x02\"\xa8\x02\n\nWalkerPose\x12\x14\n\x08position\x18\x01 \x03(\x01\x42\x02\x10\x01\x12\x16\n\nquaternion\x18\x02 \x03(\x01\x42\x02\x10\x01\x12\x12\n\x06joints\x18\x03 \x03(\x01\x42\x02\x10\x01\x12\x1a\n\x0e\x63\x65nter_of_mass\x18\x04 \x03(\x01\x42\x02\x10\x01\x12\x19\n\rend_effectors\x18\x05 \x03(\x01\x42\x02\x10\x01\x12\x14\n\x08velocity\x18\x06 \x03(\x01\x42\x02\x10\x01\x12\x1c\n\x10\x61ngular_velocity\x18\x07 \x03(\x01\x42\x02\x10\x01\x12\x1b\n\x0fjoints_velocity\x18\x08 \x03(\x01\x42\x02\x10\x01\x12\x16\n\nappendages\x18\t \x03(\x01\x42\x02\x10\x01\x12\x1a\n\x0e\x62ody_positions\x18\n \x03(\x01\x42\x02\x10\x01\x12\x1c\n\x10\x62ody_quaternions\x18\x0b \x03(\x01\x42\x02\x10\x01\"l\n\x08PropPose\x12\x14\n\x08position\x18\x01 \x03(\x01\x42\x02\x10\x01\x12\x16\n\nquaternion\x18\x02 \x03(\x01\x42\x02\x10\x01\x12\x14\n\x08velocity\x18\x03 \x03(\x01\x42\x02\x10\x01\x12\x1c\n\x10\x61ngular_velocity\x18\x04 \x03(\x01\x42\x02\x10\x01\"~\n\x0cTimestepData\x12\x38\n\x07walkers\x18\x01 \x03(\x0b\x32\'.dm_control.locomotion.mocap.WalkerPose\x12\x34\n\x05props\x18\x02 \x03(\x0b\x32%.dm_control.locomotion.mocap.PropPose\"\x82\x02\n\x10\x46ittedTrajectory\x12\x12\n\nidentifier\x18\x01 \x01(\t\x12\x0c\n\x04year\x18\x02 \x01(\x05\x12\r\n\x05month\x18\x03 \x01(\x05\x12\x0b\n\x03\x64\x61y\x18\x04 \x01(\x05\x12\n\n\x02\x64t\x18\x05 \x01(\x01\x12\x34\n\x07walkers\x18\x06 \x03(\x0b\x32#.dm_control.locomotion.mocap.Walker\x12\x30\n\x05props\x18\x07 \x03(\x0b\x32!.dm_control.locomotion.mocap.Prop\x12<\n\ttimesteps\x18\x08 \x03(\x0b\x32).dm_control.locomotion.mocap.TimestepDatab\x06proto3')
_MARKER = DESCRIPTOR.message_types_by_name['Marker']
_MARKERS = DESCRIPTOR.message_types_by_name['Markers']
_SUBTREESCALING = DESCRIPTOR.message_types_by_name['SubtreeScaling']
_WALKERSCALING = DESCRIPTOR.message_types_by_name['WalkerScaling']
_WALKER = DESCRIPTOR.message_types_by_name['Walker']
_PROP = DESCRIPTOR.message_types_by_name['Prop']
_WALKERPOSE = DESCRIPTOR.message_types_by_name['WalkerPose']
_PROPPOSE = DESCRIPTOR.message_types_by_name['PropPose']
_TIMESTEPDATA = DESCRIPTOR.message_types_by_name['TimestepData']
_FITTEDTRAJECTORY = DESCRIPTOR.message_types_by_name['FittedTrajectory']
_WALKER_MODEL = _WALKER.enum_types_by_name['Model']
_PROP_SHAPE = _PROP.enum_types_by_name['Shape']
Marker = _reflection.GeneratedProtocolMessageType('Marker', (_message.Message,), {
'DESCRIPTOR' : _MARKER,
'__module__' : 'mocap_pb2'
# @@protoc_insertion_point(class_scope:dm_control.locomotion.mocap.Marker)
})
_sym_db.RegisterMessage(Marker)
Markers = _reflection.GeneratedProtocolMessageType('Markers', (_message.Message,), {
'DESCRIPTOR' : _MARKERS,
'__module__' : 'mocap_pb2'
# @@protoc_insertion_point(class_scope:dm_control.locomotion.mocap.Markers)
})
_sym_db.RegisterMessage(Markers)
SubtreeScaling = _reflection.GeneratedProtocolMessageType('SubtreeScaling', (_message.Message,), {
'DESCRIPTOR' : _SUBTREESCALING,
'__module__' : 'mocap_pb2'
# @@protoc_insertion_point(class_scope:dm_control.locomotion.mocap.SubtreeScaling)
})
_sym_db.RegisterMessage(SubtreeScaling)
WalkerScaling = _reflection.GeneratedProtocolMessageType('WalkerScaling', (_message.Message,), {
'DESCRIPTOR' : _WALKERSCALING,
'__module__' : 'mocap_pb2'
# @@protoc_insertion_point(class_scope:dm_control.locomotion.mocap.WalkerScaling)
})
_sym_db.RegisterMessage(WalkerScaling)
Walker = _reflection.GeneratedProtocolMessageType('Walker', (_message.Message,), {
'DESCRIPTOR' : _WALKER,
'__module__' : 'mocap_pb2'
# @@protoc_insertion_point(class_scope:dm_control.locomotion.mocap.Walker)
})
_sym_db.RegisterMessage(Walker)
Prop = _reflection.GeneratedProtocolMessageType('Prop', (_message.Message,), {
'DESCRIPTOR' : _PROP,
'__module__' : 'mocap_pb2'
# @@protoc_insertion_point(class_scope:dm_control.locomotion.mocap.Prop)
})
_sym_db.RegisterMessage(Prop)
WalkerPose = _reflection.GeneratedProtocolMessageType('WalkerPose', (_message.Message,), {
'DESCRIPTOR' : _WALKERPOSE,
'__module__' : 'mocap_pb2'
# @@protoc_insertion_point(class_scope:dm_control.locomotion.mocap.WalkerPose)
})
_sym_db.RegisterMessage(WalkerPose)
PropPose = _reflection.GeneratedProtocolMessageType('PropPose', (_message.Message,), {
'DESCRIPTOR' : _PROPPOSE,
'__module__' : 'mocap_pb2'
# @@protoc_insertion_point(class_scope:dm_control.locomotion.mocap.PropPose)
})
_sym_db.RegisterMessage(PropPose)
TimestepData = _reflection.GeneratedProtocolMessageType('TimestepData', (_message.Message,), {
'DESCRIPTOR' : _TIMESTEPDATA,
'__module__' : 'mocap_pb2'
# @@protoc_insertion_point(class_scope:dm_control.locomotion.mocap.TimestepData)
})
_sym_db.RegisterMessage(TimestepData)
FittedTrajectory = _reflection.GeneratedProtocolMessageType('FittedTrajectory', (_message.Message,), {
'DESCRIPTOR' : _FITTEDTRAJECTORY,
'__module__' : 'mocap_pb2'
# @@protoc_insertion_point(class_scope:dm_control.locomotion.mocap.FittedTrajectory)
})
_sym_db.RegisterMessage(FittedTrajectory)
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
_MARKER.fields_by_name['position']._options = None
_MARKER.fields_by_name['position']._serialized_options = b'\020\001'
_MARKER.fields_by_name['quaternion']._options = None
_MARKER.fields_by_name['quaternion']._serialized_options = b'\020\001'
_PROP.fields_by_name['size']._options = None
_PROP.fields_by_name['size']._serialized_options = b'\020\001'
_WALKERPOSE.fields_by_name['position']._options = None
_WALKERPOSE.fields_by_name['position']._serialized_options = b'\020\001'
_WALKERPOSE.fields_by_name['quaternion']._options = None
_WALKERPOSE.fields_by_name['quaternion']._serialized_options = b'\020\001'
_WALKERPOSE.fields_by_name['joints']._options = None
_WALKERPOSE.fields_by_name['joints']._serialized_options = b'\020\001'
_WALKERPOSE.fields_by_name['center_of_mass']._options = None
_WALKERPOSE.fields_by_name['center_of_mass']._serialized_options = b'\020\001'
_WALKERPOSE.fields_by_name['end_effectors']._options = None
_WALKERPOSE.fields_by_name['end_effectors']._serialized_options = b'\020\001'
_WALKERPOSE.fields_by_name['velocity']._options = None
_WALKERPOSE.fields_by_name['velocity']._serialized_options = b'\020\001'
_WALKERPOSE.fields_by_name['angular_velocity']._options = None
_WALKERPOSE.fields_by_name['angular_velocity']._serialized_options = b'\020\001'
_WALKERPOSE.fields_by_name['joints_velocity']._options = None
_WALKERPOSE.fields_by_name['joints_velocity']._serialized_options = b'\020\001'
_WALKERPOSE.fields_by_name['appendages']._options = None
_WALKERPOSE.fields_by_name['appendages']._serialized_options = b'\020\001'
_WALKERPOSE.fields_by_name['body_positions']._options = None
_WALKERPOSE.fields_by_name['body_positions']._serialized_options = b'\020\001'
_WALKERPOSE.fields_by_name['body_quaternions']._options = None
_WALKERPOSE.fields_by_name['body_quaternions']._serialized_options = b'\020\001'
_PROPPOSE.fields_by_name['position']._options = None
_PROPPOSE.fields_by_name['position']._serialized_options = b'\020\001'
_PROPPOSE.fields_by_name['quaternion']._options = None
_PROPPOSE.fields_by_name['quaternion']._serialized_options = b'\020\001'
_PROPPOSE.fields_by_name['velocity']._options = None
_PROPPOSE.fields_by_name['velocity']._serialized_options = b'\020\001'
_PROPPOSE.fields_by_name['angular_velocity']._options = None
_PROPPOSE.fields_by_name['angular_velocity']._serialized_options = b'\020\001'
_MARKER._serialized_start=44
_MARKER._serialized_end=128
_MARKERS._serialized_start=130
_MARKERS._serialized_end=192
_SUBTREESCALING._serialized_start=194
_SUBTREESCALING._serialized_end=273
_WALKERSCALING._serialized_start=275
_WALKERSCALING._serialized_end=352
_WALKER._serialized_start=355
_WALKER._serialized_end=773
_WALKER_MODEL._serialized_start=621
_WALKER_MODEL._serialized_end=773
_PROP._serialized_start=776
_PROP._serialized_end=931
_PROP_SHAPE._serialized_start=886
_PROP_SHAPE._serialized_end=931
_WALKERPOSE._serialized_start=934
_WALKERPOSE._serialized_end=1230
_PROPPOSE._serialized_start=1232
_PROPPOSE._serialized_end=1340
_TIMESTEPDATA._serialized_start=1342
_TIMESTEPDATA._serialized_end=1468
_FITTEDTRAJECTORY._serialized_start=1471
_FITTEDTRAJECTORY._serialized_end=1729
# @@protoc_insertion_point(module_scope)
| dm_control-main | dm_control/locomotion/mocap/mocap_pb2.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Helpers for loading a collection of trajectories."""
import abc
import collections
import operator
from dm_control.composer import variation
from dm_control.locomotion.mocap import mocap_pb2
from dm_control.locomotion.mocap import trajectory
from dm_control.utils import transformations as tr
import numpy as np
from google.protobuf import descriptor
class TrajectoryLoader(metaclass=abc.ABCMeta):
"""Base class for helpers that load and decode mocap trajectories."""
def __init__(self, trajectory_class=trajectory.Trajectory,
proto_modifier=()):
"""Initializes this loader.
Args:
trajectory_class: A Python class that wraps a loaded trajectory proto.
proto_modifier: (optional) A callable, or an iterable of callables, that
modify each trajectory proto in-place after it has been deserialized
from the SSTable.
Raises:
ValueError: If `proto_modifier` is specified, but contains a
non-callable entry.
"""
self._trajectory_class = trajectory_class
if not isinstance(proto_modifier, collections.abc.Iterable):
if proto_modifier is None: # backwards compatibility
proto_modifier = ()
else:
proto_modifier = (proto_modifier,)
for modifier in proto_modifier:
if not callable(modifier):
raise ValueError('{} is not callable'.format(modifier))
self._proto_modifiers = proto_modifier
@abc.abstractmethod
def keys(self):
"""The sequence of identifiers for the loaded trajectories."""
@abc.abstractmethod
def _get_proto_for_key(self, key):
"""Returns a protocol buffer message corresponding to the requested key."""
def get_trajectory(self, key, start_time=None, end_time=None, start_step=None,
end_step=None, zero_out_velocities=True):
"""Retrieves a trajectory identified by `key` from the SSTable."""
proto = self._get_proto_for_key(key)
for modifier in self._proto_modifiers:
modifier(proto)
return self._trajectory_class(proto, start_time=start_time,
end_time=end_time, start_step=start_step,
end_step=end_step,
zero_out_velocities=zero_out_velocities)
class HDF5TrajectoryLoader(TrajectoryLoader):
"""A helper for loading and decoding mocap trajectories from HDF5.
In order to use this class, h5py must be installed (it's an optional
dependency of dm_control).
"""
def __init__(self, path, trajectory_class=trajectory.Trajectory,
proto_modifier=()):
# h5py is an optional dependency of dm_control, so only try to import
# if it's used.
try:
import h5py # pylint: disable=g-import-not-at-top
except ImportError as e:
raise ImportError(
'h5py not found. When installing dm_control, '
'use `pip install dm_control[HDF5]` to enable HDF5TrajectoryLoader.'
) from e
self._h5_file = h5py.File(path, mode='r')
self._keys = tuple(sorted(self._h5_file.keys()))
super().__init__(
trajectory_class=trajectory_class, proto_modifier=proto_modifier)
def keys(self):
return self._keys
def _fill_primitive_proto_fields(self, proto, h5_group, skip_fields=()):
for field in proto.DESCRIPTOR.fields:
if field.name in skip_fields or field.name not in h5_group.attrs:
continue
elif field.type not in (descriptor.FieldDescriptor.TYPE_GROUP,
descriptor.FieldDescriptor.TYPE_MESSAGE):
if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
getattr(proto, field.name).extend(h5_group.attrs[field.name])
else:
setattr(proto, field.name, h5_group.attrs[field.name])
def _fill_repeated_proto_message_fields(self, proto_container,
h5_container, h5_prefix):
for item_id in range(len(h5_container)):
h5_item = h5_container['{:s}_{:d}'.format(h5_prefix, item_id)]
proto = proto_container.add()
self._fill_primitive_proto_fields(proto, h5_item)
def _get_proto_for_key(self, key):
"""Returns a trajectory protocol buffer message for the specified key."""
if isinstance(key, str):
key = key.encode('utf-8')
h5_trajectory = self._h5_file[key]
num_steps = h5_trajectory.attrs['num_steps']
proto = mocap_pb2.FittedTrajectory()
proto.identifier = key
self._fill_primitive_proto_fields(proto, h5_trajectory,
skip_fields=('identifier',))
for _ in range(num_steps):
proto.timesteps.add()
h5_walkers = h5_trajectory['walkers']
for walker_id in range(len(h5_walkers)):
h5_walker = h5_walkers['walker_{:d}'.format(walker_id)]
walker_proto = proto.walkers.add()
self._fill_primitive_proto_fields(walker_proto, h5_walker)
self._fill_repeated_proto_message_fields(
walker_proto.scaling.subtree,
h5_walker['scaling'], h5_prefix='subtree')
self._fill_repeated_proto_message_fields(
walker_proto.markers.marker,
h5_walker['markers'], h5_prefix='marker')
walker_fields = dict()
for field in mocap_pb2.WalkerPose.DESCRIPTOR.fields:
walker_fields[field.name] = np.asarray(h5_walker[field.name])
for timestep_id, timestep in enumerate(proto.timesteps):
walker_timestep = timestep.walkers.add()
for k, v in walker_fields.items():
getattr(walker_timestep, k).extend(v[:, timestep_id])
h5_props = h5_trajectory['props']
for prop_id in range(len(h5_props)):
h5_prop = h5_props['prop_{:d}'.format(prop_id)]
prop_proto = proto.props.add()
self._fill_primitive_proto_fields(prop_proto, h5_prop)
prop_fields = dict()
for field in mocap_pb2.PropPose.DESCRIPTOR.fields:
prop_fields[field.name] = np.asarray(h5_prop[field.name])
for timestep_id, timestep in enumerate(proto.timesteps):
prop_timestep = timestep.props.add()
for k, v in prop_fields.items():
getattr(prop_timestep, k).extend(v[:, timestep_id])
return proto
class PropMassLimiter:
"""A trajectory proto modifier that enforces a maximum mass for each prop."""
def __init__(self, max_mass):
self._max_mass = max_mass
def __call__(self, proto, random_state=None):
for prop in proto.props:
prop.mass = min(prop.mass, self._max_mass)
class PropResizer:
"""A trajectory proto modifier that changes prop sizes and mass."""
def __init__(self, size_factor=None, size_delta=None, mass=None):
if size_factor and size_delta:
raise ValueError(
'Only one of `size_factor` or `size_delta` can be specified.')
elif size_factor:
self._size_variation = size_factor
self._size_op = operator.mul
else:
self._size_variation = size_delta
self._size_op = operator.add
self._mass = mass
def __call__(self, proto, random_state=None):
for prop in proto.props:
size_value = variation.evaluate(self._size_variation,
random_state=random_state)
if not np.shape(size_value):
size_value = np.full(len(prop.size), size_value)
for i in range(len(prop.size)):
prop.size[i] = self._size_op(prop.size[i], size_value[i])
prop.mass = variation.evaluate(self._mass, random_state=random_state)
class ZOffsetter:
"""A trajectory proto modifier that shifts the z position of a trajectory."""
def __init__(self, z_offset=0.0):
self._z_offset = z_offset
def _add_z_offset(self, proto_field):
if len(proto_field) % 3:
raise ValueError('Length of proto_field is not a multiple of 3.')
for i in range(2, len(proto_field), 3):
proto_field[i] += self._z_offset
def __call__(self, proto, random_state=None):
for t in proto.timesteps:
for walker_pose in t.walkers:
# shift walker position.
self._add_z_offset(walker_pose.position)
self._add_z_offset(walker_pose.body_positions)
self._add_z_offset(walker_pose.center_of_mass)
for prop_pose in t.props:
# shift prop position
self._add_z_offset(prop_pose.position)
class AppendageFixer:
def __call__(self, proto, random_state=None):
for t in proto.timesteps:
for walker_pose in t.walkers:
xpos = np.asarray(walker_pose.position)
xquat = np.asarray(walker_pose.quaternion)
appendages = np.reshape(walker_pose.appendages, (-1, 3))
xmat = tr.quat_to_mat(xquat)[:3, :3]
walker_pose.appendages[:] = np.ravel((appendages - xpos) @ xmat)
| dm_control-main | dm_control/locomotion/mocap/loader.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Props that are constructed from motion-capture data."""
from dm_control import composer
from dm_control import mjcf
from dm_control.composer import define
from dm_control.composer.observation import observable
from dm_control.locomotion.mocap import mocap_pb2
import numpy as np
_DEFAULT_LIGHT_PROP_RGBA = np.array([0.77, 0.64, 0.21, 1.])
_DEFAULT_LIGHT_PROP_MASS = 3.
_DEFAULT_HEAVY_PROP_RGBA = np.array([0.77, 0.34, 0.21, 1.])
_DEFAULT_HEAVY_PROP_MASS = 10.
_PROP_SHAPE = {
mocap_pb2.Prop.SPHERE: 'sphere',
mocap_pb2.Prop.BOX: 'box',
}
def _default_prop_rgba(prop_mass):
normalized_mass = np.clip(
(prop_mass - _DEFAULT_LIGHT_PROP_MASS) /
(_DEFAULT_HEAVY_PROP_MASS - _DEFAULT_LIGHT_PROP_MASS), 0., 1.)
return ((1 - normalized_mass) * _DEFAULT_LIGHT_PROP_RGBA +
normalized_mass * _DEFAULT_HEAVY_PROP_RGBA)
class Prop(composer.Entity):
"""A prop that is constructed from motion-capture data."""
def _build(self, prop_proto, rgba=None, priority_friction=False):
rgba = rgba or _default_prop_rgba(prop_proto.mass)
self._mjcf_root = mjcf.RootElement(model=str(prop_proto.name))
self._geom = self._mjcf_root.worldbody.add(
'geom', type=_PROP_SHAPE[prop_proto.shape],
size=prop_proto.size, mass=prop_proto.mass, rgba=rgba)
if priority_friction:
self._geom.priority = 1
self._geom.condim = 6
# Torsional and rolling friction have units of length which correspond
# to the scale of the surface contact "patch" that they approximate.
self._geom.friction = [.7, prop_proto.size[0]/4, prop_proto.size[0]/2]
self._body_geom_ids = ()
self._position = self._mjcf_root.sensor.add(
'framepos', name='position', objtype='geom', objname=self.geom)
self._orientation = self._mjcf_root.sensor.add(
'framequat', name='orientation', objtype='geom', objname=self.geom)
def _build_observables(self):
return Observables(self)
@property
def mjcf_model(self):
return self._mjcf_root
def update_with_new_prop(self, prop):
self._geom.size = prop.geom.size
self._geom.mass = prop.geom.mass
self._geom.rgba = prop.geom.rgba
@property
def geom(self):
return self._geom
def after_compile(self, physics, random_state):
del random_state # unused
self._body_geom_ids = (physics.bind(self._geom).element_id,)
@property
def body_geom_ids(self):
return self._body_geom_ids
@property
def position(self):
"""Ground truth pos sensor."""
return self._position
@property
def orientation(self):
"""Ground truth orientation sensor."""
return self._orientation
class Observables(composer.Observables):
@define.observable
def position(self):
return observable.MJCFFeature('sensordata', self._entity.position)
@define.observable
def orientation(self):
return observable.MJCFFeature('sensordata', self._entity.orientation)
| dm_control-main | dm_control/locomotion/mocap/props.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for loader."""
import os
from absl.testing import absltest
from dm_control.locomotion.mocap import loader
from dm_control.locomotion.mocap import mocap_pb2
from dm_control.locomotion.mocap import trajectory
from google.protobuf import descriptor
from google.protobuf import text_format
from dm_control.utils import io as resources
TEXTPROTOS = [
os.path.join(os.path.dirname(__file__), 'test_001.textproto'),
os.path.join(os.path.dirname(__file__), 'test_002.textproto'),
]
HDF5 = os.path.join(os.path.dirname(__file__), 'test_trajectories.h5')
class HDF5TrajectoryLoaderTest(absltest.TestCase):
def assert_proto_equal(self, x, y, msg=''):
self.assertEqual(type(x), type(y), msg=msg)
for field in x.DESCRIPTOR.fields:
x_field = getattr(x, field.name)
y_field = getattr(y, field.name)
if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
if field.type == descriptor.FieldDescriptor.TYPE_MESSAGE:
for i, (x_child, y_child) in enumerate(zip(x_field, y_field)):
self.assert_proto_equal(
x_child, y_child,
msg=os.path.join(msg, '{}[{}]'.format(field.name, i)))
else:
self.assertEqual(list(x_field), list(y_field),
msg=os.path.join(msg, field.name))
else:
if field.type == descriptor.FieldDescriptor.TYPE_MESSAGE:
self.assert_proto_equal(
x_field, y_field, msg=os.path.join(msg, field.name))
else:
self.assertEqual(x_field, y_field, msg=os.path.join(msg, field.name))
def test_hdf5_agrees_with_textprotos(self):
hdf5_loader = loader.HDF5TrajectoryLoader(
resources.GetResourceFilename(HDF5))
for textproto_path in TEXTPROTOS:
trajectory_textproto = resources.GetResource(textproto_path)
trajectory_from_textproto = mocap_pb2.FittedTrajectory()
text_format.Parse(trajectory_textproto, trajectory_from_textproto)
trajectory_identifier = (
trajectory_from_textproto.identifier.encode('utf-8'))
self.assert_proto_equal(
hdf5_loader.get_trajectory(trajectory_identifier)._proto,
trajectory.Trajectory(trajectory_from_textproto)._proto)
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/locomotion/mocap/loader_test.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for dm_control.locomotion.walkers.base."""
from absl.testing import absltest
from dm_control import mjcf
from dm_control.locomotion.walkers import base
import numpy as np
class FakeWalker(base.Walker):
def _build(self):
self._mjcf_root = mjcf.RootElement(model='walker')
self._torso_body = self._mjcf_root.worldbody.add(
'body', name='torso', xyaxes=[0, 1, 0, -1, 0, 0])
@property
def mjcf_model(self):
return self._mjcf_root
@property
def actuators(self):
return []
@property
def root_body(self):
return self._torso_body
@property
def observable_joints(self):
return []
class BaseWalkerTest(absltest.TestCase):
def testTransformVectorToEgocentricFrame(self):
walker = FakeWalker()
physics = mjcf.Physics.from_mjcf_model(walker.mjcf_model)
# 3D vectors
np.testing.assert_allclose(
walker.transform_vec_to_egocentric_frame(physics, [0, 1, 0]), [1, 0, 0],
atol=1e-10)
np.testing.assert_allclose(
walker.transform_vec_to_egocentric_frame(physics, [-1, 0, 0]),
[0, 1, 0],
atol=1e-10)
np.testing.assert_allclose(
walker.transform_vec_to_egocentric_frame(physics, [0, 0, 1]), [0, 0, 1],
atol=1e-10)
# 2D vectors; z-component is ignored
np.testing.assert_allclose(
walker.transform_vec_to_egocentric_frame(physics, [0, 1]), [1, 0],
atol=1e-10)
np.testing.assert_allclose(
walker.transform_vec_to_egocentric_frame(physics, [-1, 0]), [0, 1],
atol=1e-10)
def testTransformMatrixToEgocentricFrame(self):
walker = FakeWalker()
physics = mjcf.Physics.from_mjcf_model(walker.mjcf_model)
rotation_atob = np.array([[0, 1, 0], [0, 0, -1], [-1, 0, 0]])
ego_rotation_atob = np.array([[0, 0, -1], [0, -1, 0], [-1, 0, 0]])
np.testing.assert_allclose(
walker.transform_xmat_to_egocentric_frame(physics, rotation_atob),
ego_rotation_atob, atol=1e-10)
flat_rotation_atob = np.reshape(rotation_atob, -1)
flat_rotation_ego_atob = np.reshape(ego_rotation_atob, -1)
np.testing.assert_allclose(
walker.transform_xmat_to_egocentric_frame(physics, flat_rotation_atob),
flat_rotation_ego_atob, atol=1e-10)
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/locomotion/walkers/base_test.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Function to rescale the walkers."""
from dm_control import mjcf
def rescale_subtree(body, position_factor, size_factor):
"""Recursively rescales an entire subtree of an MJCF model."""
for child in body.all_children():
if getattr(child, 'fromto', None) is not None:
new_pos = position_factor * 0.5 * (child.fromto[3:] + child.fromto[:3])
new_size = size_factor * 0.5 * (child.fromto[3:] - child.fromto[:3])
child.fromto[:3] = new_pos - new_size
child.fromto[3:] = new_pos + new_size
if getattr(child, 'pos', None) is not None:
child.pos *= position_factor
if getattr(child, 'size', None) is not None:
child.size *= size_factor
if child.tag == 'body' or child.tag == 'worldbody':
rescale_subtree(child, position_factor, size_factor)
def rescale_humanoid(walker, position_factor, size_factor=None, mass=None):
"""Rescales a humanoid walker's lengths, sizes, and masses."""
body = walker.mjcf_model.find('body', 'root')
subtree_root = body.parent
if size_factor is None:
size_factor = position_factor
rescale_subtree(subtree_root, position_factor, size_factor)
if mass is not None:
physics = mjcf.Physics.from_mjcf_model(walker.mjcf_model.root_model)
current_mass = physics.bind(walker.root_body).subtreemass
mass_factor = mass / current_mass
for body in walker.root_body.find_all('body'):
inertial = getattr(body, 'inertial', None)
if inertial:
inertial.mass *= mass_factor
for geom in walker.root_body.find_all('geom'):
if geom.mass is not None:
geom.mass *= mass_factor
else:
current_density = geom.density if geom.density is not None else 1000
geom.density = current_density * mass_factor
| dm_control-main | dm_control/locomotion/walkers/rescale.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Base class for Walkers."""
import abc
from dm_control import composer
from dm_control.composer.observation import observable
from dm_control.locomotion.walkers import base
from dm_control.locomotion.walkers import initializers
from dm_control.mujoco.wrapper.mjbindings import mjlib
import numpy as np
_RANGEFINDER_SCALE = 10.0
_TOUCH_THRESHOLD = 1e-3
class Walker(base.Walker):
"""Legacy base class for Walker robots."""
def _build(self, initializer=None):
self._end_effectors_pos_sensors = []
self._obs_on_other = {}
try:
self._initializers = tuple(initializer)
except TypeError:
self._initializers = (initializer or initializers.UprightInitializer(),)
@property
def upright_pose(self):
return base.WalkerPose()
def _build_observables(self):
return WalkerObservables(self)
def reinitialize_pose(self, physics, random_state):
for initializer in self._initializers:
initializer.initialize_pose(physics, self, random_state)
def aliveness(self, physics):
"""A measure of the aliveness of the walker.
Aliveness measure could be used for deciding on termination (ant flipped
over and it's impossible for it to recover), or used as a shaping reward
to maintain an alive pose that we desired (humanoids remaining upright).
Args:
physics: an instance of `Physics`.
Returns:
a `float` in the range of [-1., 0.] where -1 means not alive and 0. means
alive. In walkers for which the concept of aliveness does not make sense,
the default implementation is to always return 0.0.
"""
return 0.
@property
@abc.abstractmethod
def ground_contact_geoms(self):
"""Geoms in this walker that are expected to be in contact with the ground.
This property is used by some tasks to determine contact-based failure
termination. It should only contain geoms that are expected to be in
contact with the ground during "normal" locomotion. For example, for a
humanoid model, this property would be expected to contain only the geoms
that make up the two feet.
Note that certain specialized tasks may also allow geoms that are not listed
here to be in contact with the ground. For example, a humanoid cartwheel
task would also allow the hands to touch the ground in addition to the feet.
"""
raise NotImplementedError
def after_compile(self, physics, unused_random_state):
super().after_compile(physics, unused_random_state)
self._end_effector_geom_ids = set()
for eff_body in self.end_effectors:
eff_geom = eff_body.find_all('geom')
self._end_effector_geom_ids |= set(physics.bind(eff_geom).element_id)
self._body_geom_ids = set(
physics.bind(geom).element_id
for geom in self.mjcf_model.find_all('geom'))
self._body_geom_ids.difference_update(self._end_effector_geom_ids)
@property
def end_effector_geom_ids(self):
return self._end_effector_geom_ids
@property
def body_geom_ids(self):
return self._body_geom_ids
@property
def obs_on_other(self):
return self._obs_on_other
def end_effector_contacts(self, physics):
"""Collect the contacts with the end effectors.
This function returns any contacts being made with any of the end effectors,
both the other geom with which contact is being made as well as the
magnitude.
Args:
physics: an instance of `Physics`.
Returns:
a dict with as key a tuple of geom ids, of which one is an end effector,
and as value the total magnitude of all contacts between these geoms
"""
return self.collect_contacts(physics, self._end_effector_geom_ids)
def body_contacts(self, physics):
"""Collect the contacts with the body.
This function returns any contacts being made with any of body geoms, except
the end effectors, both the other geom with which contact is being made as
well as the magnitude.
Args:
physics: an instance of `Physics`.
Returns:
a dict with as key a tuple of geom ids, of which one is a body geom,
and as value the total magnitude of all contacts between these geoms
"""
return self.collect_contacts(physics, self._body_geom_ids)
def collect_contacts(self, physics, geom_ids):
contacts = {}
forcetorque = np.zeros(6)
for i, contact in enumerate(physics.data.contact):
if ((contact.geom1 in geom_ids) or
(contact.geom2 in geom_ids)) and contact.dist < contact.includemargin:
mjlib.mj_contactForce(physics.model.ptr, physics.data.ptr, i,
forcetorque)
contacts[(contact.geom1, contact.geom2)] = (forcetorque[0]
+ contacts.get(
(contact.geom1,
contact.geom2), 0.))
return contacts
@property
@abc.abstractmethod
def end_effectors(self):
raise NotImplementedError
@property
@abc.abstractmethod
def egocentric_camera(self):
raise NotImplementedError
@composer.cached_property
def touch_sensors(self):
return self._mjcf_root.sensor.get_children('touch')
@property
def prev_action(self):
"""Returns the actuation actions applied in the previous step.
Concrete walker implementations should provide caching mechanism themselves
in order to access this observable (for example, through `apply_action`).
"""
raise NotImplementedError
def after_substep(self, physics, random_state):
del random_state # Unused.
# As of MuJoCo v2.0, updates to `mjData->subtree_linvel` will be skipped
# unless these quantities are needed by the simulation. We need these in
# order to calculate `torso_{x,y}vel`, so we therefore call `mj_subtreeVel`
# explicitly.
# TODO(b/123065920): Consider using a `subtreelinvel` sensor instead.
mjlib.mj_subtreeVel(physics.model.ptr, physics.data.ptr)
@composer.cached_property
def mocap_joints(self):
return tuple(self.mjcf_model.find_all('joint'))
def actuator_force(self, physics):
return physics.bind(self.observable_joints).qfrc_actuator
@composer.cached_property
def mocap_to_observable_joint_order(self):
mocap_to_obs = [self.mocap_joints.index(j) for j in self.observable_joints]
return mocap_to_obs
@composer.cached_property
def observable_to_mocap_joint_order(self):
obs_to_mocap = [self.observable_joints.index(j) for j in self.mocap_joints]
return obs_to_mocap
@property
def end_effectors_pos_sensors(self):
return self._end_effectors_pos_sensors
class WalkerObservables(base.WalkerObservables):
"""Legacy base class for Walker obserables."""
@composer.observable
def joints_vel(self):
return observable.MJCFFeature('qvel', self._entity.observable_joints)
@composer.observable
def body_height(self):
return observable.MJCFFeature('xpos', self._entity.root_body)[2]
@composer.observable
def end_effectors_pos(self):
"""Position of end effectors relative to torso, in the egocentric frame."""
self._entity.end_effectors_pos_sensors[:] = []
for effector in self._entity.end_effectors:
objtype = effector.tag
if objtype == 'body':
objtype = 'xbody'
self._entity.end_effectors_pos_sensors.append(
self._entity.mjcf_model.sensor.add(
'framepos', name=effector.name + '_end_effector',
objtype=objtype, objname=effector,
reftype='xbody', refname=self._entity.root_body))
def relative_pos_in_egocentric_frame(physics):
return np.reshape(
physics.bind(self._entity.end_effectors_pos_sensors).sensordata, -1)
return observable.Generic(relative_pos_in_egocentric_frame)
@composer.observable
def world_zaxis(self):
"""The world's z-vector in this Walker's torso frame."""
return observable.MJCFFeature('xmat', self._entity.root_body)[6:]
@composer.observable
def sensors_velocimeter(self):
return observable.MJCFFeature('sensordata',
self._entity.mjcf_model.sensor.velocimeter)
@composer.observable
def sensors_force(self):
return observable.MJCFFeature('sensordata',
self._entity.mjcf_model.sensor.force)
@composer.observable
def sensors_torque(self):
return observable.MJCFFeature('sensordata',
self._entity.mjcf_model.sensor.torque)
@composer.observable
def sensors_touch(self):
return observable.MJCFFeature(
'sensordata',
self._entity.mjcf_model.sensor.touch,
corruptor=
lambda v, random_state: np.array(v > _TOUCH_THRESHOLD, dtype=float))
@composer.observable
def sensors_rangefinder(self):
def tanh_rangefinder(physics):
raw = physics.bind(self._entity.mjcf_model.sensor.rangefinder).sensordata
raw = np.array(raw)
raw[raw == -1.0] = np.inf
return _RANGEFINDER_SCALE * np.tanh(raw / _RANGEFINDER_SCALE)
return observable.Generic(tanh_rangefinder)
@composer.observable
def egocentric_camera(self):
return observable.MJCFCamera(self._entity.egocentric_camera,
width=64, height=64)
@composer.observable
def position(self):
return observable.MJCFFeature('xpos', self._entity.root_body)
@composer.observable
def orientation(self):
return observable.MJCFFeature('xmat', self._entity.root_body)
def add_egocentric_vector(self,
name,
world_frame_observable,
enabled=True,
origin_callable=None,
**kwargs):
def _egocentric(physics, origin_callable=origin_callable):
vec = world_frame_observable.observation_callable(physics)()
origin_callable = origin_callable or (lambda physics: np.zeros(vec.size))
delta = vec - origin_callable(physics)
return self._entity.transform_vec_to_egocentric_frame(physics, delta)
self._observables[name] = observable.Generic(_egocentric, **kwargs)
self._observables[name].enabled = enabled
def add_egocentric_xmat(self, name, xmat_observable, enabled=True, **kwargs):
def _egocentric(physics):
return self._entity.transform_xmat_to_egocentric_frame(
physics,
xmat_observable.observation_callable(physics)())
self._observables[name] = observable.Generic(_egocentric, **kwargs)
self._observables[name].enabled = enabled
# Semantic groupings of Walker observables.
def _collect_from_attachments(self, attribute_name):
out = []
for entity in self._entity.iter_entities(exclude_self=True):
out.extend(getattr(entity.observables, attribute_name, []))
return out
@property
def proprioception(self):
return ([self.joints_pos, self.joints_vel,
self.body_height, self.end_effectors_pos, self.world_zaxis] +
self._collect_from_attachments('proprioception'))
@property
def kinematic_sensors(self):
return ([self.sensors_gyro, self.sensors_velocimeter,
self.sensors_accelerometer] +
self._collect_from_attachments('kinematic_sensors'))
@property
def dynamic_sensors(self):
return ([self.sensors_force, self.sensors_torque, self.sensors_touch] +
self._collect_from_attachments('dynamic_sensors'))
# Convenience observables for defining rewards and terminations.
@composer.observable
def veloc_strafe(self):
return observable.MJCFFeature(
'sensordata', self._entity.mjcf_model.sensor.velocimeter)[1]
@composer.observable
def veloc_up(self):
return observable.MJCFFeature(
'sensordata', self._entity.mjcf_model.sensor.velocimeter)[2]
@composer.observable
def veloc_forward(self):
return observable.MJCFFeature(
'sensordata', self._entity.mjcf_model.sensor.velocimeter)[0]
@composer.observable
def gyro_backward_roll(self):
return observable.MJCFFeature(
'sensordata', self._entity.mjcf_model.sensor.gyro)[0]
@composer.observable
def gyro_rightward_roll(self):
return observable.MJCFFeature(
'sensordata', self._entity.mjcf_model.sensor.gyro)[1]
@composer.observable
def gyro_anticlockwise_spin(self):
return observable.MJCFFeature(
'sensordata', self._entity.mjcf_model.sensor.gyro)[2]
@composer.observable
def torso_xvel(self):
return observable.MJCFFeature('subtree_linvel', self._entity.root_body)[0]
@composer.observable
def torso_yvel(self):
return observable.MJCFFeature('subtree_linvel', self._entity.root_body)[1]
@composer.observable
def prev_action(self):
return observable.Generic(lambda _: self._entity.prev_action)
| dm_control-main | dm_control/locomotion/walkers/legacy_base.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for the Rodent."""
from absl.testing import absltest
from absl.testing import parameterized
from dm_control import composer
from dm_control import mjcf
from dm_control.composer.observation.observable import base as observable_base
from dm_control.locomotion.arenas import corridors as corr_arenas
from dm_control.locomotion.tasks import corridors as corr_tasks
from dm_control.locomotion.walkers import rodent
import numpy as np
_CONTROL_TIMESTEP = .02
_PHYSICS_TIMESTEP = 0.001
def _get_rat_corridor_physics():
walker = rodent.Rat()
arena = corr_arenas.EmptyCorridor()
task = corr_tasks.RunThroughCorridor(
walker=walker,
arena=arena,
walker_spawn_position=(5, 0, 0),
walker_spawn_rotation=0,
physics_timestep=_PHYSICS_TIMESTEP,
control_timestep=_CONTROL_TIMESTEP)
env = composer.Environment(
time_limit=30,
task=task,
strip_singleton_obs_buffer_dim=True)
return walker, env
class RatTest(parameterized.TestCase):
def test_can_compile_and_step_simulation(self):
_, env = _get_rat_corridor_physics()
physics = env.physics
for _ in range(100):
physics.step()
@parameterized.parameters([
'egocentric_camera',
'head',
'left_arm_root',
'right_arm_root',
'root_body',
'pelvis_body',
])
def test_get_element_property(self, name):
attribute_value = getattr(rodent.Rat(), name)
self.assertIsInstance(attribute_value, mjcf.Element)
@parameterized.parameters([
'actuators',
'bodies',
'mocap_tracking_bodies',
'end_effectors',
'mocap_joints',
'observable_joints',
])
def test_get_element_tuple_property(self, name):
attribute_value = getattr(rodent.Rat(), name)
self.assertNotEmpty(attribute_value)
for item in attribute_value:
self.assertIsInstance(item, mjcf.Element)
def test_set_name(self):
name = 'fred'
walker = rodent.Rat(name=name)
self.assertEqual(walker.mjcf_model.model, name)
@parameterized.parameters(
'tendons_pos',
'tendons_vel',
'actuator_activation',
'appendages_pos',
'head_height',
'sensors_torque',
)
def test_evaluate_observable(self, name):
walker, env = _get_rat_corridor_physics()
physics = env.physics
observable = getattr(walker.observables, name)
observation = observable(physics)
self.assertIsInstance(observation, (float, np.ndarray))
def test_proprioception(self):
walker = rodent.Rat()
for item in walker.observables.proprioception:
self.assertIsInstance(item, observable_base.Observable)
def test_can_create_two_rats(self):
rat1 = rodent.Rat(name='rat1')
rat2 = rodent.Rat(name='rat2')
arena = corr_arenas.EmptyCorridor()
arena.add_free_entity(rat1)
arena.add_free_entity(rat2)
mjcf.Physics.from_mjcf_model(arena.mjcf_model) # Should not raise an error.
rat1.mjcf_model.model = 'rat3'
rat2.mjcf_model.model = 'rat4'
mjcf.Physics.from_mjcf_model(arena.mjcf_model) # Should not raise an error.
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/locomotion/walkers/rodent_test.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for the CMU humanoid."""
from absl.testing import absltest
from absl.testing import parameterized
from dm_control import mjcf
from dm_control.composer.observation.observable import base as observable_base
from dm_control.locomotion.walkers import cmu_humanoid
import numpy as np
class CMUHumanoidTest(parameterized.TestCase):
@parameterized.parameters([
cmu_humanoid.CMUHumanoid,
cmu_humanoid.CMUHumanoidPositionControlled,
])
def test_can_compile_and_step_simulation(self, walker_type):
walker = walker_type()
physics = mjcf.Physics.from_mjcf_model(walker.mjcf_model)
for _ in range(100):
physics.step()
@parameterized.parameters([
cmu_humanoid.CMUHumanoid,
cmu_humanoid.CMUHumanoidPositionControlled,
])
def test_actuators_sorted_alphabetically(self, walker_type):
walker = walker_type()
actuator_names = [
actuator.name for actuator in walker.mjcf_model.find_all('actuator')]
np.testing.assert_array_equal(actuator_names, sorted(actuator_names))
def test_actuator_to_mocap_joint_mapping(self):
walker = cmu_humanoid.CMUHumanoid()
with self.subTest('Forward mapping'):
for actuator_num, cmu_mocap_joint_num in enumerate(walker.actuator_order):
self.assertEqual(walker.actuator_to_joint_order[cmu_mocap_joint_num],
actuator_num)
with self.subTest('Inverse mapping'):
for cmu_mocap_joint_num, actuator_num in enumerate(
walker.actuator_to_joint_order):
self.assertEqual(walker.actuator_order[actuator_num],
cmu_mocap_joint_num)
def test_cmu_humanoid_position_controlled_has_correct_actuators(self):
walker_torque = cmu_humanoid.CMUHumanoid()
walker_pos = cmu_humanoid.CMUHumanoidPositionControlled()
actuators_torque = walker_torque.mjcf_model.find_all('actuator')
actuators_pos = walker_pos.mjcf_model.find_all('actuator')
actuator_pos_params = {
params.name: params for params in cmu_humanoid._POSITION_ACTUATORS}
self.assertEqual(len(actuators_torque), len(actuators_pos))
for actuator_torque, actuator_pos in zip(actuators_torque, actuators_pos):
self.assertEqual(actuator_pos.name, actuator_torque.name)
self.assertEqual(actuator_pos.joint.full_identifier,
actuator_torque.joint.full_identifier)
self.assertEqual(actuator_pos.tag, 'general')
self.assertEqual(actuator_pos.ctrllimited, 'true')
np.testing.assert_array_equal(actuator_pos.ctrlrange, (-1, 1))
expected_params = actuator_pos_params[actuator_pos.name]
self.assertEqual(actuator_pos.biasprm[1], -expected_params.kp)
np.testing.assert_array_equal(actuator_pos.forcerange,
expected_params.forcerange)
@parameterized.parameters([
'body_camera',
'egocentric_camera',
'head',
'left_arm_root',
'right_arm_root',
'root_body',
])
def test_get_element_property(self, name):
attribute_value = getattr(cmu_humanoid.CMUHumanoid(), name)
self.assertIsInstance(attribute_value, mjcf.Element)
@parameterized.parameters([
'actuators',
'bodies',
'end_effectors',
'marker_geoms',
'mocap_joints',
'observable_joints',
])
def test_get_element_tuple_property(self, name):
attribute_value = getattr(cmu_humanoid.CMUHumanoid(), name)
self.assertNotEmpty(attribute_value)
for item in attribute_value:
self.assertIsInstance(item, mjcf.Element)
def test_set_name(self):
name = 'fred'
walker = cmu_humanoid.CMUHumanoid(name=name)
self.assertEqual(walker.mjcf_model.model, name)
def test_set_marker_rgba(self):
marker_rgba = (1., 0., 1., 0.5)
walker = cmu_humanoid.CMUHumanoid(marker_rgba=marker_rgba)
for marker_geom in walker.marker_geoms:
np.testing.assert_array_equal(marker_geom.rgba, marker_rgba)
@parameterized.parameters(
'actuator_activation',
'appendages_pos',
'body_camera',
'head_height',
'sensors_torque',
)
def test_evaluate_observable(self, name):
walker = cmu_humanoid.CMUHumanoid()
observable = getattr(walker.observables, name)
physics = mjcf.Physics.from_mjcf_model(walker.mjcf_model)
observation = observable(physics)
self.assertIsInstance(observation, (float, np.ndarray))
def test_proprioception(self):
walker = cmu_humanoid.CMUHumanoid()
for item in walker.observables.proprioception:
self.assertIsInstance(item, observable_base.Observable)
def test_cmu_pose_to_actuation(self):
walker = cmu_humanoid.CMUHumanoidPositionControlled()
random_state = np.random.RandomState(123)
expected_actuation = random_state.uniform(-1, 1, len(walker.actuator_order))
cmu_limits = zip(*(joint.range for joint in walker.mocap_joints))
cmu_lower, cmu_upper = (np.array(limit) for limit in cmu_limits)
cmu_pose = cmu_lower + (cmu_upper - cmu_lower) * (
1 + expected_actuation[walker.actuator_to_joint_order]) / 2
actual_actuation = walker.cmu_pose_to_actuation(cmu_pose)
np.testing.assert_allclose(actual_actuation, expected_actuation)
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/locomotion/walkers/cmu_humanoid_test.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for scaled actuators."""
from absl.testing import absltest
from dm_control import mjcf
from dm_control.locomotion.walkers import scaled_actuators
import numpy as np
class ScaledActuatorsTest(absltest.TestCase):
def setUp(self):
super().setUp()
self._mjcf_model = mjcf.RootElement()
self._min = -1.4
self._max = 2.3
self._gain = 1.7
self._scaled_min = -0.8
self._scaled_max = 1.3
self._range = self._max - self._min
self._scaled_range = self._scaled_max - self._scaled_min
self._joints = []
for _ in range(2):
body = self._mjcf_model.worldbody.add('body')
body.add('geom', type='sphere', size=[1])
self._joints.append(body.add('joint', type='hinge'))
self._scaled_actuator_joint = self._joints[0]
self._standard_actuator_joint = self._joints[1]
self._random_state = np.random.RandomState(3474)
def _set_actuator_controls(self, physics, normalized_ctrl,
scaled_actuator=None, standard_actuator=None):
if scaled_actuator is not None:
physics.bind(scaled_actuator).ctrl = (
normalized_ctrl * self._scaled_range + self._scaled_min)
if standard_actuator is not None:
physics.bind(standard_actuator).ctrl = (
normalized_ctrl * self._range + self._min)
def _assert_same_qfrc_actuator(self, physics, joint1, joint2):
np.testing.assert_allclose(physics.bind(joint1).qfrc_actuator,
physics.bind(joint2).qfrc_actuator)
def test_position_actuator(self):
scaled_actuator = scaled_actuators.add_position_actuator(
target=self._scaled_actuator_joint, kp=self._gain,
qposrange=(self._min, self._max),
ctrlrange=(self._scaled_min, self._scaled_max))
standard_actuator = self._mjcf_model.actuator.add(
'position', joint=self._standard_actuator_joint, kp=self._gain,
ctrllimited=True, ctrlrange=(self._min, self._max))
physics = mjcf.Physics.from_mjcf_model(self._mjcf_model)
# Zero torque.
physics.bind(self._scaled_actuator_joint).qpos = (
0.2345 * self._range + self._min)
self._set_actuator_controls(physics, 0.2345, scaled_actuator)
np.testing.assert_allclose(
physics.bind(self._scaled_actuator_joint).qfrc_actuator, 0, atol=1e-15)
for _ in range(100):
normalized_ctrl = self._random_state.uniform()
physics.bind(self._joints).qpos = (
self._random_state.uniform() * self._range + self._min)
self._set_actuator_controls(physics, normalized_ctrl,
scaled_actuator, standard_actuator)
self._assert_same_qfrc_actuator(
physics, self._scaled_actuator_joint, self._standard_actuator_joint)
def test_velocity_actuator(self):
scaled_actuator = scaled_actuators.add_velocity_actuator(
target=self._scaled_actuator_joint, kv=self._gain,
qvelrange=(self._min, self._max),
ctrlrange=(self._scaled_min, self._scaled_max))
standard_actuator = self._mjcf_model.actuator.add(
'velocity', joint=self._standard_actuator_joint, kv=self._gain,
ctrllimited=True, ctrlrange=(self._min, self._max))
physics = mjcf.Physics.from_mjcf_model(self._mjcf_model)
# Zero torque.
physics.bind(self._scaled_actuator_joint).qvel = (
0.5432 * self._range + self._min)
self._set_actuator_controls(physics, 0.5432, scaled_actuator)
np.testing.assert_allclose(
physics.bind(self._scaled_actuator_joint).qfrc_actuator, 0, atol=1e-15)
for _ in range(100):
normalized_ctrl = self._random_state.uniform()
physics.bind(self._joints).qvel = (
self._random_state.uniform() * self._range + self._min)
self._set_actuator_controls(physics, normalized_ctrl,
scaled_actuator, standard_actuator)
self._assert_same_qfrc_actuator(
physics, self._scaled_actuator_joint, self._standard_actuator_joint)
def test_invalid_kwargs(self):
invalid_kwargs = dict(joint=self._scaled_actuator_joint, ctrllimited=False)
with self.assertRaisesWithLiteralMatch(
TypeError,
scaled_actuators._GOT_INVALID_KWARGS.format(sorted(invalid_kwargs))):
scaled_actuators.add_position_actuator(
target=self._scaled_actuator_joint,
qposrange=(self._min, self._max),
**invalid_kwargs)
def test_invalid_target(self):
invalid_target = self._mjcf_model.worldbody
with self.assertRaisesWithLiteralMatch(
TypeError,
scaled_actuators._GOT_INVALID_TARGET.format(invalid_target)):
scaled_actuators.add_position_actuator(
target=invalid_target, qposrange=(self._min, self._max))
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/locomotion/walkers/scaled_actuators_test.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""A quadruped "ant" walker."""
import os
from dm_control import composer
from dm_control import mjcf
from dm_control.composer.observation import observable
from dm_control.locomotion.walkers import base
from dm_control.locomotion.walkers import legacy_base
import numpy as np
_XML_DIRNAME = os.path.join(os.path.dirname(__file__), '../../third_party/ant')
_XML_FILENAME = 'ant.xml'
class Ant(legacy_base.Walker):
"""A quadruped "Ant" walker."""
def _build(self, name='walker', marker_rgba=None, initializer=None):
"""Build an Ant walker.
Args:
name: name of the walker.
marker_rgba: (Optional) color the ant's front legs with marker_rgba.
initializer: (Optional) A `WalkerInitializer` object.
"""
super()._build(initializer=initializer)
self._appendages_sensors = []
self._bodies_pos_sensors = []
self._bodies_quats_sensors = []
self._mjcf_root = mjcf.from_path(os.path.join(_XML_DIRNAME, _XML_FILENAME))
if name:
self._mjcf_root.model = name
# Set corresponding marker color if specified.
if marker_rgba is not None:
for geom in self.marker_geoms:
geom.set_attributes(rgba=marker_rgba)
# Initialize previous action.
self._prev_action = np.zeros(shape=self.action_spec.shape,
dtype=self.action_spec.dtype)
def initialize_episode(self, physics, random_state):
self._prev_action = np.zeros_like(self._prev_action)
def apply_action(self, physics, action, random_state):
super().apply_action(physics, action, random_state)
# Updates previous action.
self._prev_action[:] = action
def _build_observables(self):
return AntObservables(self)
@property
def mjcf_model(self):
return self._mjcf_root
@property
def upright_pose(self):
return base.WalkerPose()
@property
def marker_geoms(self):
return [self._mjcf_root.find('geom', 'front_left_leg_geom'),
self._mjcf_root.find('geom', 'front_right_leg_geom')]
@composer.cached_property
def actuators(self):
return self._mjcf_root.find_all('actuator')
@composer.cached_property
def root_body(self):
return self._mjcf_root.find('body', 'torso')
@composer.cached_property
def bodies(self):
return tuple(self.mjcf_model.find_all('body'))
@composer.cached_property
def mocap_tracking_bodies(self):
"""Collection of bodies for mocap tracking."""
return tuple(self.mjcf_model.find_all('body'))
@property
def mocap_joints(self):
return self.mjcf_model.find_all('joint')
@property
def _foot_bodies(self):
return (self._mjcf_root.find('body', 'front_left_foot'),
self._mjcf_root.find('body', 'front_right_foot'),
self._mjcf_root.find('body', 'back_right_foot'),
self._mjcf_root.find('body', 'back_left_foot'))
@composer.cached_property
def end_effectors(self):
return self._foot_bodies
@composer.cached_property
def observable_joints(self):
return [actuator.joint for actuator in self.actuators] # pylint: disable=not-an-iterable
@composer.cached_property
def egocentric_camera(self):
return self._mjcf_root.find('camera', 'egocentric')
def aliveness(self, physics):
return (physics.bind(self.root_body).xmat[-1] - 1.) / 2.
@composer.cached_property
def ground_contact_geoms(self):
foot_geoms = []
for foot in self._foot_bodies:
foot_geoms.extend(foot.find_all('geom'))
return tuple(foot_geoms)
@property
def prev_action(self):
return self._prev_action
@property
def appendages_sensors(self):
return self._appendages_sensors
@property
def bodies_pos_sensors(self):
return self._bodies_pos_sensors
@property
def bodies_quats_sensors(self):
return self._bodies_quats_sensors
class AntObservables(legacy_base.WalkerObservables):
"""Observables for the Ant."""
@composer.observable
def appendages_pos(self):
"""Equivalent to `end_effectors_pos` with the head's position appended."""
appendages = self._entity.end_effectors
self._entity.appendages_sensors[:] = []
for body in appendages:
self._entity.appendages_sensors.append(
self._entity.mjcf_model.sensor.add(
'framepos', name=body.name + '_appendage',
objtype='xbody', objname=body,
reftype='xbody', refname=self._entity.root_body))
def appendages_ego_pos(physics):
return np.reshape(
physics.bind(self._entity.appendages_sensors).sensordata, -1)
return observable.Generic(appendages_ego_pos)
@composer.observable
def bodies_quats(self):
"""Orientations of the bodies as quaternions, in the egocentric frame."""
bodies = self._entity.bodies
self._entity.bodies_quats_sensors[:] = []
for body in bodies:
self._entity.bodies_quats_sensors.append(
self._entity.mjcf_model.sensor.add(
'framequat', name=body.name + '_ego_body_quat',
objtype='xbody', objname=body,
reftype='xbody', refname=self._entity.root_body))
def bodies_ego_orientation(physics):
return np.reshape(
physics.bind(self._entity.bodies_quats_sensors).sensordata, -1)
return observable.Generic(bodies_ego_orientation)
@composer.observable
def bodies_pos(self):
"""Position of bodies relative to root, in the egocentric frame."""
bodies = self._entity.bodies
self._entity.bodies_pos_sensors[:] = []
for body in bodies:
self._entity.bodies_pos_sensors.append(
self._entity.mjcf_model.sensor.add(
'framepos', name=body.name + '_ego_body_pos',
objtype='xbody', objname=body,
reftype='xbody', refname=self._entity.root_body))
def bodies_ego_pos(physics):
return np.reshape(
physics.bind(self._entity.bodies_pos_sensors).sensordata, -1)
return observable.Generic(bodies_ego_pos)
@property
def proprioception(self):
return ([self.joints_pos, self.joints_vel,
self.body_height, self.end_effectors_pos,
self.appendages_pos, self.world_zaxis,
self.bodies_quats, self.bodies_pos] +
self._collect_from_attachments('proprioception'))
| dm_control-main | dm_control/locomotion/walkers/ant.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Walkers for Locomotion tasks."""
from dm_control.locomotion.walkers.ant import Ant
from dm_control.locomotion.walkers.cmu_humanoid import CMUHumanoidPositionControlled
from dm_control.locomotion.walkers.cmu_humanoid import CMUHumanoidPositionControlledV2020
# Import removed.
from dm_control.locomotion.walkers.jumping_ball import JumpingBallWithHead
from dm_control.locomotion.walkers.jumping_ball import RollingBallWithHead
from dm_control.locomotion.walkers.rodent import Rat
| dm_control-main | dm_control/locomotion/walkers/__init__.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Position & velocity actuators whose controls are scaled to a given range."""
_DISALLOWED_KWARGS = frozenset(
['biastype', 'gainprm', 'biasprm', 'ctrllimited',
'joint', 'tendon', 'site', 'slidersite', 'cranksite'])
_ALLOWED_TAGS = frozenset(['joint', 'tendon', 'site'])
_GOT_INVALID_KWARGS = 'Received invalid keyword argument(s): {}'
_GOT_INVALID_TARGET = '`target` tag type should be one of {}: got {{}}'.format(
sorted(_ALLOWED_TAGS))
def _check_target_and_kwargs(target, **kwargs):
invalid_kwargs = _DISALLOWED_KWARGS.intersection(kwargs)
if invalid_kwargs:
raise TypeError(_GOT_INVALID_KWARGS.format(sorted(invalid_kwargs)))
if target.tag not in _ALLOWED_TAGS:
raise TypeError(_GOT_INVALID_TARGET.format(target))
def add_position_actuator(target, qposrange, ctrlrange=(-1, 1),
kp=1.0, **kwargs):
"""Adds a scaled position actuator that is bound to the specified element.
This is equivalent to MuJoCo's built-in `<position>` actuator where an affine
transformation is pre-applied to the control signal, such that the minimum
control value corresponds to the minimum desired position, and the
maximum control value corresponds to the maximum desired position.
Args:
target: A PyMJCF joint, tendon, or site element object that is to be
controlled.
qposrange: A sequence of two numbers specifying the allowed range of target
position.
ctrlrange: A sequence of two numbers specifying the allowed range of
this actuator's control signal.
kp: The gain parameter of this position actuator.
**kwargs: Additional MJCF attributes for this actuator element.
The following attributes are disallowed: `['biastype', 'gainprm',
'biasprm', 'ctrllimited', 'joint', 'tendon', 'site',
'slidersite', 'cranksite']`.
Returns:
A PyMJCF actuator element that has been added to the MJCF model containing
the specified `target`.
Raises:
TypeError: `kwargs` contains an unrecognized or disallowed MJCF attribute,
or `target` is not an allowed MJCF element type.
"""
_check_target_and_kwargs(target, **kwargs)
kwargs[target.tag] = target
slope = (qposrange[1] - qposrange[0]) / (ctrlrange[1] - ctrlrange[0])
g0 = kp * slope
b0 = kp * (qposrange[0] - slope * ctrlrange[0])
b1 = -kp
b2 = 0
return target.root.actuator.add('general',
biastype='affine',
gainprm=[g0],
biasprm=[b0, b1, b2],
ctrllimited=True,
ctrlrange=ctrlrange,
**kwargs)
def add_velocity_actuator(target, qvelrange, ctrlrange=(-1, 1),
kv=1.0, **kwargs):
"""Adds a scaled velocity actuator that is bound to the specified element.
This is equivalent to MuJoCo's built-in `<velocity>` actuator where an affine
transformation is pre-applied to the control signal, such that the minimum
control value corresponds to the minimum desired velocity, and the
maximum control value corresponds to the maximum desired velocity.
Args:
target: A PyMJCF joint, tendon, or site element object that is to be
controlled.
qvelrange: A sequence of two numbers specifying the allowed range of target
velocity.
ctrlrange: A sequence of two numbers specifying the allowed range of
this actuator's control signal.
kv: The gain parameter of this velocity actuator.
**kwargs: Additional MJCF attributes for this actuator element.
The following attributes are disallowed: `['biastype', 'gainprm',
'biasprm', 'ctrllimited', 'joint', 'tendon', 'site',
'slidersite', 'cranksite']`.
Returns:
A PyMJCF actuator element that has been added to the MJCF model containing
the specified `target`.
Raises:
TypeError: `kwargs` contains an unrecognized or disallowed MJCF attribute,
or `target` is not an allowed MJCF element type.
"""
_check_target_and_kwargs(target, **kwargs)
kwargs[target.tag] = target
slope = (qvelrange[1] - qvelrange[0]) / (ctrlrange[1] - ctrlrange[0])
g0 = kv * slope
b0 = kv * (qvelrange[0] - slope * ctrlrange[0])
b1 = 0
b2 = -kv
return target.root.actuator.add('general',
biastype='affine',
gainprm=[g0],
biasprm=[b0, b1, b2],
ctrllimited=True,
ctrlrange=ctrlrange,
**kwargs)
| dm_control-main | dm_control/locomotion/walkers/scaled_actuators.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Walkers based on an actuated jumping ball."""
import os
from dm_control import composer
from dm_control import mjcf
from dm_control.locomotion.walkers import legacy_base
import numpy as np
_ASSETS_PATH = os.path.join(os.path.dirname(__file__),
'assets/jumping_ball')
class JumpingBallWithHead(legacy_base.Walker):
"""A rollable and jumpable ball with a head."""
def _build(self, name='walker', marker_rgba=None, camera_control=False,
initializer=None, add_ears=False, camera_height=None):
"""Build a JumpingBallWithHead.
Args:
name: name of the walker.
marker_rgba: RGBA value set to walker.marker_geoms to distinguish between
walkers (in multi-agent setting).
camera_control: If `True`, the walker exposes two additional actuated
degrees of freedom to control the egocentric camera height and tilt.
initializer: (Optional) A `WalkerInitializer` object.
add_ears: a boolean. Same as the nose above but the red/blue balls are
placed to the left/right of the agent. Better for egocentric vision.
camera_height: A float specifying the height of the camera, or `None` if
the camera height should be left as specified in the XML model.
"""
super()._build(initializer=initializer)
self._mjcf_root = self._mjcf_root = mjcf.from_path(self._xml_path)
if name:
self._mjcf_root.model = name
if camera_height is not None:
self._mjcf_root.find('body', 'egocentric_camera').pos[2] = camera_height
if add_ears:
# Large ears
head = self._mjcf_root.find('body', 'head_body')
head.add('site', type='sphere', size=(.26,),
pos=(.22, 0, 0),
rgba=(.7, 0, 0, 1))
head.add('site', type='sphere', size=(.26,),
pos=(-.22, 0, 0),
rgba=(0, 0, .7, 1))
# Set corresponding marker color if specified.
if marker_rgba is not None:
for geom in self.marker_geoms:
geom.set_attributes(rgba=marker_rgba)
self._root_joints = None
self._camera_control = camera_control
if not camera_control:
for name in ('camera_height', 'camera_tilt'):
self._mjcf_root.find('actuator', name).remove()
self._mjcf_root.find('joint', name).remove()
@property
def _xml_path(self):
return os.path.join(_ASSETS_PATH, 'jumping_ball_with_head.xml')
@property
def marker_geoms(self):
return [self._mjcf_root.find('geom', 'head')]
def create_root_joints(self, attachment_frame):
root_class = self._mjcf_root.find('default', 'root')
root_x = attachment_frame.add(
'joint', name='root_x', type='slide', axis=[1, 0, 0], dclass=root_class)
root_y = attachment_frame.add(
'joint', name='root_y', type='slide', axis=[0, 1, 0], dclass=root_class)
root_z = attachment_frame.add(
'joint', name='root_z', type='slide', axis=[0, 0, 1], dclass=root_class)
self._root_joints = [root_x, root_y, root_z]
def set_pose(self, physics, position=None, quaternion=None):
if position is not None:
if self._root_joints is not None:
physics.bind(self._root_joints).qpos = position
else:
super().set_pose(physics, position, quaternion=None)
physics.bind(self._mjcf_root.find_all('joint')).qpos = 0.
if quaternion is not None:
# This walker can only rotate along the z-axis, so we extract only that
# component from the quaternion.
z_angle = np.arctan2(
2 * (quaternion[0] * quaternion[3] + quaternion[1] * quaternion[2]),
1 - 2 * (quaternion[2] ** 2 + quaternion[3] ** 2))
physics.bind(self._mjcf_root.find('joint', 'steer')).qpos = z_angle
def initialize_episode(self, physics, unused_random_state):
# gravity compensation
if self._camera_control:
gravity = np.hstack([physics.model.opt.gravity, [0, 0, 0]])
comp_bodies = physics.bind(self._mjcf_root.find('body',
'egocentric_camera'))
comp_bodies.xfrc_applied = -gravity * comp_bodies.mass[..., None]
@property
def mjcf_model(self):
return self._mjcf_root
@composer.cached_property
def actuators(self):
return self._mjcf_root.find_all('actuator')
@composer.cached_property
def root_body(self):
return self._mjcf_root.find('body', 'head_body')
@composer.cached_property
def end_effectors(self):
return [self._mjcf_root.find('body', 'head_body')]
@composer.cached_property
def observable_joints(self):
return [self._mjcf_root.find('joint', 'kick')]
@composer.cached_property
def egocentric_camera(self):
return self._mjcf_root.find('camera', 'egocentric')
@composer.cached_property
def ground_contact_geoms(self):
return (self._mjcf_root.find('geom', 'shell'),)
class RollingBallWithHead(JumpingBallWithHead):
"""A rollable ball with a head."""
def _build(self, **kwargs):
super()._build(**kwargs)
self._mjcf_root.find('actuator', 'kick').remove()
self._mjcf_root.find('joint', 'kick').remove()
@composer.cached_property
def observable_joints(self):
return []
| dm_control-main | dm_control/locomotion/walkers/jumping_ball.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for the Jumping Ball."""
from absl.testing import absltest
from absl.testing import parameterized
from dm_control import composer
from dm_control import mjcf
from dm_control.composer.observation.observable import base as observable_base
from dm_control.locomotion.arenas import corridors as corr_arenas
from dm_control.locomotion.tasks import corridors as corr_tasks
from dm_control.locomotion.walkers import jumping_ball
import numpy as np
_CONTROL_TIMESTEP = .02
_PHYSICS_TIMESTEP = 0.005
def _get_jumping_ball_corridor_physics():
walker = jumping_ball.JumpingBallWithHead()
arena = corr_arenas.EmptyCorridor()
task = corr_tasks.RunThroughCorridor(
walker=walker,
arena=arena,
walker_spawn_position=(5, 0, 0),
walker_spawn_rotation=0,
physics_timestep=_PHYSICS_TIMESTEP,
control_timestep=_CONTROL_TIMESTEP)
env = composer.Environment(
time_limit=30,
task=task,
strip_singleton_obs_buffer_dim=True)
return walker, env
class JumpingBallWithHeadTest(parameterized.TestCase):
def test_can_compile_and_step_simulation(self):
_, env = _get_jumping_ball_corridor_physics()
physics = env.physics
for _ in range(100):
physics.step()
@parameterized.parameters([
'egocentric_camera',
])
def test_get_element_property(self, name):
attribute_value = getattr(jumping_ball.JumpingBallWithHead(), name)
self.assertIsInstance(attribute_value, mjcf.Element)
@parameterized.parameters([
'actuators',
'end_effectors',
'observable_joints',
])
def test_get_element_tuple_property(self, name):
attribute_value = getattr(jumping_ball.JumpingBallWithHead(), name)
self.assertNotEmpty(attribute_value)
for item in attribute_value:
self.assertIsInstance(item, mjcf.Element)
def test_set_name(self):
name = 'fred'
walker = jumping_ball.JumpingBallWithHead(name=name)
self.assertEqual(walker.mjcf_model.model, name)
@parameterized.parameters(
'sensors_velocimeter',
'world_zaxis',
)
def test_evaluate_observable(self, name):
walker, env = _get_jumping_ball_corridor_physics()
physics = env.physics
observable = getattr(walker.observables, name)
observation = observable(physics)
self.assertIsInstance(observation, (float, np.ndarray))
def test_proprioception(self):
walker = jumping_ball.JumpingBallWithHead()
for item in walker.observables.proprioception:
self.assertIsInstance(item, observable_base.Observable)
@parameterized.parameters(
dict(camera_control=True, add_ears=True, camera_height=1.),
dict(camera_control=True, add_ears=False, camera_height=1.),
dict(camera_control=False, add_ears=True, camera_height=1.),
dict(camera_control=False, add_ears=False, camera_height=1.),
dict(camera_control=True, add_ears=True, camera_height=None),
dict(camera_control=True, add_ears=False, camera_height=None),
dict(camera_control=False, add_ears=True, camera_height=None),
dict(camera_control=False, add_ears=False, camera_height=None),
)
def test_instantiation(self, camera_control, add_ears, camera_height):
jumping_ball.JumpingBallWithHead(camera_control=camera_control,
add_ears=add_ears,
camera_height=camera_height)
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/locomotion/walkers/jumping_ball_test.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""A Rodent walker."""
import os
import re
from dm_control import composer
from dm_control import mjcf
from dm_control.composer.observation import observable
from dm_control.locomotion.walkers import base
from dm_control.locomotion.walkers import legacy_base
from dm_control.mujoco import wrapper as mj_wrapper
import numpy as np
_XML_PATH = os.path.join(os.path.dirname(__file__),
'assets/rodent.xml')
_RAT_MOCAP_JOINTS = [
'vertebra_1_extend', 'vertebra_2_bend', 'vertebra_3_twist',
'vertebra_4_extend', 'vertebra_5_bend', 'vertebra_6_twist',
'hip_L_supinate', 'hip_L_abduct', 'hip_L_extend', 'knee_L', 'ankle_L',
'toe_L', 'hip_R_supinate', 'hip_R_abduct', 'hip_R_extend', 'knee_R',
'ankle_R', 'toe_R', 'vertebra_C1_extend', 'vertebra_C1_bend',
'vertebra_C2_extend', 'vertebra_C2_bend', 'vertebra_C3_extend',
'vertebra_C3_bend', 'vertebra_C4_extend', 'vertebra_C4_bend',
'vertebra_C5_extend', 'vertebra_C5_bend', 'vertebra_C6_extend',
'vertebra_C6_bend', 'vertebra_C7_extend', 'vertebra_C9_bend',
'vertebra_C11_extend', 'vertebra_C13_bend', 'vertebra_C15_extend',
'vertebra_C17_bend', 'vertebra_C19_extend', 'vertebra_C21_bend',
'vertebra_C23_extend', 'vertebra_C25_bend', 'vertebra_C27_extend',
'vertebra_C29_bend', 'vertebra_cervical_5_extend',
'vertebra_cervical_4_bend', 'vertebra_cervical_3_twist',
'vertebra_cervical_2_extend', 'vertebra_cervical_1_bend',
'vertebra_axis_twist', 'vertebra_atlant_extend', 'atlas', 'mandible',
'scapula_L_supinate', 'scapula_L_abduct', 'scapula_L_extend', 'shoulder_L',
'shoulder_sup_L', 'elbow_L', 'wrist_L', 'finger_L', 'scapula_R_supinate',
'scapula_R_abduct', 'scapula_R_extend', 'shoulder_R', 'shoulder_sup_R',
'elbow_R', 'wrist_R', 'finger_R'
]
_UPRIGHT_POS = (0.0, 0.0, 0.0)
_UPRIGHT_QUAT = (1., 0., 0., 0.)
_TORQUE_THRESHOLD = 60
class Rat(legacy_base.Walker):
"""A position-controlled rat with control range scaled to [-1, 1]."""
def _build(self,
params=None,
name='walker',
torque_actuators=False,
foot_mods=False,
initializer=None):
self.params = params
self._mjcf_root = mjcf.from_path(_XML_PATH)
if name:
self._mjcf_root.model = name
self.body_sites = []
super()._build(initializer=initializer)
# modify actuators
if torque_actuators:
for actuator in self._mjcf_root.find_all('actuator'):
actuator.gainprm = [actuator.forcerange[1]]
del actuator.biastype
del actuator.biasprm
# modify ankle and toe limits
if foot_mods:
self._mjcf_root.find('default', 'ankle').joint.range = [-0.1, 2.]
self._mjcf_root.find('default', 'toe').joint.range = [-0.7, 0.87]
@property
def upright_pose(self):
"""Reset pose to upright position."""
return base.WalkerPose(xpos=_UPRIGHT_POS, xquat=_UPRIGHT_QUAT)
@property
def mjcf_model(self):
"""Return the model root."""
return self._mjcf_root
@composer.cached_property
def actuators(self):
"""Return all actuators."""
return tuple(self._mjcf_root.find_all('actuator'))
@composer.cached_property
def root_body(self):
"""Return the body."""
return self._mjcf_root.find('body', 'torso')
@composer.cached_property
def pelvis_body(self):
"""Return the body."""
return self._mjcf_root.find('body', 'pelvis')
@composer.cached_property
def head(self):
"""Return the head."""
return self._mjcf_root.find('body', 'skull')
@composer.cached_property
def left_arm_root(self):
"""Return the left arm."""
return self._mjcf_root.find('body', 'scapula_L')
@composer.cached_property
def right_arm_root(self):
"""Return the right arm."""
return self._mjcf_root.find('body', 'scapula_R')
@composer.cached_property
def ground_contact_geoms(self):
"""Return ground contact geoms."""
return tuple(
self._mjcf_root.find('body', 'foot_L').find_all('geom') +
self._mjcf_root.find('body', 'foot_R').find_all('geom') +
self._mjcf_root.find('body', 'hand_L').find_all('geom') +
self._mjcf_root.find('body', 'hand_R').find_all('geom') +
self._mjcf_root.find('body', 'vertebra_C1').find_all('geom')
)
@composer.cached_property
def standing_height(self):
"""Return standing height."""
return self.params['_STAND_HEIGHT']
@composer.cached_property
def end_effectors(self):
"""Return end effectors."""
return (self._mjcf_root.find('body', 'lower_arm_R'),
self._mjcf_root.find('body', 'lower_arm_L'),
self._mjcf_root.find('body', 'foot_R'),
self._mjcf_root.find('body', 'foot_L'))
@composer.cached_property
def observable_joints(self):
"""Return observable joints."""
return tuple(actuator.joint
for actuator in self.actuators # This lint is mistaken; pylint: disable=not-an-iterable
if actuator.joint is not None)
@composer.cached_property
def observable_tendons(self):
return self._mjcf_root.find_all('tendon')
@composer.cached_property
def mocap_joints(self):
return tuple(
self._mjcf_root.find('joint', name) for name in _RAT_MOCAP_JOINTS)
@composer.cached_property
def mocap_joint_order(self):
return tuple([jnt.name for jnt in self.mocap_joints]) # This lint is mistaken; pylint: disable=not-an-iterable
@composer.cached_property
def bodies(self):
"""Return all bodies."""
return tuple(self._mjcf_root.find_all('body'))
@composer.cached_property
def mocap_tracking_bodies(self):
"""Return bodies for mocap comparison."""
return tuple(body for body in self._mjcf_root.find_all('body')
if not re.match(r'(vertebra|hand|toe)', body.name))
@composer.cached_property
def primary_joints(self):
"""Return primary (non-vertebra) joints."""
return tuple(jnt for jnt in self._mjcf_root.find_all('joint')
if 'vertebra' not in jnt.name)
@composer.cached_property
def vertebra_joints(self):
"""Return vertebra joints."""
return tuple(jnt for jnt in self._mjcf_root.find_all('joint')
if 'vertebra' in jnt.name)
@composer.cached_property
def primary_joint_order(self):
joint_names = self.mocap_joint_order
primary_names = tuple([jnt.name for jnt in self.primary_joints]) # pylint: disable=not-an-iterable
primary_order = []
for nm in primary_names:
primary_order.append(joint_names.index(nm))
return primary_order
@composer.cached_property
def vertebra_joint_order(self):
joint_names = self.mocap_joint_order
vertebra_names = tuple([jnt.name for jnt in self.vertebra_joints]) # pylint: disable=not-an-iterable
vertebra_order = []
for nm in vertebra_names:
vertebra_order.append(joint_names.index(nm))
return vertebra_order
@composer.cached_property
def egocentric_camera(self):
"""Return the egocentric camera."""
return self._mjcf_root.find('camera', 'egocentric')
@property
def _xml_path(self):
"""Return the path to th model .xml file."""
return self.params['_XML_PATH']
@composer.cached_property
def joint_actuators(self):
"""Return all joint actuators."""
return tuple([act for act in self._mjcf_root.find_all('actuator')
if act.joint])
@composer.cached_property
def joint_actuators_range(self):
act_joint_range = []
for act in self.joint_actuators: # This lint is mistaken; pylint: disable=not-an-iterable
associated_joint = self._mjcf_root.find('joint', act.name)
act_range = associated_joint.dclass.joint.range
act_joint_range.append(act_range)
return act_joint_range
def pose_to_actuation(self, pose):
# holds for joint actuators, find desired torque = 0
# u_ref = [2 q_ref - (r_low + r_up) ]/(r_up - r_low)
r_lower = np.array([ajr[0] for ajr in self.joint_actuators_range]) # This lint is mistaken; pylint: disable=not-an-iterable
r_upper = np.array([ajr[1] for ajr in self.joint_actuators_range]) # This lint is mistaken; pylint: disable=not-an-iterable
num_tendon_actuators = len(self.actuators) - len(self.joint_actuators)
tendon_actions = np.zeros(num_tendon_actuators)
return np.hstack([tendon_actions, (2*pose[self.joint_actuator_order]-
(r_lower+r_upper))/(r_upper-r_lower)])
@composer.cached_property
def joint_actuator_order(self):
joint_names = self.mocap_joint_order
joint_actuator_names = tuple([act.name for act in self.joint_actuators]) # This lint is mistaken; pylint: disable=not-an-iterable
actuator_order = []
for nm in joint_actuator_names:
actuator_order.append(joint_names.index(nm))
return actuator_order
def _build_observables(self):
return RodentObservables(self)
class RodentObservables(legacy_base.WalkerObservables):
"""Observables for the Rat."""
@composer.observable
def head_height(self):
"""Observe the head height."""
return observable.MJCFFeature('xpos', self._entity.head)[2]
@composer.observable
def sensors_torque(self):
"""Observe the torque sensors."""
return observable.MJCFFeature(
'sensordata',
self._entity.mjcf_model.sensor.torque,
corruptor=lambda v, random_state: np.tanh(2 * v / _TORQUE_THRESHOLD)
)
@composer.observable
def tendons_pos(self):
return observable.MJCFFeature('length', self._entity.observable_tendons)
@composer.observable
def tendons_vel(self):
return observable.MJCFFeature('velocity', self._entity.observable_tendons)
@composer.observable
def actuator_activation(self):
"""Observe the actuator activation."""
model = self._entity.mjcf_model
return observable.MJCFFeature('act', model.find_all('actuator'))
@composer.observable
def appendages_pos(self):
"""Equivalent to `end_effectors_pos` with head's position appended."""
def relative_pos_in_egocentric_frame(physics):
end_effectors_with_head = (
self._entity.end_effectors + (self._entity.head,))
end_effector = physics.bind(end_effectors_with_head).xpos
torso = physics.bind(self._entity.root_body).xpos
xmat = \
np.reshape(physics.bind(self._entity.root_body).xmat, (3, 3))
return np.reshape(np.dot(end_effector - torso, xmat), -1)
return observable.Generic(relative_pos_in_egocentric_frame)
@property
def proprioception(self):
"""Return proprioceptive information."""
return [
self.joints_pos, self.joints_vel,
self.tendons_pos, self.tendons_vel,
self.actuator_activation,
self.body_height, self.end_effectors_pos, self.appendages_pos,
self.world_zaxis
] + self._collect_from_attachments('proprioception')
@composer.observable
def egocentric_camera(self):
"""Observable of the egocentric camera."""
if not hasattr(self, '_scene_options'):
# Don't render this walker's geoms.
self._scene_options = mj_wrapper.MjvOption()
collision_geom_group = 2
self._scene_options.geomgroup[collision_geom_group] = 0
cosmetic_geom_group = 1
self._scene_options.geomgroup[cosmetic_geom_group] = 0
return observable.MJCFCamera(self._entity.egocentric_camera,
width=64, height=64,
scene_option=self._scene_options
)
| dm_control-main | dm_control/locomotion/walkers/rodent.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""A CMU humanoid walker."""
import abc
import collections
import os
from dm_control import composer
from dm_control import mjcf
from dm_control.composer.observation import observable
from dm_control.locomotion.walkers import base
from dm_control.locomotion.walkers import legacy_base
from dm_control.locomotion.walkers import rescale
from dm_control.locomotion.walkers import scaled_actuators
from dm_control.mujoco import wrapper as mj_wrapper
import numpy as np
_XML_PATH = os.path.join(os.path.dirname(__file__),
'assets/humanoid_CMU_V{model_version}.xml')
_WALKER_GEOM_GROUP = 2
_WALKER_INVIS_GROUP = 1
_CMU_MOCAP_JOINTS = (
'lfemurrz', 'lfemurry', 'lfemurrx', 'ltibiarx', 'lfootrz', 'lfootrx',
'ltoesrx', 'rfemurrz', 'rfemurry', 'rfemurrx', 'rtibiarx', 'rfootrz',
'rfootrx', 'rtoesrx', 'lowerbackrz', 'lowerbackry', 'lowerbackrx',
'upperbackrz', 'upperbackry', 'upperbackrx', 'thoraxrz', 'thoraxry',
'thoraxrx', 'lowerneckrz', 'lowerneckry', 'lowerneckrx', 'upperneckrz',
'upperneckry', 'upperneckrx', 'headrz', 'headry', 'headrx', 'lclaviclerz',
'lclaviclery', 'lhumerusrz', 'lhumerusry', 'lhumerusrx', 'lradiusrx',
'lwristry', 'lhandrz', 'lhandrx', 'lfingersrx', 'lthumbrz', 'lthumbrx',
'rclaviclerz', 'rclaviclery', 'rhumerusrz', 'rhumerusry', 'rhumerusrx',
'rradiusrx', 'rwristry', 'rhandrz', 'rhandrx', 'rfingersrx', 'rthumbrz',
'rthumbrx')
# pylint: disable=bad-whitespace
PositionActuatorParams = collections.namedtuple(
'PositionActuatorParams', ['name', 'forcerange', 'kp'])
_POSITION_ACTUATORS = [
PositionActuatorParams('headrx', [-20, 20 ], 20 ),
PositionActuatorParams('headry', [-20, 20 ], 20 ),
PositionActuatorParams('headrz', [-20, 20 ], 20 ),
PositionActuatorParams('lclaviclery', [-20, 20 ], 20 ),
PositionActuatorParams('lclaviclerz', [-20, 20 ], 20 ),
PositionActuatorParams('lfemurrx', [-120, 120], 120),
PositionActuatorParams('lfemurry', [-80, 80 ], 80 ),
PositionActuatorParams('lfemurrz', [-80, 80 ], 80 ),
PositionActuatorParams('lfingersrx', [-20, 20 ], 20 ),
PositionActuatorParams('lfootrx', [-50, 50 ], 50 ),
PositionActuatorParams('lfootrz', [-50, 50 ], 50 ),
PositionActuatorParams('lhandrx', [-20, 20 ], 20 ),
PositionActuatorParams('lhandrz', [-20, 20 ], 20 ),
PositionActuatorParams('lhumerusrx', [-60, 60 ], 60 ),
PositionActuatorParams('lhumerusry', [-60, 60 ], 60 ),
PositionActuatorParams('lhumerusrz', [-60, 60 ], 60 ),
PositionActuatorParams('lowerbackrx', [-120, 120], 150),
PositionActuatorParams('lowerbackry', [-120, 120], 150),
PositionActuatorParams('lowerbackrz', [-120, 120], 150),
PositionActuatorParams('lowerneckrx', [-20, 20 ], 20 ),
PositionActuatorParams('lowerneckry', [-20, 20 ], 20 ),
PositionActuatorParams('lowerneckrz', [-20, 20 ], 20 ),
PositionActuatorParams('lradiusrx', [-60, 60 ], 60 ),
PositionActuatorParams('lthumbrx', [-20, 20 ], 20) ,
PositionActuatorParams('lthumbrz', [-20, 20 ], 20 ),
PositionActuatorParams('ltibiarx', [-80, 80 ], 80 ),
PositionActuatorParams('ltoesrx', [-20, 20 ], 20 ),
PositionActuatorParams('lwristry', [-20, 20 ], 20 ),
PositionActuatorParams('rclaviclery', [-20, 20 ], 20 ),
PositionActuatorParams('rclaviclerz', [-20, 20 ], 20 ),
PositionActuatorParams('rfemurrx', [-120, 120], 120),
PositionActuatorParams('rfemurry', [-80, 80 ], 80 ),
PositionActuatorParams('rfemurrz', [-80, 80 ], 80 ),
PositionActuatorParams('rfingersrx', [-20, 20 ], 20 ),
PositionActuatorParams('rfootrx', [-50, 50 ], 50 ),
PositionActuatorParams('rfootrz', [-50, 50 ], 50 ),
PositionActuatorParams('rhandrx', [-20, 20 ], 20 ),
PositionActuatorParams('rhandrz', [-20, 20 ], 20 ),
PositionActuatorParams('rhumerusrx', [-60, 60 ], 60 ),
PositionActuatorParams('rhumerusry', [-60, 60 ], 60 ),
PositionActuatorParams('rhumerusrz', [-60, 60 ], 60 ),
PositionActuatorParams('rradiusrx', [-60, 60 ], 60 ),
PositionActuatorParams('rthumbrx', [-20, 20 ], 20 ),
PositionActuatorParams('rthumbrz', [-20, 20 ], 20 ),
PositionActuatorParams('rtibiarx', [-80, 80 ], 80 ),
PositionActuatorParams('rtoesrx', [-20, 20 ], 20 ),
PositionActuatorParams('rwristry', [-20, 20 ], 20 ),
PositionActuatorParams('thoraxrx', [-80, 80 ], 100),
PositionActuatorParams('thoraxry', [-80, 80 ], 100),
PositionActuatorParams('thoraxrz', [-80, 80 ], 100),
PositionActuatorParams('upperbackrx', [-80, 80 ], 80 ),
PositionActuatorParams('upperbackry', [-80, 80 ], 80 ),
PositionActuatorParams('upperbackrz', [-80, 80 ], 80 ),
PositionActuatorParams('upperneckrx', [-20, 20 ], 20 ),
PositionActuatorParams('upperneckry', [-20, 20 ], 20 ),
PositionActuatorParams('upperneckrz', [-20, 20 ], 20 ),
]
PositionActuatorParamsV2020 = collections.namedtuple(
'PositionActuatorParams', ['name', 'forcerange', 'kp', 'damping'])
_POSITION_ACTUATORS_V2020 = [
PositionActuatorParamsV2020('headrx', [-40, 40 ], 40 , 2 ),
PositionActuatorParamsV2020('headry', [-40, 40 ], 40 , 2 ),
PositionActuatorParamsV2020('headrz', [-40, 40 ], 40 , 2 ),
PositionActuatorParamsV2020('lclaviclery', [-80, 80 ], 80 , 20),
PositionActuatorParamsV2020('lclaviclerz', [-80, 80 ], 80 , 20),
PositionActuatorParamsV2020('lfemurrx', [-300, 300], 300, 15),
PositionActuatorParamsV2020('lfemurry', [-200, 200], 200, 10),
PositionActuatorParamsV2020('lfemurrz', [-200, 200], 200, 10),
PositionActuatorParamsV2020('lfingersrx', [-20, 20 ], 20 , 1 ),
PositionActuatorParamsV2020('lfootrx', [-120, 120], 120, 6 ),
PositionActuatorParamsV2020('lfootrz', [-50, 50 ], 50 , 3 ),
PositionActuatorParamsV2020('lhandrx', [-20, 20 ], 20 , 1 ),
PositionActuatorParamsV2020('lhandrz', [-20, 20 ], 20 , 1 ),
PositionActuatorParamsV2020('lhumerusrx', [-120, 120], 120, 6 ),
PositionActuatorParamsV2020('lhumerusry', [-120, 120], 120, 6 ),
PositionActuatorParamsV2020('lhumerusrz', [-120, 120], 120, 6 ),
PositionActuatorParamsV2020('lowerbackrx', [-300, 300], 300, 15),
PositionActuatorParamsV2020('lowerbackry', [-180, 180], 180, 20),
PositionActuatorParamsV2020('lowerbackrz', [-200, 200], 200, 20),
PositionActuatorParamsV2020('lowerneckrx', [-120, 120 ],120, 20),
PositionActuatorParamsV2020('lowerneckry', [-120, 120 ],120, 20),
PositionActuatorParamsV2020('lowerneckrz', [-120, 120 ],120, 20),
PositionActuatorParamsV2020('lradiusrx', [-90, 90 ], 90 , 5 ),
PositionActuatorParamsV2020('lthumbrx', [-20, 20 ], 20 , 1 ),
PositionActuatorParamsV2020('lthumbrz', [-20, 20 ], 20 , 1 ),
PositionActuatorParamsV2020('ltibiarx', [-160, 160], 160, 8 ),
PositionActuatorParamsV2020('ltoesrx', [-20, 20 ], 20 , 1 ),
PositionActuatorParamsV2020('lwristry', [-20, 20 ], 20 , 1 ),
PositionActuatorParamsV2020('rclaviclery', [-80, 80 ], 80 , 20),
PositionActuatorParamsV2020('rclaviclerz', [-80, 80 ], 80 , 20),
PositionActuatorParamsV2020('rfemurrx', [-300, 300], 300, 15),
PositionActuatorParamsV2020('rfemurry', [-200, 200], 200, 10),
PositionActuatorParamsV2020('rfemurrz', [-200, 200], 200, 10),
PositionActuatorParamsV2020('rfingersrx', [-20, 20 ], 20 , 1 ),
PositionActuatorParamsV2020('rfootrx', [-120, 120], 120, 6 ),
PositionActuatorParamsV2020('rfootrz', [-50, 50 ], 50 , 3 ),
PositionActuatorParamsV2020('rhandrx', [-20, 20 ], 20 , 1 ),
PositionActuatorParamsV2020('rhandrz', [-20, 20 ], 20 , 1 ),
PositionActuatorParamsV2020('rhumerusrx', [-120, 120], 120, 6 ),
PositionActuatorParamsV2020('rhumerusry', [-120, 120], 120, 6 ),
PositionActuatorParamsV2020('rhumerusrz', [-120, 120], 120, 6 ),
PositionActuatorParamsV2020('rradiusrx', [-90, 90 ], 90 , 5 ),
PositionActuatorParamsV2020('rthumbrx', [-20, 20 ], 20 , 1 ),
PositionActuatorParamsV2020('rthumbrz', [-20, 20 ], 20 , 1 ),
PositionActuatorParamsV2020('rtibiarx', [-160, 160], 160, 8 ),
PositionActuatorParamsV2020('rtoesrx', [-20, 20 ], 20 , 1 ),
PositionActuatorParamsV2020('rwristry', [-20, 20 ], 20 , 1 ),
PositionActuatorParamsV2020('thoraxrx', [-300, 300], 300, 15),
PositionActuatorParamsV2020('thoraxry', [-80, 80], 80 , 8 ),
PositionActuatorParamsV2020('thoraxrz', [-200, 200], 200, 12),
PositionActuatorParamsV2020('upperbackrx', [-300, 300], 300, 15),
PositionActuatorParamsV2020('upperbackry', [-80, 80], 80 , 8 ),
PositionActuatorParamsV2020('upperbackrz', [-200, 200], 200, 12),
PositionActuatorParamsV2020('upperneckrx', [-60, 60 ], 60 , 10),
PositionActuatorParamsV2020('upperneckry', [-60, 60 ], 60 , 10),
PositionActuatorParamsV2020('upperneckrz', [-60, 60 ], 60 , 10),
]
# pylint: enable=bad-whitespace
_UPRIGHT_POS = (0.0, 0.0, 0.94)
_UPRIGHT_POS_V2020 = (0.0, 0.0, 1.143)
_UPRIGHT_QUAT = (0.859, 1.0, 1.0, 0.859)
# Height of head above which the humanoid is considered standing.
_STAND_HEIGHT = 1.5
_TORQUE_THRESHOLD = 60
class _CMUHumanoidBase(legacy_base.Walker, metaclass=abc.ABCMeta):
"""The abstract base class for walkers compatible with the CMU humanoid."""
def _build(self,
name='walker',
marker_rgba=None,
include_face=False,
initializer=None):
self._mjcf_root = mjcf.from_path(self._xml_path)
if name:
self._mjcf_root.model = name
# Set corresponding marker color if specified.
if marker_rgba is not None:
for geom in self.marker_geoms:
geom.set_attributes(rgba=marker_rgba)
self._actuator_order = np.argsort(_CMU_MOCAP_JOINTS)
self._inverse_order = np.argsort(self._actuator_order)
super()._build(initializer=initializer)
if include_face:
head = self._mjcf_root.find('body', 'head')
head.add(
'geom',
type='capsule',
name='face',
size=(0.065, 0.014),
pos=(0.000341465, 0.048184, 0.01),
quat=(0.717887, 0.696142, -0.00493334, 0),
mass=0.,
contype=0,
conaffinity=0)
face_forwardness = head.pos[1]-.02
head_geom = self._mjcf_root.find('geom', 'head')
nose_size = head_geom.size[0] / 4.75
face = head.add(
'body', name='face', pos=(0.0, 0.039, face_forwardness))
face.add('geom',
type='capsule',
name='nose',
size=(nose_size, 0.01),
pos=(0.0, 0.0, 0.0),
quat=(1, 0.7, 0, 0),
mass=0.,
contype=0,
conaffinity=0,
group=_WALKER_INVIS_GROUP)
def _build_observables(self):
return CMUHumanoidObservables(self)
@property
@abc.abstractmethod
def _xml_path(self):
raise NotImplementedError
@composer.cached_property
def mocap_joints(self):
return tuple(
self._mjcf_root.find('joint', name) for name in _CMU_MOCAP_JOINTS)
@property
def actuator_order(self):
"""Index of joints from the CMU mocap dataset sorted alphabetically by name.
Actuators in this walkers are ordered alphabetically by name. This property
provides a mapping between from actuator ordering to canonical CMU ordering.
Returns:
A list of integers corresponding to joint indices from the CMU dataset.
Specifically, the n-th element in the list is the index of the CMU joint
index that corresponds to the n-th actuator in this walker.
"""
return self._actuator_order
@property
def actuator_to_joint_order(self):
"""Index of actuators corresponding to each CMU mocap joint.
Actuators in this walkers are ordered alphabetically by name. This property
provides a mapping between from canonical CMU ordering to actuator ordering.
Returns:
A list of integers corresponding to actuator indices within this walker.
Specifically, the n-th element in the list is the index of the actuator
in this walker that corresponds to the n-th joint from the CMU mocap
dataset.
"""
return self._inverse_order
@property
def upright_pose(self):
return base.WalkerPose(xpos=_UPRIGHT_POS, xquat=_UPRIGHT_QUAT)
@property
def mjcf_model(self):
return self._mjcf_root
@composer.cached_property
def actuators(self):
return tuple(self._mjcf_root.find_all('actuator'))
@composer.cached_property
def root_body(self):
return self._mjcf_root.find('body', 'root')
@composer.cached_property
def head(self):
return self._mjcf_root.find('body', 'head')
@composer.cached_property
def left_arm_root(self):
return self._mjcf_root.find('body', 'lclavicle')
@composer.cached_property
def right_arm_root(self):
return self._mjcf_root.find('body', 'rclavicle')
@composer.cached_property
def ground_contact_geoms(self):
return tuple(self._mjcf_root.find('body', 'lfoot').find_all('geom') +
self._mjcf_root.find('body', 'rfoot').find_all('geom'))
@composer.cached_property
def standing_height(self):
return _STAND_HEIGHT
@composer.cached_property
def end_effectors(self):
return (self._mjcf_root.find('body', 'rradius'),
self._mjcf_root.find('body', 'lradius'),
self._mjcf_root.find('body', 'rfoot'),
self._mjcf_root.find('body', 'lfoot'))
@composer.cached_property
def observable_joints(self):
return tuple(actuator.joint for actuator in self.actuators
if actuator.joint is not None)
@composer.cached_property
def bodies(self):
return tuple(self._mjcf_root.find_all('body'))
@composer.cached_property
def mocap_tracking_bodies(self):
"""Collection of bodies for mocap tracking."""
# remove root body
root_body = self._mjcf_root.find('body', 'root')
return tuple(
b for b in self._mjcf_root.find_all('body') if b != root_body)
@composer.cached_property
def egocentric_camera(self):
return self._mjcf_root.find('camera', 'egocentric')
@composer.cached_property
def body_camera(self):
return self._mjcf_root.find('camera', 'bodycam')
@property
def marker_geoms(self):
return (self._mjcf_root.find('geom', 'rradius'),
self._mjcf_root.find('geom', 'lradius'))
class CMUHumanoid(_CMUHumanoidBase):
"""A CMU humanoid walker."""
@property
def _xml_path(self):
return _XML_PATH.format(model_version='2019')
class CMUHumanoidPositionControlled(CMUHumanoid):
"""A position-controlled CMU humanoid with control range scaled to [-1, 1]."""
def _build(self, model_version='2019', **kwargs):
self._version = model_version
if 'scale_default' in kwargs:
scale_default = kwargs['scale_default']
del kwargs['scale_default']
else:
scale_default = False
super()._build(**kwargs)
if scale_default:
# NOTE: This rescaling doesn't affect the attached hands
rescale.rescale_humanoid(self, 1.2, 1.2, 70)
# modify actuators
if self._version == '2020':
position_actuators = _POSITION_ACTUATORS_V2020
else:
position_actuators = _POSITION_ACTUATORS
self._mjcf_root.default.general.forcelimited = 'true'
self._mjcf_root.actuator.motor.clear()
for actuator_params in position_actuators:
associated_joint = self._mjcf_root.find('joint', actuator_params.name)
if hasattr(actuator_params, 'damping'):
associated_joint.damping = actuator_params.damping
actuator = scaled_actuators.add_position_actuator(
name=actuator_params.name,
target=associated_joint,
kp=actuator_params.kp,
qposrange=associated_joint.range,
ctrlrange=(-1, 1),
forcerange=actuator_params.forcerange)
if self._version == '2020':
actuator.dyntype = 'filter'
actuator.dynprm = [0.030]
limits = zip(*(actuator.joint.range for actuator in self.actuators)) # pylint: disable=not-an-iterable
lower, upper = (np.array(limit) for limit in limits)
self._scale = upper - lower
self._offset = upper + lower
@property
def _xml_path(self):
return _XML_PATH.format(model_version=self._version)
def cmu_pose_to_actuation(self, target_pose):
"""Creates the control signal corresponding a CMU mocap joints pose.
Args:
target_pose: An array containing the target position for each joint.
These must be given in "canonical CMU order" rather than "qpos order",
i.e. the order of `target_pose[self.actuator_order]` should correspond
to the order of `physics.bind(self.actuators).ctrl`.
Returns:
An array of the same shape as `target_pose` containing inputs for position
controllers. Writing these values into `physics.bind(self.actuators).ctrl`
will cause the actuators to drive joints towards `target_pose`.
"""
return (2 * target_pose[self.actuator_order] - self._offset) / self._scale
class CMUHumanoidPositionControlledV2020(CMUHumanoidPositionControlled):
"""A 2020 updated CMU humanoid walker; includes nose for head orientation."""
def _build(self, **kwargs):
super()._build(
model_version='2020', scale_default=True, include_face=True, **kwargs)
@property
def upright_pose(self):
return base.WalkerPose(xpos=_UPRIGHT_POS_V2020, xquat=_UPRIGHT_QUAT)
class CMUHumanoidObservables(legacy_base.WalkerObservables):
"""Observables for the Humanoid."""
@composer.observable
def body_camera(self):
options = mj_wrapper.MjvOption()
# Don't render this walker's geoms.
options.geomgroup[_WALKER_GEOM_GROUP] = 0
return observable.MJCFCamera(
self._entity.body_camera, width=64, height=64, scene_option=options)
@composer.observable
def egocentric_camera(self):
options = mj_wrapper.MjvOption()
# Don't render this walker's geoms.
options.geomgroup[_WALKER_INVIS_GROUP] = 0
return observable.MJCFCamera(self._entity.egocentric_camera,
width=64, height=64, scene_option=options)
@composer.observable
def head_height(self):
return observable.MJCFFeature('xpos', self._entity.head)[2]
@composer.observable
def sensors_torque(self):
return observable.MJCFFeature(
'sensordata', self._entity.mjcf_model.sensor.torque,
corruptor=lambda v, random_state: np.tanh(2 * v / _TORQUE_THRESHOLD))
@composer.observable
def actuator_activation(self):
return observable.MJCFFeature('act',
self._entity.mjcf_model.find_all('actuator'))
@composer.observable
def appendages_pos(self):
"""Equivalent to `end_effectors_pos` with the head's position appended."""
def relative_pos_in_egocentric_frame(physics):
end_effectors_with_head = (
self._entity.end_effectors + (self._entity.head,))
end_effector = physics.bind(end_effectors_with_head).xpos
torso = physics.bind(self._entity.root_body).xpos
xmat = np.reshape(physics.bind(self._entity.root_body).xmat, (3, 3))
return np.reshape(np.dot(end_effector - torso, xmat), -1)
return observable.Generic(relative_pos_in_egocentric_frame)
@property
def proprioception(self):
return [
self.joints_pos,
self.joints_vel,
self.actuator_activation,
self.body_height,
self.end_effectors_pos,
self.appendages_pos,
self.world_zaxis
] + self._collect_from_attachments('proprioception')
| dm_control-main | dm_control/locomotion/walkers/cmu_humanoid.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for the Ant."""
from absl.testing import absltest
from absl.testing import parameterized
from dm_control import composer
from dm_control import mjcf
from dm_control.composer.observation.observable import base as observable_base
from dm_control.locomotion.arenas import corridors as corr_arenas
from dm_control.locomotion.tasks import corridors as corr_tasks
from dm_control.locomotion.walkers import ant
import numpy as np
_CONTROL_TIMESTEP = .02
_PHYSICS_TIMESTEP = 0.005
def _get_ant_corridor_physics():
walker = ant.Ant()
arena = corr_arenas.EmptyCorridor()
task = corr_tasks.RunThroughCorridor(
walker=walker,
arena=arena,
walker_spawn_position=(5, 0, 0),
walker_spawn_rotation=0,
physics_timestep=_PHYSICS_TIMESTEP,
control_timestep=_CONTROL_TIMESTEP)
env = composer.Environment(
time_limit=30,
task=task,
strip_singleton_obs_buffer_dim=True)
return walker, env
class AntTest(parameterized.TestCase):
def test_can_compile_and_step_simulation(self):
_, env = _get_ant_corridor_physics()
physics = env.physics
for _ in range(100):
physics.step()
@parameterized.parameters([
'egocentric_camera',
'root_body',
])
def test_get_element_property(self, name):
attribute_value = getattr(ant.Ant(), name)
self.assertIsInstance(attribute_value, mjcf.Element)
@parameterized.parameters([
'actuators',
'end_effectors',
'observable_joints',
])
def test_get_element_tuple_property(self, name):
attribute_value = getattr(ant.Ant(), name)
self.assertNotEmpty(attribute_value)
for item in attribute_value:
self.assertIsInstance(item, mjcf.Element)
def test_set_name(self):
name = 'fred'
walker = ant.Ant(name=name)
self.assertEqual(walker.mjcf_model.model, name)
@parameterized.parameters(
'appendages_pos',
'sensors_touch',
)
def test_evaluate_observable(self, name):
walker, env = _get_ant_corridor_physics()
physics = env.physics
observable = getattr(walker.observables, name)
observation = observable(physics)
self.assertIsInstance(observation, (float, np.ndarray))
def test_proprioception(self):
walker = ant.Ant()
for item in walker.observables.proprioception:
self.assertIsInstance(item, observable_base.Observable)
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/locomotion/walkers/ant_test.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for rescaling bodies."""
from absl.testing import absltest
from dm_control import mjcf
from dm_control.locomotion.walkers import rescale
import numpy as np
class RescaleTest(absltest.TestCase):
def setUp(self):
super().setUp()
# build a simple three-link chain with an endpoint site
self._mjcf_model = mjcf.RootElement()
body = self._mjcf_model.worldbody.add('body', pos=[0, 0, 0])
body.add('geom', type='capsule', fromto=[0, 0, 0, 0, 0, -0.4], size=[0.06])
body.add('joint', type='ball')
body = body.add('body', pos=[0, 0, -0.5])
body.add('geom', type='capsule', pos=[0, 0, -0.15], size=[0.06, 0.15])
body.add('joint', type='ball')
body = body.add('body', pos=[0, 0, -0.4])
body.add('geom', type='capsule', fromto=[0, 0, 0, 0.3, 0, -0.4],
size=[0.06])
body.add('joint', type='ball')
body.add('site', name='endpoint', type='sphere', pos=[0.3, 0, -0.4],
size=[0.1])
def test_rescale(self):
# verify endpoint is where expected
physics = mjcf.Physics.from_mjcf_model(self._mjcf_model)
np.testing.assert_allclose(physics.named.data.site_xpos['endpoint'],
np.array([0.3, 0., -1.3]), atol=1e-15)
# rescale chain and verify endpoint is where expected after modification
subtree_root = self._mjcf_model
position_factor = .5
size_factor = .5
rescale.rescale_subtree(subtree_root, position_factor, size_factor)
physics = mjcf.Physics.from_mjcf_model(self._mjcf_model)
np.testing.assert_allclose(physics.named.data.site_xpos['endpoint'],
np.array([0.15, 0., -0.65]), atol=1e-15)
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/locomotion/walkers/rescale_test.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Base class for Walkers."""
import abc
import collections
from dm_control import composer
from dm_control.composer.observation import observable
from dm_env import specs
import numpy as np
def _make_readonly_float64_copy(value):
if np.isscalar(value):
return np.float64(value)
else:
out = np.array(value, dtype=np.float64)
out.flags.writeable = False
return out
class WalkerPose(collections.namedtuple(
'WalkerPose', ('qpos', 'xpos', 'xquat'))):
"""A named tuple representing a walker's joint and Cartesian pose."""
__slots__ = ()
def __new__(cls, qpos=None, xpos=(0, 0, 0), xquat=(1, 0, 0, 0)):
"""Creates a new WalkerPose.
Args:
qpos: The joint position for the pose, or `None` if the `qpos0` values in
the `mjModel` should be used.
xpos: A Cartesian displacement, for example if the walker should be lifted
or lowered by a specific amount for this pose.
xquat: A quaternion displacement for the root body.
Returns:
A new instance of `WalkerPose`.
"""
return super(WalkerPose, cls).__new__(
cls,
qpos=_make_readonly_float64_copy(qpos) if qpos is not None else None,
xpos=_make_readonly_float64_copy(xpos),
xquat=_make_readonly_float64_copy(xquat))
def __eq__(self, other):
return (np.all(self.qpos == other.qpos) and
np.all(self.xpos == other.xpos) and
np.all(self.xquat == other.xquat))
class Walker(composer.Robot, metaclass=abc.ABCMeta):
"""Abstract base class for Walker robots."""
def create_root_joints(self, attachment_frame) -> None:
attachment_frame.add('freejoint')
def _build_observables(self) -> 'WalkerObservables':
return WalkerObservables(self)
def transform_vec_to_egocentric_frame(self, physics, vec_in_world_frame):
"""Linearly transforms a world-frame vector into walker's egocentric frame.
Note that this function does not perform an affine transformation of the
vector. In other words, the input vector is assumed to be specified with
respect to the same origin as this walker's egocentric frame. This function
can also be applied to matrices whose innermost dimensions are either 2 or
3. In this case, a matrix with the same leading dimensions is returned
where the innermost vectors are replaced by their values computed in the
egocentric frame.
Args:
physics: An `mjcf.Physics` instance.
vec_in_world_frame: A NumPy array with last dimension of shape (2,) or
(3,) that represents a vector quantity in the world frame.
Returns:
The same quantity as `vec_in_world_frame` but reexpressed in this
entity's egocentric frame. The returned np.array has the same shape as
np.asarray(vec_in_world_frame).
Raises:
ValueError: if `vec_in_world_frame` does not have shape ending with (2,)
or (3,).
"""
return super().global_vector_to_local_frame(physics, vec_in_world_frame)
def transform_xmat_to_egocentric_frame(self, physics, xmat):
"""Transforms another entity's `xmat` into this walker's egocentric frame.
This function takes another entity's (E) xmat, which is an SO(3) matrix
from E's frame to the world frame, and turns it to a matrix that transforms
from E's frame into this walker's egocentric frame.
Args:
physics: An `mjcf.Physics` instance.
xmat: A NumPy array of shape (3, 3) or (9,) that represents another
entity's xmat.
Returns:
The `xmat` reexpressed in this entity's egocentric frame. The returned
np.array has the same shape as np.asarray(xmat).
Raises:
ValueError: if `xmat` does not have shape (3, 3) or (9,).
"""
return super().global_xmat_to_local_frame(physics, xmat)
@property
@abc.abstractmethod
def root_body(self):
raise NotImplementedError
@property
@abc.abstractmethod
def observable_joints(self):
raise NotImplementedError
@property
def action_spec(self):
if not self.actuators:
minimum, maximum = (), ()
else:
minimum, maximum = zip(*[
a.ctrlrange if a.ctrlrange is not None else (-1., 1.)
for a in self.actuators
])
return specs.BoundedArray(
shape=(len(self.actuators),),
dtype=float,
minimum=minimum,
maximum=maximum,
name='\t'.join([actuator.name for actuator in self.actuators]))
def apply_action(self, physics, action, random_state):
"""Apply action to walker's actuators."""
del random_state
physics.bind(self.actuators).ctrl = action
class WalkerObservables(composer.Observables):
"""Base class for Walker obserables."""
@composer.observable
def joints_pos(self):
return observable.MJCFFeature('qpos', self._entity.observable_joints)
@composer.observable
def sensors_gyro(self):
return observable.MJCFFeature('sensordata',
self._entity.mjcf_model.sensor.gyro)
@composer.observable
def sensors_accelerometer(self):
return observable.MJCFFeature('sensordata',
self._entity.mjcf_model.sensor.accelerometer)
@composer.observable
def sensors_framequat(self):
return observable.MJCFFeature('sensordata',
self._entity.mjcf_model.sensor.framequat)
# Semantic groupings of Walker observables.
def _collect_from_attachments(self, attribute_name):
out = []
for entity in self._entity.iter_entities(exclude_self=True):
out.extend(getattr(entity.observables, attribute_name, []))
return out
@property
def proprioception(self):
return ([self.joints_pos] +
self._collect_from_attachments('proprioception'))
@property
def kinematic_sensors(self):
return ([self.sensors_gyro,
self.sensors_accelerometer,
self.sensors_framequat] +
self._collect_from_attachments('kinematic_sensors'))
@property
def dynamic_sensors(self):
return self._collect_from_attachments('dynamic_sensors')
| dm_control-main | dm_control/locomotion/walkers/base.py |
# Copyright 2023 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Make tail for the dog model."""
import collections
from dm_control import mjcf
import numpy as np
def create_tail(
caudal_dofs_per_vertebra, bone_size, model, bone_position, parent
):
"""Add tail in the dog model.
Args:
caudal_dofs_per_vertebra: a number that the determines how many dofs are
going to be used between each pair of caudal vetebrae.
bone_size: dictionary containing the scale of the geometry.
model: model in which we want to add the tail.
bone_position: a dictionary of bones positions.
parent: parent object on which we should start attaching new components.
Returns:
A list of caudal joints.
"""
# Caudal spine (tail) bodies:
caudal_bones = ['Ca_' + str(i + 1) for i in range(21)]
parent_pos = bone_position['Pelvis']
caudal_bodies = []
caudal_geoms = []
for bone in caudal_bones:
bone_pos = bone_position[bone]
rel_pos = bone_pos - parent_pos
xyaxes = np.hstack((-rel_pos, (0, 1, 0)))
xyaxes[1] = 0
child = parent.add('body', name=bone, pos=rel_pos)
caudal_bodies.append(child)
geom = child.add('geom', name=bone, mesh=bone, pos=-bone_pos, dclass='bone')
caudal_geoms.append(geom)
parent = child
parent_pos = bone_pos
# Reload
physics = mjcf.Physics.from_mjcf_model(model)
# Caudal spine joints:
caudal_axis = collections.OrderedDict()
caudal_axis['extend'] = np.array((0.0, 1.0, 0.0))
scale = np.asarray([bone_size[bone] for bone in caudal_bones]).mean()
joint_pos = np.array((0.3, 0, 0.26)) * scale
num_dofs = 0
caudal_joints = []
caudal_joint_names = []
parent = model.find('geom', 'Sacrum')
for i, vertebra in enumerate(caudal_bodies):
while num_dofs < (i + 1) * caudal_dofs_per_vertebra:
dof = num_dofs % 2
dof_name = list(caudal_axis.keys())[dof]
caudal_joint_names.append(vertebra.name + '_' + dof_name)
rel_pos = physics.bind(parent).xpos - physics.bind(vertebra).xpos
twist_dir = rel_pos / np.linalg.norm(rel_pos)
bend_dir = np.cross(caudal_axis['extend'], twist_dir)
caudal_axis['bend'] = bend_dir
joint_pos = twist_dir * physics.bind(caudal_geoms[i]).size[2]
joint = vertebra.add(
'joint',
name=caudal_joint_names[-1],
dclass='caudal_' + dof_name,
axis=caudal_axis[dof_name],
pos=joint_pos,
)
caudal_joints.append(joint)
num_dofs += 1
parent = vertebra
parent.add('site', name='tail_tip', dclass='sensor', size=(0.005,))
physics = mjcf.Physics.from_mjcf_model(model)
all_geoms = model.find_all('geom')
for geom in all_geoms:
if 'Ca_' in geom.name:
sc = (float(geom.name[3:]) + 1) / 4
scale = np.array((1.2, sc, 1))
bound_geom = physics.bind(geom)
geom.parent.add(
'geom',
name=geom.name + '_collision',
pos=bound_geom.pos,
size=bound_geom.size * scale,
quat=bound_geom.quat,
dclass='collision_primitive',
)
return caudal_joints
| dm_control-main | dm_control/locomotion/walkers/assets/dog_v2/build_tail.py |
# Copyright 2023 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Make torso for the dog model."""
import collections
from dm_control import mjcf
import numpy as np
def create_torso(
model, bones, bone_position, lumbar_dofs_per_vertebra, side_sign, parent
):
"""Add torso in the dog model.
Args:
model: model in which we want to add the torso.
bones: a list of strings with all the names of the bones.
bone_position: a dictionary of bones positions.
lumbar_dofs_per_vertebra: a number that the determines how many dofs are
going to be used between each pair of lumbar vetebrae.
side_sign: a dictionary with two axis representing the signs of
translations.
parent: parent object on which we should start attaching new components.
Returns:
The tuple `(pelvic_bones, lumbar_joints)`.
"""
# Lumbar Spine
def_lumbar_extend = model.default.find('default', 'lumbar_extend')
def_lumbar_bend = model.default.find('default', 'lumbar_bend')
def_lumbar_twist = model.default.find('default', 'lumbar_twist')
lumbar_defaults = {
'extend': def_lumbar_extend,
'bend': def_lumbar_bend,
'twist': def_lumbar_twist,
}
thoracic_spine = [m for m in bones if 'T_' in m]
ribs = [m for m in bones if 'Rib' in m and 'cage' not in m]
sternum = [m for m in bones if 'Sternum' in m]
torso_bones = thoracic_spine + ribs + sternum # + ['Xiphoid_cartilage']
torso = parent.add('body', name='torso')
torso.add('freejoint', name='root')
torso.add('site', name='root', size=(0.01,), rgba=[0, 1, 0, 1])
torso.add('light', name='light', mode='trackcom', pos=[0, 0, 3])
torso.add(
'camera',
name='y-axis',
mode='trackcom',
pos=[0, -1.5, 0.8],
xyaxes=[1, 0, 0, 0, 0.6, 1],
)
torso.add(
'camera',
name='x-axis',
mode='trackcom',
pos=[2, 0, 0.5],
xyaxes=[0, 1, 0, -0.3, 0, 1],
)
torso_geoms = []
for bone in torso_bones:
torso_geoms.append(
torso.add('geom', name=bone, mesh=bone, dclass='light_bone')
)
# Reload, get CoM position, set pos
physics = mjcf.Physics.from_mjcf_model(model)
torso_pos = np.array(physics.bind(model.find('body', 'torso')).xipos)
torso.pos = torso_pos
for geom in torso_geoms:
geom.pos = -torso_pos
# Collision primitive for torso
torso.add(
'geom',
name='collision_torso',
dclass='nonself_collision_primitive',
type='ellipsoid',
pos=[0, 0, 0],
size=[0.2, 0.09, 0.11],
euler=[0, 10, 0],
density=200,
)
# Lumbar spine bodies:
lumbar_bones = ['L_1', 'L_2', 'L_3', 'L_4', 'L_5', 'L_6', 'L_7']
parent = torso
parent_pos = torso_pos
lumbar_bodies = []
lumbar_geoms = []
for i, bone in enumerate(lumbar_bones):
bone_pos = bone_position[bone]
child = parent.add('body', name=bone, pos=bone_pos - parent_pos)
lumbar_bodies.append(child)
geom = child.add('geom', name=bone, mesh=bone, pos=-bone_pos, dclass='bone')
child.add(
'geom',
name=bone + '_collision',
type='sphere',
size=[0.05],
pos=[0, 0, -0.02],
dclass='nonself_collision_primitive',
)
lumbar_geoms.append(geom)
parent = child
parent_pos = bone_pos
l_7 = parent
# Lumbar spine joints:
lumbar_axis = collections.OrderedDict()
lumbar_axis['extend'] = np.array((0.0, 1.0, 0.0))
lumbar_axis['bend'] = np.array((0.0, 0.0, 1.0))
lumbar_axis['twist'] = np.array((1.0, 0.0, 0))
num_dofs = 0
lumbar_joints = []
lumbar_joint_names = []
for i, vertebra in enumerate(lumbar_bodies):
while num_dofs < (i + 1) * lumbar_dofs_per_vertebra:
dof = num_dofs % 3
dof_name = list(lumbar_axis.keys())[dof]
dof_axis = lumbar_axis[dof_name]
lumbar_joint_names.append(vertebra.name + '_' + dof_name)
joint = vertebra.add(
'joint',
name=lumbar_joint_names[-1],
dclass='lumbar_' + dof_name,
axis=dof_axis,
)
lumbar_joints.append(joint)
num_dofs += 1
# Scale joint defaults relative to 3 lumbar_dofs_per_veterbra
for dof in lumbar_axis.keys():
axis_scale = 7.0 / [dof in joint for joint in lumbar_joint_names].count(
True
)
lumbar_defaults[dof].joint.range *= axis_scale
# Pelvis:
pelvis = l_7.add(
'body', name='pelvis', pos=bone_position['Pelvis'] - bone_position['L_7']
)
pelvic_bones = ['Sacrum', 'Pelvis']
pelvic_geoms = []
for bone in pelvic_bones:
geom = pelvis.add(
'geom',
name=bone,
mesh=bone,
pos=-bone_position['Pelvis'],
dclass='bone',
)
pelvic_geoms.append(geom)
# Collision primitives for pelvis
for side in ['_L', '_R']:
pos = np.array((0.01, -0.02, -0.01)) * side_sign[side]
pelvis.add(
'geom',
name='collision_pelvis' + side,
pos=pos,
size=[0.05, 0.05, 0],
euler=[0, 70, 0],
dclass='nonself_collision_primitive',
)
return pelvic_bones, lumbar_joints
| dm_control-main | dm_control/locomotion/walkers/assets/dog_v2/build_torso.py |
# Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Make dog model."""
import os
from absl import app
from absl import flags
from dm_control import mjcf
from dm_control.locomotion.walkers.assets.dog_v2 import add_torque_actuators
from dm_control.locomotion.walkers.assets.dog_v2 import build_back_legs
from dm_control.locomotion.walkers.assets.dog_v2 import build_front_legs
from dm_control.locomotion.walkers.assets.dog_v2 import build_neck
from dm_control.locomotion.walkers.assets.dog_v2 import build_tail
from dm_control.locomotion.walkers.assets.dog_v2 import build_torso
from dm_control.locomotion.walkers.assets.dog_v2 import create_skin
from lxml import etree
import numpy as np
from dm_control.utils import io as resources
flags.DEFINE_boolean('make_skin', True, 'Whether to make a new dog_skin.skn')
flags.DEFINE_float(
'lumbar_dofs_per_vertebra',
1.5,
'Number of degrees of freedom per vertebra in lumbar spine.',
)
flags.DEFINE_float(
'cervical_dofs_per_vertebra',
1.5,
'Number of degrees of freedom vertebra in cervical spine.',
)
flags.DEFINE_float(
'caudal_dofs_per_vertebra',
1,
'Number of degrees of freedom vertebra in caudal spine.',
)
FLAGS = flags.FLAGS
BASE_MODEL = 'dog_base.xml'
ASSET_RELPATH = '../../../../suite/dog_assets'
ASSET_DIR = os.path.dirname(__file__) + '/' + ASSET_RELPATH
print(ASSET_DIR)
def exclude_contacts(model):
"""Exclude contacts from model.
Args:
model: model in which we want to exclude contacts.
"""
physics = mjcf.Physics.from_mjcf_model(model)
excluded_pairs = []
for c in physics.data.contact:
body1 = physics.model.id2name(physics.model.geom_bodyid[c.geom1], 'body')
body2 = physics.model.id2name(physics.model.geom_bodyid[c.geom2], 'body')
pair = body1 + ':' + body2
if pair not in excluded_pairs:
excluded_pairs.append(pair)
model.contact.add('exclude', name=pair, body1=body1, body2=body2)
# manual exclusions
model.contact.add(
'exclude',
name='C_1:jaw',
body1=model.find('body', 'C_1'),
body2=model.find('body', 'jaw'),
)
model.contact.add(
'exclude',
name='torso:lower_arm_L',
body1=model.find('body', 'torso'),
body2='lower_arm_L',
)
model.contact.add(
'exclude',
name='torso:lower_arm_R',
body1=model.find('body', 'torso'),
body2='lower_arm_R',
)
model.contact.add(
'exclude', name='C_4:scapula_R', body1='C_4', body2='scapula_R'
)
model.contact.add(
'exclude', name='C_4:scapula_L', body1='C_4', body2='scapula_L'
)
model.contact.add(
'exclude', name='C_5:upper_arm_R', body1='C_5', body2='upper_arm_R'
)
model.contact.add(
'exclude', name='C_5:upper_arm_L', body1='C_5', body2='upper_arm_L'
)
model.contact.add(
'exclude', name='C_6:upper_arm_R', body1='C_6', body2='upper_arm_R'
)
model.contact.add(
'exclude', name='C_6:upper_arm_L', body1='C_6', body2='upper_arm_L'
)
model.contact.add(
'exclude', name='C_7:upper_arm_R', body1='C_7', body2='upper_arm_R'
)
model.contact.add(
'exclude', name='C_7:upper_arm_L', body1='C_7', body2='upper_arm_L'
)
model.contact.add(
'exclude',
name='upper_leg_L:upper_leg_R',
body1='upper_leg_L',
body2='upper_leg_R',
)
for side in ['_L', '_R']:
model.contact.add(
'exclude',
name='lower_leg' + side + ':pelvis',
body1='lower_leg' + side,
body2='pelvis',
)
model.contact.add(
'exclude',
name='upper_leg' + side + ':foot' + side,
body1='upper_leg' + side,
body2='foot' + side,
)
def main(argv):
del argv
# Read flags.
if FLAGS.is_parsed():
lumbar_dofs_per_vert = FLAGS.lumbar_dofs_per_vertebra
cervical_dofs_per_vertebra = FLAGS.cervical_dofs_per_vertebra
caudal_dofs_per_vertebra = FLAGS.caudal_dofs_per_vertebra
make_skin = FLAGS.make_skin
else:
lumbar_dofs_per_vert = FLAGS['lumbar_dofs_per_vertebra'].default
cervical_dofs_per_vertebra = FLAGS['cervical_dofs_per_vertebra'].default
caudal_dofs_per_vertebra = FLAGS['caudal_dofs_per_vertebra'].default
make_skin = FLAGS['make_skin'].default
print('Load base model.')
with open(BASE_MODEL, 'r') as f:
model = mjcf.from_file(f)
# Helper constants:
side_sign = {
'_L': np.array((1.0, -1.0, 1.0)),
'_R': np.array((1.0, 1.0, 1.0)),
}
primary_axis = {
'_abduct': np.array((-1.0, 0.0, 0.0)),
'_extend': np.array((0.0, 1.0, 0.0)),
'_supinate': np.array((0.0, 0.0, -1.0)),
}
# Add meshes:
print('Loading all meshes, getting positions and sizes.')
meshdir = ASSET_DIR
model.compiler.meshdir = meshdir
texturedir = ASSET_DIR
model.compiler.texturedir = texturedir
bones = []
for dirpath, _, filenames in resources.WalkResources(meshdir):
prefix = 'extras/' if 'extras' in dirpath else ''
for filename in filenames:
if 'dog_skin.msh' in filename:
skin_msh = model.asset.add(
'mesh', name='skin_msh', file=filename, scale=(1.25, 1.25, 1.25)
)
name = filename[4:-4]
name = name.replace('*', ':')
if filename.startswith('BONE'):
if 'Lingual' not in name:
bones.append(name)
model.asset.add('mesh', name=name, file=prefix + filename)
# Put all bones in worldbody, get positions, remove bones:
bone_geoms = []
for bone in bones:
geom = model.worldbody.add(
'geom',
name=bone,
mesh=bone,
type='mesh',
contype=0,
conaffinity=0,
rgba=[1, 0.5, 0.5, 0.4],
)
bone_geoms.append(geom)
physics = mjcf.Physics.from_mjcf_model(model)
bone_position = {}
bone_size = {}
for bone in bones:
geom = model.find('geom', bone)
bone_position[bone] = np.array(physics.bind(geom).xpos)
bone_size[bone] = np.array(physics.bind(geom).rbound)
geom.remove()
# Torso
print('Torso, lumbar spine, pelvis.')
pelvic_bones, lumbar_joints = build_torso.create_torso(
model,
bones,
bone_position,
lumbar_dofs_per_vert,
side_sign,
parent=model.worldbody,
)
print('Neck, skull, jaw.')
# Cervical spine (neck) bodies:
cervical_joints = build_neck.create_neck(
model,
bone_position,
cervical_dofs_per_vertebra,
bones,
side_sign,
bone_size,
parent=model.find('body', 'torso'),
)
print('Back legs.')
nails, sole_sites = build_back_legs.create_back_legs(
model,
primary_axis,
bone_position,
bones,
side_sign,
bone_size,
pelvic_bones,
parent=model.find('body', 'pelvis'),
)
print('Shoulders, front legs.')
palm_sites = build_front_legs.create_front_legs(
nails,
model,
primary_axis,
bones,
side_sign,
parent=model.find('body', 'torso'),
)
print('Tail.')
caudal_joints = build_tail.create_tail(
caudal_dofs_per_vertebra,
bone_size,
model,
bone_position,
parent=model.find('body', 'pelvis'),
)
print('Collision geoms, fixed tendons.')
physics = mjcf.Physics.from_mjcf_model(model)
print('Unify ribcage and jaw meshes.')
for body in model.find_all('body'):
body_meshes = [
geom
for geom in body.all_children()
if geom.tag == 'geom'
and hasattr(geom, 'mesh')
and geom.mesh is not None
]
if len(body_meshes) > 10:
mergables = [
('torso', 'Ribcage'),
('jaw', 'Jaw'),
('skull', 'MergedSkull'),
]
for bodyname, meshname in mergables:
if body.name == bodyname:
print('==== Merging ', bodyname)
for mesh in body_meshes:
print(mesh.name)
body.add(
'inertial',
mass=physics.bind(body).mass,
pos=physics.bind(body).ipos,
quat=physics.bind(body).iquat,
diaginertia=physics.bind(body).inertia,
)
for mesh in body_meshes:
if 'eye' not in mesh.name:
model.find('mesh', mesh.name).remove()
mesh.remove()
body.add(
'geom',
name=meshname,
mesh=meshname,
dclass='bone',
pos=-bone_position[meshname],
)
print('Add Actuators')
actuated_joints = add_torque_actuators.add_motors(
physics, model, lumbar_joints, cervical_joints, caudal_joints
)
print('Excluding contacts.')
exclude_contacts(model)
if make_skin:
create_skin.create(model, skin_msh)
# Add skin from .skn
print('Adding Skin.')
skin_texture = model.asset.add(
'texture', name='skin', file='skin_texture.png', type='2d'
)
skin_material = model.asset.add('material', name='skin', texture=skin_texture)
model.asset.add(
'skin', name='skin', file='dog_skin.skn', material=skin_material
)
skin_msh.remove()
print('Removing non-essential sites.')
all_sites = model.find_all('site')
for site in all_sites:
if site.dclass is None:
site.remove()
physics = mjcf.Physics.from_mjcf_model(model)
# sensors
model.sensor.add(
'accelerometer', name='accelerometer', site=model.find('site', 'head')
)
model.sensor.add(
'velocimeter', name='velocimeter', site=model.find('site', 'head')
)
model.sensor.add('gyro', name='gyro', site=model.find('site', 'head'))
model.sensor.add(
'subtreelinvel', name='torso_linvel', body=model.find('body', 'torso')
)
model.sensor.add(
'subtreeangmom', name='torso_angmom', body=model.find('body', 'torso')
)
for site in palm_sites + sole_sites:
model.sensor.add('touch', name=site.name, site=site)
anchors = [site for site in model.find_all('site') if 'anchor' in site.name]
for site in anchors:
model.sensor.add('force', name=site.name.replace('_anchor', ''), site=site)
# Print stuff
joint_acts = [model.find('actuator', j.name) for j in actuated_joints]
print(
'{:20} {:>10} {:>10} {:>10} {:>10} {:>10}'.format(
'name', 'mass', 'damping', 'stiffness', 'ratio', 'armature'
)
)
for i, j in enumerate(actuated_joints):
dmp = physics.bind(j).damping[0]
mass_eff = physics.bind(j).M0[0]
dmp = physics.bind(j).damping[0]
stf = physics.bind(joint_acts[i]).gainprm[0]
arma = physics.bind(j).armature[0]
print(
'{:20} {:10.4} {:10} {:10.4} {:10.4} {:10}'.format(
j.name,
mass_eff,
dmp,
stf,
dmp / (2 * np.sqrt(mass_eff * stf)),
arma,
)
)
print('Finalising and saving model.')
xml_string = model.to_xml_string('float', precision=4, zero_threshold=1e-7)
root = etree.XML(xml_string, etree.XMLParser(remove_blank_text=True))
print('Remove hashes from filenames')
assets = list(root.find('asset').iter())
for asset in assets:
asset_filename = asset.get('file')
if asset_filename is not None:
name = asset_filename[:-4]
extension = asset_filename[-4:]
asset.set('file', name[:-41] + extension)
print('Add <compiler meshdir/>, for locally-loadable model')
compiler = etree.Element(
'compiler', meshdir=ASSET_RELPATH, texturedir=ASSET_RELPATH
)
root.insert(0, compiler)
print('Remove class="/"')
default_elem = root.find('default')
root.insert(6, default_elem[0])
root.remove(default_elem)
xml_string = etree.tostring(root, pretty_print=True)
xml_string = xml_string.replace(b' class="/"', b'')
print('Insert spaces between top level elements')
lines = xml_string.splitlines()
newlines = []
for line in lines:
newlines.append(line)
if line.startswith(b' <'):
if line.startswith(b' </') or line.endswith(b'/>'):
newlines.append(b'')
newlines.append(b'')
xml_string = b'\n'.join(newlines)
# Save to file.
f = open('dog.xml', 'wb')
f.write(xml_string)
f.close()
if __name__ == '__main__':
app.run(main)
| dm_control-main | dm_control/locomotion/walkers/assets/dog_v2/build_dog.py |
# Copyright 2023 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Make front legs for the dog model."""
from dm_control import mjcf
import numpy as np
def create_front_legs(nails, model, primary_axis, bones, side_sign, parent):
"""Add front legs in the model.
Args:
nails: a list of string with the geoms representing nails.
model: model in which we want to add the front legs.
primary_axis: a dictionary of numpy arrays representing axis of rotation.
bones: a list of strings with all the names of the bones.
side_sign: a dictionary with two axis representing the signs of
translations.
parent: parent object on which we should start attaching new components.
Returns:
A list of palm sites.
"""
def_scapula_supinate = model.default.find('default', 'scapula_supinate')
def_scapula_abduct = model.default.find('default', 'scapula_abduct')
def_scapula_extend = model.default.find('default', 'scapula_extend')
scapula_defaults = {
'_abduct': def_scapula_abduct,
'_extend': def_scapula_extend,
'_supinate': def_scapula_supinate,
}
torso = parent
# Shoulders
scapula = {}
scapulae = [b for b in bones if 'Scapula' in b]
scapula_pos = np.array((0.08, -0.02, 0.14))
for side in ['_L', '_R']:
body_pos = scapula_pos * side_sign[side]
arm = torso.add('body', name='scapula' + side, pos=body_pos)
scapula[side] = arm
for bone in [b for b in scapulae if side in b]:
arm.add(
'geom', name=bone, mesh=bone, pos=-torso.pos - body_pos, dclass='bone'
)
# Shoulder joints
for dof in ['_supinate', '_abduct', '_extend']:
joint_axis = primary_axis[dof].copy()
joint_pos = scapula_defaults[dof].joint.pos.copy()
if dof != '_extend':
joint_axis *= 1.0 if side == '_R' else -1.0
joint_pos *= side_sign[side]
else:
joint_axis += (
0.3 * (1 if side == '_R' else -1) * primary_axis['_abduct']
)
arm.add(
'joint',
name='scapula' + side + dof,
dclass='scapula' + dof,
axis=joint_axis,
pos=joint_pos,
)
# Shoulder sites
shoulder_pos = np.array((0.075, -0.033, -0.13))
arm.add(
'site',
name='shoulder' + side,
size=[0.01],
pos=shoulder_pos * side_sign[side],
)
# Upper Arms:
upper_arm = {}
parent_pos = {}
humeri = ['humerus_R', 'humerus_L']
for side in ['_L', '_R']:
body_pos = shoulder_pos * side_sign[side]
parent = scapula[side]
parent_pos[side] = torso.pos + parent.pos
arm = parent.add('body', name='upper_arm' + side, pos=body_pos)
upper_arm[side] = arm
for bone in [b for b in humeri if side in b]:
arm.add(
'geom',
name=bone,
mesh=bone,
pos=-parent_pos[side] - body_pos,
dclass='bone',
)
parent_pos[side] += body_pos
# Shoulder joints
for dof in ['_supinate', '_extend']:
joint_axis = primary_axis[dof].copy()
if dof == '_supinate':
joint_axis[0] = 1
joint_axis *= 1.0 if side == '_R' else -1.0
arm.add(
'joint',
name='shoulder' + side + dof,
dclass='shoulder' + dof,
axis=joint_axis,
)
# Elbow sites
elbow_pos = np.array((-0.05, -0.015, -0.145))
arm.add(
'site',
type='cylinder',
name='elbow' + side,
size=[0.003, 0.02],
zaxis=(0, 1, -(1.0 if side == '_R' else -1.0) * 0.2),
pos=elbow_pos * side_sign[side],
)
# Lower arms:
lower_arm = {}
lower_arm_bones = [
b
for b in bones
if 'ulna' in b.lower() or 'Radius' in b or 'accessory' in b
]
for side in ['_L', '_R']:
body_pos = elbow_pos * side_sign[side]
arm = upper_arm[side].add('body', name='lower_arm' + side, pos=body_pos)
lower_arm[side] = arm
for bone in [b for b in lower_arm_bones if side in b]:
arm.add(
'geom',
name=bone,
mesh=bone,
pos=-parent_pos[side] - body_pos,
dclass='bone',
)
# Elbow joints
elbow_axis = upper_arm[side].find_all('site')[0].zaxis
arm.add('joint', name='elbow' + side, dclass='elbow', axis=elbow_axis)
parent_pos[side] += body_pos
# Wrist sites
wrist_pos = np.array((0.003, 0.015, -0.19))
arm.add(
'site',
type='cylinder',
name='wrist' + side,
size=[0.004, 0.017],
zaxis=(0, 1, 0),
pos=wrist_pos * side_sign[side],
)
# Hands:
hands = {}
hand_bones = [
b
for b in bones
if ('carpal' in b.lower() and 'acces' not in b and 'ulna' not in b)
or ('distalis_digiti_I_' in b)
]
for side in ['_L', '_R']:
body_pos = wrist_pos * side_sign[side]
hand_anchor = lower_arm[side].add(
'body', name='hand_anchor' + side, pos=body_pos
)
hand_anchor.add(
'geom',
name=hand_anchor.name,
dclass='foot_primitive',
type='box',
size=(0.005, 0.005, 0.005),
contype=0,
conaffinity=0,
)
hand_anchor.add('site', name=hand_anchor.name, dclass='sensor')
hand = hand_anchor.add('body', name='hand' + side)
hands[side] = hand
for bone in [b for b in hand_bones if side in b]:
hand.add(
'geom',
name=bone,
mesh=bone,
pos=-parent_pos[side] - body_pos,
dclass='bone',
)
# Wrist joints
hand.add('joint', name='wrist' + side, dclass='wrist', axis=(0, -1, 0))
hand.add(
'geom',
name=hand.name + '_collision',
size=[0.03, 0.016, 0.012],
pos=[0.01, 0, -0.04],
euler=(0, 65, 0),
dclass='collision_primitive',
type='box',
)
parent_pos[side] += body_pos
# Finger sites
finger_pos = np.array((0.02, 0, -0.06))
hand.add(
'site',
type='cylinder',
name='finger' + side,
size=[0.003, 0.025],
zaxis=((1.0 if side == '_R' else -1.0) * 0.2, 1, 0),
pos=finger_pos * side_sign[side],
)
# Fingers:
finger_bones = [
b for b in bones if 'Phalanx' in b and 'distalis_digiti_I_' not in b
]
palm_sites = []
for side in ['_L', '_R']:
body_pos = finger_pos * side_sign[side]
hand = hands[side].add('body', name='finger' + side, pos=body_pos)
for bone in [b for b in finger_bones if side in b]:
geom = hand.add(
'geom',
name=bone,
mesh=bone,
pos=-parent_pos[side] - body_pos,
dclass='bone',
)
if 'distalis' in bone:
nails.append(bone)
geom.dclass = 'visible_bone'
# Finger joints
finger_axis = upper_arm[side].find_all('site')[0].zaxis
hand.add('joint', name='finger' + side, dclass='finger', axis=finger_axis)
hand.add(
'geom',
name=hand.name + '0_collision',
size=[0.018, 0.012],
pos=[0.012, 0, -0.012],
euler=(90, 0, 0),
dclass='foot_primitive',
)
hand.add(
'geom',
name=hand.name + '1_collision',
size=[0.01, 0.015],
pos=[0.032, 0, -0.02],
euler=(90, 0, 0),
dclass='foot_primitive',
)
hand.add(
'geom',
name=hand.name + '2_collision',
size=[0.008, 0.01],
pos=[0.042, 0, -0.022],
euler=(90, 0, 0),
dclass='foot_primitive',
)
palm = hand.add(
'site',
name='palm' + side,
size=(0.028, 0.03, 0.007),
pos=(0.02, 0, -0.024),
type='box',
dclass='sensor',
)
palm_sites.append(palm)
physics = mjcf.Physics.from_mjcf_model(model)
for side in ['_L', '_R']:
# scapula:
scap = scapula[side]
geom = scap.get_children('geom')[0]
bound_geom = physics.bind(geom)
scap.add(
'geom',
name=geom.name + '_collision',
pos=bound_geom.pos,
size=bound_geom.size * 0.8,
quat=bound_geom.quat,
type='box',
dclass='collision_primitive',
)
# upper arm:
arm = upper_arm[side]
geom = arm.get_children('geom')[0]
bound_geom = physics.bind(geom)
arm.add(
'geom',
name=geom.name + '_collision',
pos=bound_geom.pos,
size=[0.02, 0.08],
quat=bound_geom.quat,
dclass='collision_primitive',
)
all_geoms = model.find_all('geom')
for geom in all_geoms:
if 'Ulna' in geom.name:
bound_geom = physics.bind(geom)
geom.parent.add(
'geom',
name=geom.name + '_collision',
pos=bound_geom.pos,
size=[0.015, 0.06],
quat=bound_geom.quat,
dclass='collision_primitive',
)
if 'Radius' in geom.name:
bound_geom = physics.bind(geom)
pos = bound_geom.pos + np.array((-0.005, 0.0, -0.01))
geom.parent.add(
'geom',
name=geom.name + '_collision',
pos=pos,
size=[0.017, 0.09],
quat=bound_geom.quat,
dclass='collision_primitive',
)
return palm_sites
| dm_control-main | dm_control/locomotion/walkers/assets/dog_v2/build_front_legs.py |
# Copyright 2023 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Make back legs for the dog model."""
from dm_control import mjcf
import numpy as np
def create_back_legs(
model,
primary_axis,
bone_position,
bones,
side_sign,
bone_size,
pelvic_bones,
parent,
):
"""Add back legs in the model.
Args:
model: model in which we want to add the back legs.
primary_axis: a dictionary of numpy arrays representing axis of rotation.
bone_position: a dictionary of bones positions.
bones: a list of strings with all the names of the bones.
side_sign: a dictionary with two axis representing the signs of
translations.
bone_size: dictionary containing the scale of the geometry.
pelvic_bones: list of string of the pelvic bones.
parent: parent object on which we should start attaching new components.
Returns:
The tuple `(nails, sole_sites)`.
"""
pelvis = parent
# Hip joint sites:
scale = np.asarray([bone_size[bone] for bone in pelvic_bones]).mean()
hip_pos = np.array((-0.23, -0.6, -0.16)) * scale
for side in ['_L', '_R']:
pelvis.add(
'site', name='hip' + side, size=[0.011], pos=hip_pos * side_sign[side]
)
# Upper legs:
upper_leg = {}
femurs = [b for b in bones if 'Fem' in b]
use_tendons = False
if not use_tendons:
femurs += [b for b in bones if 'Patella' in b]
for side in ['_L', '_R']:
body_pos = hip_pos * side_sign[side]
leg = pelvis.add('body', name='upper_leg' + side, pos=body_pos)
upper_leg[side] = leg
for bone in [b for b in femurs if side in b]:
leg.add(
'geom',
name=bone,
mesh=bone,
pos=-bone_position['Pelvis'] - body_pos,
dclass='bone',
)
# Hip joints
for dof in ['_supinate', '_abduct', '_extend']:
axis = primary_axis[dof].copy()
if dof != '_extend':
axis *= 1.0 if side != '_R' else -1.0
leg.add('joint', name='hip' + side + dof, dclass='hip' + dof, axis=axis)
# Knee sites
scale = bone_size['Femoris_L']
knee_pos = np.array((-0.2, -0.27, -1.45)) * scale
leg.add(
'site',
type='cylinder',
name='knee' + side,
size=[0.003, 0.02],
zaxis=(0, 1, 0),
pos=knee_pos * side_sign[side],
)
pos = np.array((-0.01, -0.02, -0.08)) * side_sign[side]
euler = [-10 * (1.0 if side == '_R' else -1.0), 20, 0]
leg.add(
'geom',
name=leg.name + '0_collision',
pos=pos,
size=[0.04, 0.08],
euler=euler,
dclass='collision_primitive',
)
pos = np.array((-0.03, 0, -0.05))
euler = [-10 * (1.0 if side == '_R' else -1.0), 5, 0]
leg.add(
'geom',
name=leg.name + '1_collision',
pos=pos,
size=[0.04, 0.04],
euler=euler,
dclass='collision_primitive',
)
# Patella
if use_tendons:
# Make patella body
pass
# Lower legs:
lower_leg = {}
lower_leg_bones = [b for b in bones if 'Tibia_' in b or 'Fibula' in b]
for side in ['_L', '_R']:
body_pos = knee_pos * side_sign[side]
leg = upper_leg[side].add('body', name='lower_leg' + side, pos=body_pos)
lower_leg[side] = leg
for bone in [b for b in lower_leg_bones if side in b]:
leg.add(
'geom',
name=bone,
mesh=bone,
pos=-bone_position['Pelvis'] - upper_leg[side].pos - body_pos,
dclass='bone',
)
# Knee joints
leg.add('joint', name='knee' + side, dclass='knee', axis=(0, -1, 0))
# Ankle sites
scale = bone_size['Tibia_L']
ankle_pos = np.array((-1.27, 0.04, -0.98)) * scale
leg.add(
'site',
type='cylinder',
name='ankle' + side,
size=[0.003, 0.013],
zaxis=(0, 1, 0),
pos=ankle_pos * side_sign[side],
)
# Feet:
foot = {}
foot_bones = [b for b in bones if 'tars' in b.lower() or 'tuber' in b]
for side in ['_L', '_R']:
body_pos = ankle_pos * side_sign[side]
leg = lower_leg[side].add('body', name='foot' + side, pos=body_pos)
foot[side] = leg
for bone in [b for b in foot_bones if side in b]:
leg.add(
'geom',
name=bone,
mesh=bone,
pos=-bone_position['Pelvis']
- upper_leg[side].pos
- lower_leg[side].pos
- body_pos,
dclass='bone',
)
# Ankle joints
leg.add('joint', name='ankle' + side, dclass='ankle', axis=(0, 1, 0))
pos = np.array((-0.01, -0.005, -0.05)) * side_sign[side]
leg.add(
'geom',
name=leg.name + '_collision',
size=[0.015, 0.07],
pos=pos,
dclass='collision_primitive',
)
# Toe sites
scale = bone_size['Metatarsi_R_2']
toe_pos = np.array((-0.37, -0.2, -2.95)) * scale
leg.add(
'site',
type='cylinder',
name='toe' + side,
size=[0.003, 0.025],
zaxis=(0, 1, 0),
pos=toe_pos * side_sign[side],
)
# Toes:
toe_bones = [b for b in bones if 'Phalange' in b]
toe_geoms = []
sole_sites = []
nails = []
for side in ['_L', '_R']:
body_pos = toe_pos * side_sign[side]
foot_anchor = foot[side].add(
'body', name='foot_anchor' + side, pos=body_pos
)
foot_anchor.add(
'geom',
name=foot_anchor.name,
dclass='foot_primitive',
type='box',
size=(0.005, 0.005, 0.005),
contype=0,
conaffinity=0,
)
foot_anchor.add('site', name=foot_anchor.name, dclass='sensor')
leg = foot_anchor.add('body', name='toe' + side)
for bone in [b for b in toe_bones if side in b]:
geom = leg.add(
'geom',
name=bone,
mesh=bone,
pos=-bone_position['Pelvis']
- upper_leg[side].pos
- lower_leg[side].pos
- foot[side].pos
- body_pos,
dclass='bone',
)
if 'B_3' in bone:
nails.append(bone)
geom.dclass = 'visible_bone'
else:
toe_geoms.append(geom)
# Toe joints
leg.add('joint', name='toe' + side, dclass='toe', axis=(0, 1, 0))
# Collision geoms
leg.add(
'geom',
name=leg.name + '0_collision',
size=[0.018, 0.012],
pos=[0.015, 0, -0.02],
euler=(90, 0, 0),
dclass='foot_primitive',
)
leg.add(
'geom',
name=leg.name + '1_collision',
size=[0.01, 0.015],
pos=[0.035, 0, -0.028],
euler=(90, 0, 0),
dclass='foot_primitive',
)
leg.add(
'geom',
name=leg.name + '2_collision',
size=[0.008, 0.01],
pos=[0.045, 0, -0.03],
euler=(90, 0, 0),
dclass='foot_primitive',
)
sole = leg.add(
'site',
name='sole' + side,
size=(0.025, 0.03, 0.008),
pos=(0.026, 0, -0.033),
type='box',
dclass='sensor',
)
sole_sites.append(sole)
physics = mjcf.Physics.from_mjcf_model(model)
for side in ['_L', '_R']:
# lower leg:
leg = lower_leg[side]
leg.add(
'geom',
name=leg.name + '_collision',
pos=physics.bind(leg).ipos * 1.3,
size=[0.02, 0.1],
quat=physics.bind(leg).iquat,
dclass='collision_primitive',
)
return nails, sole_sites
| dm_control-main | dm_control/locomotion/walkers/assets/dog_v2/build_back_legs.py |
# Copyright 2023 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Make neck for the dog model."""
import collections
from dm_control import mjcf
import numpy as np
def create_neck(
model,
bone_position,
cervical_dofs_per_vertebra,
bones,
side_sign,
bone_size,
parent,
):
"""Add neck and head in the dog model.
Args:
model: model in which we want to add the neck.
bone_position: a dictionary of bones positions.
cervical_dofs_per_vertebra: a number that the determines how many dofs are
going to be used between each pair of cervical vetebrae.
bones: a list of strings with all the names of the bones.
side_sign: a dictionary with two axis representing the signs of
translations.
bone_size: dictionary containing the scale of the geometry.
parent: parent object on which we should start attaching new components.
Returns:
A list of cervical joints.
"""
# Cervical Spine
def_cervical = model.default.find('default', 'cervical')
def_cervical_extend = model.default.find('default', 'cervical_extend')
def_cervical_bend = model.default.find('default', 'cervical_bend')
def_cervical_twist = model.default.find('default', 'cervical_twist')
cervical_defaults = {
'extend': def_cervical_extend,
'bend': def_cervical_bend,
'twist': def_cervical_twist,
}
cervical_bones = ['C_' + str(i) for i in range(7, 0, -1)]
parent_pos = parent.pos
cervical_bodies = []
cervical_geoms = []
radius = 0.07
for i, bone in enumerate(cervical_bones):
bone_pos = bone_position[bone]
rel_pos = bone_pos - parent_pos
child = parent.add('body', name=bone, pos=rel_pos)
cervical_bodies.append(child)
dclass = 'bone' if i > 3 else 'light_bone'
geom = child.add('geom', name=bone, mesh=bone, pos=-bone_pos, dclass=dclass)
child.add(
'geom',
name=bone + '_collision',
type='sphere',
size=[radius],
dclass='nonself_collision_primitive',
)
radius -= 0.006
cervical_geoms.append(geom)
parent = child
parent_pos = bone_pos
# Reload
physics = mjcf.Physics.from_mjcf_model(model)
# Cervical (neck) spine joints:
cervical_axis = collections.OrderedDict()
cervical_axis['extend'] = np.array((0.0, 1.0, 0.0))
cervical_axis['bend'] = np.array((0.0, 0.0, 1.0))
cervical_axis['twist'] = np.array((1.0, 0.0, 0))
num_dofs = 0
cervical_joints = []
cervical_joint_names = []
torso = model.find('body', 'torso')
parent = torso.find('geom', 'T_1')
for i, vertebra in enumerate(cervical_bodies):
while num_dofs < (i + 1) * cervical_dofs_per_vertebra:
dof = num_dofs % 3
dof_name = list(cervical_axis.keys())[dof]
cervical_joint_names.append(vertebra.name + '_' + dof_name)
rel_pos = physics.bind(vertebra).xpos - physics.bind(parent).xpos
twist_dir = rel_pos / np.linalg.norm(rel_pos)
bend_dir = np.cross(twist_dir, cervical_axis['extend'])
cervical_axis['bend'] = bend_dir
cervical_axis['twist'] = twist_dir
joint_frame = np.vstack((twist_dir, cervical_axis['extend'], bend_dir))
joint_pos = (
def_cervical.joint.pos
* physics.bind(vertebra.find('geom', vertebra.name)).size.mean()
)
joint = vertebra.add(
'joint',
name=cervical_joint_names[-1],
dclass='cervical_' + dof_name,
axis=cervical_axis[dof_name],
pos=joint_pos.dot(joint_frame),
)
cervical_joints.append(joint)
num_dofs += 1
parent = vertebra
# Lumbar spine joints:
lumbar_axis = collections.OrderedDict()
lumbar_axis['extend'] = np.array((0.0, 1.0, 0.0))
lumbar_axis['bend'] = np.array((0.0, 0.0, 1.0))
lumbar_axis['twist'] = np.array((1.0, 0.0, 0))
# Scale joint defaults relative to 3 cervical_dofs_per_vertebra
for dof in lumbar_axis.keys():
axis_scale = 7.0 / [dof in joint for joint in cervical_joint_names].count(
True
)
cervical_defaults[dof].joint.range *= axis_scale
# Reload
physics = mjcf.Physics.from_mjcf_model(model)
# Skull
c_1 = cervical_bodies[-1]
upper_teeth = [m for m in bones if 'Top' in m]
skull_bones = upper_teeth + ['Skull', 'Ethmoid', 'Vomer', 'eye_L', 'eye_R']
skull = c_1.add(
'body', name='skull', pos=bone_position['Skull'] - physics.bind(c_1).xpos
)
skull_geoms = []
for bone in skull_bones:
geom = skull.add(
'geom',
name=bone,
mesh=bone,
pos=-bone_position['Skull'],
dclass='light_bone',
)
if 'eye' in bone:
geom.rgba = [1, 1, 1, 1]
geom.dclass = 'visible_bone'
skull_geoms.append(geom)
if bone in upper_teeth:
geom.dclass = 'visible_bone'
for side in ['_L', '_R']:
pos = np.array((0.023, -0.027, 0.01)) * side_sign[side]
skull.add(
'geom',
name='iris' + side,
type='ellipsoid',
dclass='visible_bone',
rgba=(0.45, 0.45, 0.225, 0.4),
size=(0.003, 0.007, 0.007),
pos=pos,
euler=[0, 0, -20 * (1.0 if side == '_R' else -1.0)],
)
pos = np.array((0.0215, -0.0275, 0.01)) * side_sign[side]
skull.add(
'geom',
name='pupil' + side,
type='sphere',
dclass='visible_bone',
rgba=(0, 0, 0, 1),
size=(0.003, 0, 0),
pos=pos,
)
# collision geoms
skull.add(
'geom',
name='skull0' + '_collision',
type='ellipsoid',
dclass='collision_primitive',
size=(0.06, 0.06, 0.04),
pos=(-0.02, 0, 0.01),
euler=[0, 10, 0],
)
skull.add(
'geom',
name='skull1' + '_collision',
type='capsule',
dclass='collision_primitive',
size=(0.015, 0.04, 0.015),
pos=(0.06, 0, -0.01),
euler=[0, 110, 0],
)
skull.add(
'geom',
name='skull2' + '_collision',
type='box',
dclass='collision_primitive',
size=(0.03, 0.028, 0.008),
pos=(0.02, 0, -0.03),
)
skull.add(
'geom',
name='skull3' + '_collision',
type='box',
dclass='collision_primitive',
size=(0.02, 0.018, 0.006),
pos=(0.07, 0, -0.03),
)
skull.add(
'geom',
name='skull4' + '_collision',
type='box',
dclass='collision_primitive',
size=(0.005, 0.015, 0.004),
pos=(0.095, 0, -0.03),
)
skull.add(
'joint',
name='atlas',
dclass='atlas',
pos=np.array((-0.5, 0, 0)) * bone_size['Skull'],
)
skull.add(
'site', name='head', size=(0.01, 0.01, 0.01), type='box', dclass='sensor'
)
skull.add(
'site',
name='upper_bite',
size=(0.005,),
dclass='sensor',
pos=(0.065, 0, -0.07),
)
# Jaw
lower_teeth = [m for m in bones if 'Bottom' in m]
jaw_bones = lower_teeth + ['Mandible']
jaw = skull.add(
'body', name='jaw', pos=bone_position['Mandible'] - bone_position['Skull']
)
jaw_geoms = []
for bone in jaw_bones:
geom = jaw.add(
'geom',
name=bone,
mesh=bone,
pos=-bone_position['Mandible'],
dclass='light_bone',
)
jaw_geoms.append(geom)
if bone in lower_teeth:
geom.dclass = 'visible_bone'
# Jaw collision geoms:
jaw_col_pos = [
(-0.03, 0, 0.01),
(0, 0, -0.012),
(0.03, 0, -0.028),
(0.052, 0, -0.035),
]
jaw_col_size = [
(0.03, 0.028, 0.008),
(0.02, 0.022, 0.005),
(0.02, 0.018, 0.005),
(0.015, 0.013, 0.003),
]
jaw_col_angle = [55, 30, 25, 15]
for i in range(4):
jaw.add(
'geom',
name='jaw' + str(i) + '_collision',
type='box',
dclass='collision_primitive',
size=jaw_col_size[i],
pos=jaw_col_pos[i],
euler=[0, jaw_col_angle[i], 0],
)
jaw.add(
'joint',
name='mandible',
dclass='mandible',
axis=[0, 1, 0],
pos=np.array((-0.043, 0, 0.05)),
)
jaw.add(
'site',
name='lower_bite',
size=(0.005,),
dclass='sensor',
pos=(0.063, 0, 0.005),
)
print('Make collision ellipsoids for teeth.')
visible_bones = upper_teeth + lower_teeth
for bone in visible_bones:
bone_geom = torso.find('geom', bone)
bone_geom.type = 'ellipsoid'
physics = mjcf.Physics.from_mjcf_model(model)
for bone in visible_bones:
bone_geom = torso.find('geom', bone)
pos = physics.bind(bone_geom).pos
quat = physics.bind(bone_geom).quat
size = physics.bind(bone_geom).size
bone_geom.parent.add(
'geom',
name=bone + '_collision',
dclass='tooth_primitive',
pos=pos,
size=size * 1.2,
quat=quat,
type='ellipsoid',
)
bone_geom.type = None
return cervical_joints
| dm_control-main | dm_control/locomotion/walkers/assets/dog_v2/build_neck.py |
# Copyright 2023 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Make skin for the dog model."""
import struct
from dm_control import mjcf
from dm_control.mujoco.wrapper.mjbindings import enums
import numpy as np
from scipy import spatial
def create(model, skin_msh):
"""Create and add skin in the dog model.
Args:
model: model in which we want to add the skin.
skin_msh: a binary mesh format of the skin.
"""
print('Making Skin.')
# Add skin mesh:
skinmesh = model.worldbody.add(
'geom',
name='skinmesh',
mesh='skin_msh',
type='mesh',
contype=0,
conaffinity=0,
rgba=[1, 0.5, 0.5, 0.5],
group=1,
euler=(0, 0, 90),
)
physics = mjcf.Physics.from_mjcf_model(model)
# Get skinmesh vertices in global coordinates
vertadr = physics.named.model.mesh_vertadr['skin_msh']
vertnum = physics.named.model.mesh_vertnum['skin_msh']
skin_vertices = physics.model.mesh_vert[vertadr : vertadr + vertnum, :]
skin_vertices = skin_vertices.dot(
physics.named.data.geom_xmat['skinmesh'].reshape(3, 3).T
)
skin_vertices += physics.named.data.geom_xpos['skinmesh']
skin_normals = physics.model.mesh_normal[vertadr : vertadr + vertnum, :]
skin_normals = skin_normals.dot(
physics.named.data.geom_xmat['skinmesh'].reshape(3, 3).T
)
skin_normals += physics.named.data.geom_xpos['skinmesh']
# Get skinmesh faces
faceadr = physics.named.model.mesh_faceadr['skin_msh']
facenum = physics.named.model.mesh_facenum['skin_msh']
skin_faces = physics.model.mesh_face[faceadr : faceadr + facenum, :]
# Make skin
skin = model.asset.add(
'skin', name='skin', vertex=skin_vertices.ravel(), face=skin_faces.ravel()
)
# Functions for capsule vertices
numslices = 10
numstacks = 10
numquads = 8
def hemisphere(radius):
positions = []
for az in np.linspace(0, 2 * np.pi, numslices, False):
for el in np.linspace(0, np.pi, numstacks, False):
pos = np.asarray(
[np.cos(el) * np.cos(az), np.cos(el) * np.sin(az), np.sin(el)]
)
positions.append(pos)
return radius * np.asarray(positions)
def cylinder(radius, height):
positions = []
for az in np.linspace(0, 2 * np.pi, numslices, False):
for el in np.linspace(-1, 1, numstacks):
pos = np.asarray(
[radius * np.cos(az), radius * np.sin(az), height * el]
)
positions.append(pos)
return np.asarray(positions)
def capsule(radius, height):
hp = hemisphere(radius)
cy = cylinder(radius, height)
offset = np.array((0, 0, height))
return np.unique(np.vstack((cy, hp + offset, -hp - offset)), axis=0)
def ellipsoid(size):
hp = hemisphere(1)
sphere = np.unique(np.vstack((hp, -hp)), axis=0)
return sphere * size
def box(sx, sy, sz):
positions = []
for x in np.linspace(-sx, sx, numquads + 1):
for y in np.linspace(-sy, sy, numquads + 1):
for z in np.linspace(-sz, sz, numquads + 1):
if abs(x) == sx or abs(y) == sy or abs(z) == sz:
pos = np.asarray([x, y, z])
positions.append(pos)
return np.unique(np.asarray(positions), axis=0)
# Find smallest distance between
# each skin vertex and vertices of all meshes in body i
distance = np.zeros((skin_vertices.shape[0], physics.model.nbody))
for i in range(1, physics.model.nbody):
geom_id = np.argwhere(physics.model.geom_bodyid == i).ravel()
mesh_id = physics.model.geom_dataid[geom_id]
body_verts = []
for k, gid in enumerate(geom_id):
skip = False
if physics.model.geom_type[gid] == enums.mjtGeom.mjGEOM_MESH:
vertadr = physics.model.mesh_vertadr[mesh_id[k]]
vertnum = physics.model.mesh_vertnum[mesh_id[k]]
vertices = physics.model.mesh_vert[vertadr : vertadr + vertnum, :]
elif physics.model.geom_type[gid] == enums.mjtGeom.mjGEOM_CAPSULE:
radius = physics.model.geom_size[gid, 0]
height = physics.model.geom_size[gid, 1]
vertices = capsule(radius, height)
elif physics.model.geom_type[gid] == enums.mjtGeom.mjGEOM_ELLIPSOID:
vertices = ellipsoid(physics.model.geom_size[gid])
elif physics.model.geom_type[gid] == enums.mjtGeom.mjGEOM_BOX:
vertices = box(*physics.model.geom_size[gid])
else:
skip = True
if not skip:
vertices = vertices.dot(physics.data.geom_xmat[gid].reshape(3, 3).T)
vertices += physics.data.geom_xpos[gid]
body_verts.append(vertices)
body_verts = np.vstack((body_verts))
# hull = spatial.ConvexHull(body_verts)
tree = spatial.cKDTree(body_verts)
distance[:, i], _ = tree.query(skin_vertices)
# non-KDTree implementation of the above 2 lines:
# distance[:, i] = np.amin(
# spatial.distance.cdist(skin_vertices, body_verts, 'euclidean'),
# axis=1)
# Calculate bone weights from distances
sigma = 0.015
weights = np.exp(-distance[:, 1:] / sigma)
threshold = 0.01
weights /= np.atleast_2d(np.sum(weights, axis=1)).T
weights[weights < threshold] = 0
weights /= np.atleast_2d(np.sum(weights, axis=1)).T
for i in range(1, physics.model.nbody):
vertweight = weights[weights[:, i - 1] >= threshold, i - 1]
vertid = np.argwhere(weights[:, i - 1] >= threshold).ravel()
if vertid.any():
skin.add(
'bone',
body=physics.model.id2name(i, 'body'),
bindquat=[1, 0, 0, 0],
bindpos=physics.data.xpos[i, :],
vertid=vertid,
vertweight=vertweight,
)
# Remove skinmesh
skinmesh.remove()
# Convert skin into *.skn file according to
# https://mujoco.readthedocs.io/en/latest/XMLreference.html#asset-skin
f = open('dog_skin.skn', 'w+b')
nvert = skin.vertex.size // 3
f.write(
struct.pack(
'4i', nvert, nvert, skin.face.size // 3, physics.model.nbody - 1
)
)
f.write(struct.pack(str(skin.vertex.size) + 'f', *skin.vertex))
assert physics.model.mesh_texcoord.shape[0] == physics.bind(skin_msh).vertnum
f.write(
struct.pack(str(2 * nvert) + 'f', *physics.model.mesh_texcoord.flatten())
)
f.write(struct.pack(str(skin.face.size) + 'i', *skin.face))
for bone in skin.bone:
name_length = len(bone.body)
assert name_length <= 40
f.write(
struct.pack(str(name_length) + 'c', *[s.encode() for s in bone.body])
)
f.write((40 - name_length) * b'\x00')
f.write(struct.pack('3f', *bone.bindpos))
f.write(struct.pack('4f', *bone.bindquat))
f.write(struct.pack('i', bone.vertid.size))
f.write(struct.pack(str(bone.vertid.size) + 'i', *bone.vertid))
f.write(struct.pack(str(bone.vertid.size) + 'f', *bone.vertweight))
f.close()
# Remove XML-based skin, add binary skin.
skin.remove()
| dm_control-main | dm_control/locomotion/walkers/assets/dog_v2/create_skin.py |
# Copyright 2023 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Make torque actuators for the dog model."""
import collections
def add_motors(physics, model, lumbar_joints, cervical_joints, caudal_joints):
"""Add torque motors in model.
Args:
physics: an instance of physics for the most updated model.
model: model in which we want to add motors.
lumbar_joints: a list of joints objects.
cervical_joints: a list of joints objects.
caudal_joints: a list of joints objects.
Returns:
A list of actuated joints.
"""
# Fixed Tendons:
spinal_joints = collections.OrderedDict()
spinal_joints['lumbar_'] = lumbar_joints
spinal_joints['cervical_'] = cervical_joints
spinal_joints['caudal_'] = caudal_joints
tendons = []
for region in spinal_joints.keys():
for direction in ['extend', 'bend', 'twist']:
joints = [
joint for joint in spinal_joints[region] if direction in joint.name
]
if joints:
tendon = model.tendon.add(
'fixed', name=region + direction, dclass=joints[0].dclass
)
tendons.append(tendon)
joint_inertia = physics.bind(joints).M0
coefs = joint_inertia**0.25
coefs /= coefs.sum()
coefs *= len(joints)
for i, joint in enumerate(joints):
tendon.add('joint', joint=joint, coef=coefs[i])
# Actuators:
all_spinal_joints = []
for region in spinal_joints.values():
all_spinal_joints.extend(region)
root_joint = model.find('joint', 'root')
actuated_joints = [
joint
for joint in model.find_all('joint')
if joint not in all_spinal_joints and joint is not root_joint
]
for tendon in tendons:
gain = 0.0
for joint in tendon.joint:
# joint.joint.user = physics.bind(joint.joint).damping
def_joint = model.default.find('default', joint.joint.dclass)
j_gain = def_joint.general.gainprm or def_joint.parent.general.gainprm
gain += j_gain[0] * joint.coef
gain /= len(tendon.joint)
model.actuator.add(
'general', tendon=tendon, name=tendon.name, dclass=tendon.dclass
)
for joint in actuated_joints:
model.actuator.add(
'general', joint=joint, name=joint.name, dclass=joint.dclass
)
return actuated_joints
| dm_control-main | dm_control/locomotion/walkers/assets/dog_v2/add_torque_actuators.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Initializers for the locomotion walkers."""
import abc
import numpy as np
class WalkerInitializer(metaclass=abc.ABCMeta):
"""The abstract base class for a walker initializer."""
@abc.abstractmethod
def initialize_pose(self, physics, walker, random_state):
raise NotImplementedError
class UprightInitializer(WalkerInitializer):
"""An initializer that uses the walker-declared upright pose."""
def initialize_pose(self, physics, walker, random_state):
all_joints_binding = physics.bind(walker.mjcf_model.find_all('joint'))
qpos, xpos, xquat = walker.upright_pose
if qpos is None:
walker.configure_joints(physics, all_joints_binding.qpos0)
else:
walker.configure_joints(physics, qpos)
walker.set_pose(physics, position=xpos, quaternion=xquat)
walker.set_velocity(
physics, velocity=np.zeros(3), angular_velocity=np.zeros(3))
class RandomlySampledInitializer(WalkerInitializer):
"""An initializer that random selects between many initializers."""
def __init__(self, initializers):
self._initializers = initializers
self.num_initializers = len(initializers)
def initialize_pose(self, physics, walker, random_state):
random_initalizer_idx = np.random.randint(0, self.num_initializers)
self._initializers[random_initalizer_idx].initialize_pose(
physics, walker, random_state)
class NoOpInitializer(WalkerInitializer):
"""An initializer that does nothing."""
def initialize_pose(self, physics, walker, random_state):
pass
| dm_control-main | dm_control/locomotion/walkers/initializers/__init__.py |
# Copyright 2021 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Initializers for walkers that use motion capture data."""
from dm_control.locomotion.mocap import cmu_mocap_data
from dm_control.locomotion.mocap import loader
from dm_control.locomotion.walkers import initializers
class CMUMocapInitializer(initializers.UprightInitializer):
"""Initializer that uses data from a CMU mocap dataset.
Only suitable if walker matches the motion capture data.
"""
def __init__(self, mocap_key='CMU_077_02', version='2019'):
"""Load the trajectory."""
ref_path = cmu_mocap_data.get_path_for_cmu(version)
self._loader = loader.HDF5TrajectoryLoader(ref_path)
self._trajectory = self._loader.get_trajectory(mocap_key)
def initialize_pose(self, physics, walker, random_state):
super(CMUMocapInitializer, self).initialize_pose(
physics, walker, random_state)
random_time = (self._trajectory.start_time +
self._trajectory.dt * random_state.randint(
self._trajectory.num_steps))
(walker_timestep,) = self._trajectory.get_timestep_data(
random_time).walkers
physics.bind(walker.mocap_joints).qpos = walker_timestep.joints
physics.bind(walker.mocap_joints).qvel = (
walker_timestep.joints_velocity)
walker.set_velocity(physics,
velocity=walker_timestep.velocity,
angular_velocity=walker_timestep.angular_velocity)
| dm_control-main | dm_control/locomotion/walkers/initializers/mocap.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Produces reference environments for rodent tasks."""
import functools
from dm_control import composer
from dm_control.composer.variation import distributions
from dm_control.locomotion.arenas import bowl
from dm_control.locomotion.arenas import corridors as corr_arenas
from dm_control.locomotion.arenas import floors
from dm_control.locomotion.arenas import labmaze_textures
from dm_control.locomotion.arenas import mazes
from dm_control.locomotion.props import target_sphere
from dm_control.locomotion.tasks import corridors as corr_tasks
from dm_control.locomotion.tasks import escape
from dm_control.locomotion.tasks import random_goal_maze
from dm_control.locomotion.tasks import reach
from dm_control.locomotion.walkers import rodent
_CONTROL_TIMESTEP = .02
_PHYSICS_TIMESTEP = 0.001
def rodent_escape_bowl(random_state=None):
"""Requires a rodent to climb out of a bowl-shaped terrain."""
# Build a position-controlled rodent walker.
walker = rodent.Rat(
observable_options={'egocentric_camera': dict(enabled=True)})
# Build a bowl-shaped arena.
arena = bowl.Bowl(
size=(20., 20.),
aesthetic='outdoor_natural')
# Build a task that rewards the agent for being far from the origin.
task = escape.Escape(
walker=walker,
arena=arena,
physics_timestep=_PHYSICS_TIMESTEP,
control_timestep=_CONTROL_TIMESTEP)
return composer.Environment(time_limit=20,
task=task,
random_state=random_state,
strip_singleton_obs_buffer_dim=True)
def rodent_run_gaps(random_state=None):
"""Requires a rodent to run down a corridor with gaps."""
# Build a position-controlled rodent walker.
walker = rodent.Rat(
observable_options={'egocentric_camera': dict(enabled=True)})
# Build a corridor-shaped arena with gaps, where the sizes of the gaps and
# platforms are uniformly randomized.
arena = corr_arenas.GapsCorridor(
platform_length=distributions.Uniform(.4, .8),
gap_length=distributions.Uniform(.05, .2),
corridor_width=2,
corridor_length=40,
aesthetic='outdoor_natural')
# Build a task that rewards the agent for running down the corridor at a
# specific velocity.
task = corr_tasks.RunThroughCorridor(
walker=walker,
arena=arena,
walker_spawn_position=(5, 0, 0),
walker_spawn_rotation=0,
target_velocity=1.0,
contact_termination=False,
terminate_at_height=-0.3,
physics_timestep=_PHYSICS_TIMESTEP,
control_timestep=_CONTROL_TIMESTEP)
return composer.Environment(time_limit=30,
task=task,
random_state=random_state,
strip_singleton_obs_buffer_dim=True)
def rodent_maze_forage(random_state=None):
"""Requires a rodent to find all items in a maze."""
# Build a position-controlled rodent walker.
walker = rodent.Rat(
observable_options={'egocentric_camera': dict(enabled=True)})
# Build a maze with rooms and targets.
wall_textures = labmaze_textures.WallTextures(style='style_01')
arena = mazes.RandomMazeWithTargets(
x_cells=11,
y_cells=11,
xy_scale=.5,
z_height=.3,
max_rooms=4,
room_min_size=4,
room_max_size=5,
spawns_per_room=1,
targets_per_room=3,
wall_textures=wall_textures,
aesthetic='outdoor_natural')
# Build a task that rewards the agent for obtaining targets.
task = random_goal_maze.ManyGoalsMaze(
walker=walker,
maze_arena=arena,
target_builder=functools.partial(
target_sphere.TargetSphere,
radius=0.05,
height_above_ground=.125,
rgb1=(0, 0, 0.4),
rgb2=(0, 0, 0.7)),
target_reward_scale=50.,
contact_termination=False,
physics_timestep=_PHYSICS_TIMESTEP,
control_timestep=_CONTROL_TIMESTEP)
return composer.Environment(time_limit=30,
task=task,
random_state=random_state,
strip_singleton_obs_buffer_dim=True)
def rodent_two_touch(random_state=None):
"""Requires a rodent to tap an orb, wait an interval, and tap it again."""
# Build a position-controlled rodent walker.
walker = rodent.Rat(
observable_options={'egocentric_camera': dict(enabled=True)})
# Build an open floor arena
arena = floors.Floor(
size=(10., 10.),
aesthetic='outdoor_natural')
# Build a task that rewards the walker for touching/reaching orbs with a
# specific time interval between touches
task = reach.TwoTouch(
walker=walker,
arena=arena,
target_builders=[
functools.partial(target_sphere.TargetSphereTwoTouch, radius=0.025),
],
randomize_spawn_rotation=True,
target_type_rewards=[25.],
shuffle_target_builders=False,
target_area=(1.5, 1.5),
physics_timestep=_PHYSICS_TIMESTEP,
control_timestep=_CONTROL_TIMESTEP,
)
return composer.Environment(time_limit=30,
task=task,
random_state=random_state,
strip_singleton_obs_buffer_dim=True)
| dm_control-main | dm_control/locomotion/examples/basic_rodent_2020.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for `dm_control.locomotion.examples`."""
from absl.testing import absltest
from absl.testing import parameterized
from dm_control.locomotion.examples import basic_cmu_2019
from dm_control.locomotion.examples import basic_rodent_2020
import numpy as np
_NUM_EPISODES = 5
_NUM_STEPS_PER_EPISODE = 10
class ExampleEnvironmentsTest(parameterized.TestCase):
"""Tests run on all the tasks registered."""
def _validate_observation(self, observation, observation_spec):
self.assertEqual(list(observation.keys()), list(observation_spec.keys()))
for name, array_spec in observation_spec.items():
array_spec.validate(observation[name])
def _validate_reward_range(self, reward):
self.assertIsInstance(reward, float)
self.assertBetween(reward, 0, 1)
def _validate_discount(self, discount):
self.assertIsInstance(discount, float)
self.assertBetween(discount, 0, 1)
@parameterized.named_parameters(
('cmu_humanoid_run_walls', basic_cmu_2019.cmu_humanoid_run_walls),
('cmu_humanoid_run_gaps', basic_cmu_2019.cmu_humanoid_run_gaps),
('cmu_humanoid_go_to_target', basic_cmu_2019.cmu_humanoid_go_to_target),
('cmu_humanoid_maze_forage', basic_cmu_2019.cmu_humanoid_maze_forage),
('cmu_humanoid_heterogeneous_forage',
basic_cmu_2019.cmu_humanoid_heterogeneous_forage),
('rodent_escape_bowl', basic_rodent_2020.rodent_escape_bowl),
('rodent_run_gaps', basic_rodent_2020.rodent_run_gaps),
('rodent_maze_forage', basic_rodent_2020.rodent_maze_forage),
('rodent_two_touch', basic_rodent_2020.rodent_two_touch),
)
def test_env_runs(self, env_constructor):
"""Tests that the environment runs and is coherent with its specs."""
random_state = np.random.RandomState(99)
env = env_constructor(random_state=random_state)
observation_spec = env.observation_spec()
action_spec = env.action_spec()
self.assertTrue(np.all(np.isfinite(action_spec.minimum)))
self.assertTrue(np.all(np.isfinite(action_spec.maximum)))
# Run a partial episode, check observations, rewards, discount.
for _ in range(_NUM_EPISODES):
time_step = env.reset()
for _ in range(_NUM_STEPS_PER_EPISODE):
self._validate_observation(time_step.observation, observation_spec)
if time_step.first():
self.assertIsNone(time_step.reward)
self.assertIsNone(time_step.discount)
else:
self._validate_reward_range(time_step.reward)
self._validate_discount(time_step.discount)
action = random_state.uniform(action_spec.minimum, action_spec.maximum)
env.step(action)
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/locomotion/examples/examples_test.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Walkers for Locomotion tasks."""
from dm_control.locomotion.walkers.cmu_humanoid import CMUHumanoid
from dm_control.locomotion.walkers.cmu_humanoid import CMUHumanoidPositionControlled
from dm_control.locomotion.walkers.cmu_humanoid import CMUHumanoidPositionControlledV2020
| dm_control-main | dm_control/locomotion/examples/__init__.py |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Produces reference environments for CMU humanoid tracking task."""
from dm_control import composer
from dm_control.locomotion import arenas
from dm_control.locomotion.mocap import cmu_mocap_data
from dm_control.locomotion.tasks.reference_pose import tracking
from dm_control.locomotion.walkers import cmu_humanoid
def cmu_humanoid_tracking(random_state=None):
"""Requires a CMU humanoid to run down a corridor obstructed by walls."""
# Use a position-controlled CMU humanoid walker.
walker_type = cmu_humanoid.CMUHumanoidPositionControlledV2020
# Build an empty arena.
arena = arenas.Floor()
# Build a task that rewards the agent for tracking motion capture reference
# data.
task = tracking.MultiClipMocapTracking(
walker=walker_type,
arena=arena,
ref_path=cmu_mocap_data.get_path_for_cmu(version='2020'),
dataset='walk_tiny',
ref_steps=(1, 2, 3, 4, 5),
min_steps=10,
reward_type='comic',
)
return composer.Environment(time_limit=30,
task=task,
random_state=random_state,
strip_singleton_obs_buffer_dim=True)
| dm_control-main | dm_control/locomotion/examples/cmu_2020_tracking.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Produces reference environments for CMU humanoid locomotion tasks."""
import functools
from dm_control import composer
from dm_control.composer.variation import distributions
from dm_control.locomotion.arenas import corridors as corr_arenas
from dm_control.locomotion.arenas import floors
from dm_control.locomotion.arenas import labmaze_textures
from dm_control.locomotion.arenas import mazes
from dm_control.locomotion.props import target_sphere
from dm_control.locomotion.tasks import corridors as corr_tasks
from dm_control.locomotion.tasks import go_to_target
from dm_control.locomotion.tasks import random_goal_maze
from dm_control.locomotion.walkers import cmu_humanoid
from labmaze import fixed_maze
def cmu_humanoid_run_walls(random_state=None):
"""Requires a CMU humanoid to run down a corridor obstructed by walls."""
# Build a position-controlled CMU humanoid walker.
walker = cmu_humanoid.CMUHumanoidPositionControlled(
observable_options={'egocentric_camera': dict(enabled=True)})
# Build a corridor-shaped arena that is obstructed by walls.
arena = corr_arenas.WallsCorridor(
wall_gap=4.,
wall_width=distributions.Uniform(1, 7),
wall_height=3.0,
corridor_width=10,
corridor_length=100,
include_initial_padding=False)
# Build a task that rewards the agent for running down the corridor at a
# specific velocity.
task = corr_tasks.RunThroughCorridor(
walker=walker,
arena=arena,
walker_spawn_position=(0.5, 0, 0),
target_velocity=3.0,
physics_timestep=0.005,
control_timestep=0.03)
return composer.Environment(time_limit=30,
task=task,
random_state=random_state,
strip_singleton_obs_buffer_dim=True)
def cmu_humanoid_run_gaps(random_state=None):
"""Requires a CMU humanoid to run down a corridor with gaps."""
# Build a position-controlled CMU humanoid walker.
walker = cmu_humanoid.CMUHumanoidPositionControlled(
observable_options={'egocentric_camera': dict(enabled=True)})
# Build a corridor-shaped arena with gaps, where the sizes of the gaps and
# platforms are uniformly randomized.
arena = corr_arenas.GapsCorridor(
platform_length=distributions.Uniform(.3, 2.5),
gap_length=distributions.Uniform(.5, 1.25),
corridor_width=10,
corridor_length=100)
# Build a task that rewards the agent for running down the corridor at a
# specific velocity.
task = corr_tasks.RunThroughCorridor(
walker=walker,
arena=arena,
walker_spawn_position=(0.5, 0, 0),
target_velocity=3.0,
physics_timestep=0.005,
control_timestep=0.03)
return composer.Environment(time_limit=30,
task=task,
random_state=random_state,
strip_singleton_obs_buffer_dim=True)
def cmu_humanoid_go_to_target(random_state=None):
"""Requires a CMU humanoid to go to a target."""
# Build a position-controlled CMU humanoid walker.
walker = cmu_humanoid.CMUHumanoidPositionControlled()
# Build a standard floor arena.
arena = floors.Floor()
# Build a task that rewards the agent for going to a target.
task = go_to_target.GoToTarget(
walker=walker,
arena=arena,
physics_timestep=0.005,
control_timestep=0.03)
return composer.Environment(time_limit=30,
task=task,
random_state=random_state,
strip_singleton_obs_buffer_dim=True)
def cmu_humanoid_maze_forage(random_state=None):
"""Requires a CMU humanoid to find all items in a maze."""
# Build a position-controlled CMU humanoid walker.
walker = cmu_humanoid.CMUHumanoidPositionControlled(
observable_options={'egocentric_camera': dict(enabled=True)})
# Build a maze with rooms and targets.
skybox_texture = labmaze_textures.SkyBox(style='sky_03')
wall_textures = labmaze_textures.WallTextures(style='style_01')
floor_textures = labmaze_textures.FloorTextures(style='style_01')
arena = mazes.RandomMazeWithTargets(
x_cells=11,
y_cells=11,
xy_scale=3,
max_rooms=4,
room_min_size=4,
room_max_size=5,
spawns_per_room=1,
targets_per_room=3,
skybox_texture=skybox_texture,
wall_textures=wall_textures,
floor_textures=floor_textures,
)
# Build a task that rewards the agent for obtaining targets.
task = random_goal_maze.ManyGoalsMaze(
walker=walker,
maze_arena=arena,
target_builder=functools.partial(
target_sphere.TargetSphere,
radius=0.4,
rgb1=(0, 0, 0.4),
rgb2=(0, 0, 0.7)),
target_reward_scale=50.,
physics_timestep=0.005,
control_timestep=0.03,
)
return composer.Environment(time_limit=30,
task=task,
random_state=random_state,
strip_singleton_obs_buffer_dim=True)
def cmu_humanoid_heterogeneous_forage(random_state=None):
"""Requires a CMU humanoid to find all items of a particular type in a maze."""
level = ('*******\n'
'* *\n'
'* P *\n'
'* *\n'
'* G *\n'
'* *\n'
'*******\n')
# Build a position-controlled CMU humanoid walker.
walker = cmu_humanoid.CMUHumanoidPositionControlled(
observable_options={'egocentric_camera': dict(enabled=True)})
skybox_texture = labmaze_textures.SkyBox(style='sky_03')
wall_textures = labmaze_textures.WallTextures(style='style_01')
floor_textures = labmaze_textures.FloorTextures(style='style_01')
maze = fixed_maze.FixedMazeWithRandomGoals(
entity_layer=level,
variations_layer=None,
num_spawns=1,
num_objects=6,
)
arena = mazes.MazeWithTargets(
maze=maze,
xy_scale=3.0,
z_height=2.0,
skybox_texture=skybox_texture,
wall_textures=wall_textures,
floor_textures=floor_textures,
)
task = random_goal_maze.ManyHeterogeneousGoalsMaze(
walker=walker,
maze_arena=arena,
target_builders=[
functools.partial(
target_sphere.TargetSphere,
radius=0.4,
rgb1=(0, 0.4, 0),
rgb2=(0, 0.7, 0)),
functools.partial(
target_sphere.TargetSphere,
radius=0.4,
rgb1=(0.4, 0, 0),
rgb2=(0.7, 0, 0)),
],
randomize_spawn_rotation=False,
target_type_rewards=[30., -10.],
target_type_proportions=[1, 1],
shuffle_target_builders=True,
aliveness_reward=0.01,
control_timestep=.03,
)
return composer.Environment(
time_limit=25,
task=task,
random_state=random_state,
strip_singleton_obs_buffer_dim=True)
| dm_control-main | dm_control/locomotion/examples/basic_cmu_2019.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Simple script to launch viewer with an example environment."""
from absl import app
from dm_control import viewer
from dm_control.locomotion.examples import basic_cmu_2019
def main(unused_argv):
viewer.launch(environment_loader=basic_cmu_2019.cmu_humanoid_run_gaps)
if __name__ == '__main__':
app.run(main)
| dm_control-main | dm_control/locomotion/examples/explore.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Abstract base class for a Composer task."""
import abc
import collections
import copy
from dm_control import mujoco
from dm_env import specs
def _check_timesteps_divisible(control_timestep, physics_timestep):
num_steps = control_timestep / physics_timestep
rounded_num_steps = int(round(num_steps))
if abs(num_steps - rounded_num_steps) > 1e-6:
raise ValueError(
'Control timestep should be an integer multiple of physics timestep'
': got {!r} and {!r}'.format(control_timestep, physics_timestep))
return rounded_num_steps
class Task(metaclass=abc.ABCMeta):
"""Abstract base class for a Composer task."""
@abc.abstractproperty
def root_entity(self):
"""A `base.Entity` instance for this task."""
raise NotImplementedError
def iter_entities(self):
return self.root_entity.iter_entities()
@property
def observables(self):
"""An OrderedDict of `control.Observable` instances for this task.
Task subclasses should generally NOT override this property.
This property is automatically computed by combining the observables dict
provided by each `Entity` present in this task, and any additional
observables returned via the `task_observables` property.
To provide an observable to an agent, the task code should either set
`enabled` property of an `Entity`-bound observable to `True`, or override
the `task_observables` property to provide additional observables not bound
to an `Entity`.
Returns:
An `collections.OrderedDict` mapping strings to instances of
`control.Observable`.
"""
# Make a shallow copy of the OrderedDict, not the Observables themselves.
observables = copy.copy(self.task_observables)
for entity in self.root_entity.iter_entities():
observables.update(entity.observables.as_dict())
return observables
@property
def task_observables(self):
"""An OrderedDict of task-specific `control.Observable` instances.
A task should override this property if it wants to provide additional
observables to the agent that are not already provided by any `Entity` that
forms part of the task's model. For example, this may be used to provide
observations that is derived from relative poses between two entities.
Returns:
An `collections.OrderedDict` mapping strings to instances of
`control.Observable`.
"""
return collections.OrderedDict()
def after_compile(self, physics, random_state):
"""A callback which is executed after the Mujoco Physics is recompiled.
Args:
physics: An instance of `control.Physics`.
random_state: An instance of `np.random.RandomState`.
"""
pass
def _check_root_entity(self, callee_name):
try:
_ = self.root_entity
except Exception as effect:
cause = RuntimeError(
f'call to `{callee_name}` made before `root_entity` is available')
raise effect from cause
@property
def control_timestep(self):
"""Returns the agent's control timestep for this task (in seconds)."""
self._check_root_entity('control_timestep')
if hasattr(self, '_control_timestep'):
return self._control_timestep
else:
return self.physics_timestep
@control_timestep.setter
def control_timestep(self, new_value):
"""Changes the agent's control timestep for this task.
Args:
new_value: the new control timestep (in seconds).
Raises:
ValueError: if `new_value` is set and is not divisible by
`physics_timestep`.
"""
self._check_root_entity('control_timestep')
_check_timesteps_divisible(new_value, self.physics_timestep)
self._control_timestep = new_value
@property
def physics_timestep(self):
"""Returns the physics timestep for this task (in seconds)."""
self._check_root_entity('physics_timestep')
if self.root_entity.mjcf_model.option.timestep is None:
return 0.002 # MuJoCo's default.
else:
return self.root_entity.mjcf_model.option.timestep
@physics_timestep.setter
def physics_timestep(self, new_value):
"""Changes the physics simulation timestep for this task.
Args:
new_value: the new simulation timestep (in seconds).
Raises:
ValueError: if `control_timestep` is set and is not divisible by
`new_value`.
"""
self._check_root_entity('physics_timestep')
if hasattr(self, '_control_timestep'):
_check_timesteps_divisible(self._control_timestep, new_value)
self.root_entity.mjcf_model.option.timestep = new_value
def set_timesteps(self, control_timestep, physics_timestep):
"""Changes the agent's control timestep and physics simulation timestep.
This is equivalent to modifying `control_timestep` and `physics_timestep`
simultaneously. The divisibility check is performed between the two
new values.
Args:
control_timestep: the new agent's control timestep (in seconds).
physics_timestep: the new physics simulation timestep (in seconds).
Raises:
ValueError: if `control_timestep` is not divisible by `physics_timestep`.
"""
self._check_root_entity('set_timesteps')
_check_timesteps_divisible(control_timestep, physics_timestep)
self.root_entity.mjcf_model.option.timestep = physics_timestep
self._control_timestep = control_timestep
@property
def physics_steps_per_control_step(self):
"""Returns number of physics steps per agent's control step."""
return _check_timesteps_divisible(
self.control_timestep, self.physics_timestep)
def action_spec(self, physics):
"""Returns a `BoundedArray` spec matching the `Physics` actuators.
BoundedArray.name should contain a tab-separated list of actuator names.
When overloading this method, non-MuJoCo actuators should be added to the
top of the list when possible, as a matter of convention.
Args:
physics: used to query actuator names in the model.
"""
names = [physics.model.id2name(i, 'actuator') or str(i)
for i in range(physics.model.nu)]
action_spec = mujoco.action_spec(physics)
return specs.BoundedArray(shape=action_spec.shape,
dtype=action_spec.dtype,
minimum=action_spec.minimum,
maximum=action_spec.maximum,
name='\t'.join(names))
def get_reward_spec(self):
"""Optional method to define non-scalar rewards for a `Task`."""
return None
def get_discount_spec(self):
"""Optional method to define non-scalar discounts for a `Task`."""
return None
def initialize_episode_mjcf(self, random_state):
"""Modifies the MJCF model of this task before the next episode begins.
The Environment calls this method and recompiles the physics
if necessary before calling `initialize_episode`.
Args:
random_state: An instance of `np.random.RandomState`.
"""
pass
def initialize_episode(self, physics, random_state):
"""Modifies the physics state before the next episode begins.
The Environment calls this method after `initialize_episode_mjcf`, and also
after the physics has been recompiled if necessary.
Args:
physics: An instance of `control.Physics`.
random_state: An instance of `np.random.RandomState`.
"""
pass
def before_step(self, physics, action, random_state):
"""A callback which is executed before an agent control step.
The default implementation sets the control signal for the actuators in
`physics` to be equal to `action`. Subclasses that override this method
should ensure that the overriding method also sets the control signal before
returning, either by calling `super().before_step`, or by setting
the control signal explicitly (e.g. in order to create a non-trivial mapping
between `action` and the control signal).
Args:
physics: An instance of `control.Physics`.
action: A NumPy array corresponding to agent actions.
random_state: An instance of `np.random.RandomState` (unused).
"""
del random_state # Unused.
physics.set_control(action)
def before_substep(self, physics, action, random_state):
"""A callback which is executed before a simulation step.
Actuation can be set, or overridden, in this callback.
Args:
physics: An instance of `control.Physics`.
action: A NumPy array corresponding to agent actions.
random_state: An instance of `np.random.RandomState`.
"""
pass
def after_substep(self, physics, random_state):
"""A callback which is executed after a simulation step.
Args:
physics: An instance of `control.Physics`.
random_state: An instance of `np.random.RandomState`.
"""
pass
def after_step(self, physics, random_state):
"""A callback which is executed after an agent control step.
Args:
physics: An instance of `control.Physics`.
random_state: An instance of `np.random.RandomState`.
"""
pass
@abc.abstractmethod
def get_reward(self, physics):
"""Calculates the reward signal given the physics state.
Args:
physics: A Physics object.
Returns:
A float
"""
raise NotImplementedError
def should_terminate_episode(self, physics): # pylint: disable=unused-argument
"""Determines whether the episode should terminate given the physics state.
Args:
physics: A Physics object
Returns:
A boolean
"""
return False
def get_discount(self, physics): # pylint: disable=unused-argument
"""Calculates the reward discount factor given the physics state.
Args:
physics: A Physics object
Returns:
A float
"""
return 1.0
class NullTask(Task):
"""A class that wraps a single `Entity` into a `Task` with no reward."""
def __init__(self, root_entity):
self._root_entity = root_entity
@property
def root_entity(self):
return self._root_entity
def get_reward(self, physics):
return 0.0
| dm_control-main | dm_control/composer/task.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for Entity and Task hooks in an Environment."""
from absl.testing import absltest
from dm_control import composer
from dm_control.composer import hooks_test_utils
import numpy as np
class EnvironmentHooksTest(hooks_test_utils.HooksTestMixin, absltest.TestCase):
def testEnvironmentHooksScheduling(self):
env = composer.Environment(self.task)
for hook_name in composer.HOOK_NAMES:
env.add_extra_hook(hook_name, getattr(self.extra_hooks, hook_name))
for _ in range(self.num_episodes):
with self.track_episode():
env.reset()
for _ in range(self.steps_per_episode):
env.step([0.1, 0.2, 0.3, 0.4])
np.testing.assert_array_equal(env.physics.data.ctrl,
[0.1, 0.2, 0.3, 0.4])
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/composer/environment_hooks_test.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Decorators for Entity methods returning elements and observables."""
import abc
import threading
class cached_property(property): # pylint: disable=invalid-name
"""A property that is evaluated only once per object instance."""
def __init__(self, func, doc=None):
super().__init__(fget=func, doc=doc)
self.lock = threading.RLock()
def __get__(self, obj, cls):
if obj is None:
return self
name = self.fget.__name__
obj_dict = obj.__dict__
try:
# Try returning a precomputed value without locking first.
# Profiling shows that the lock takes up a non-trivial amount of time.
return obj_dict[name]
except KeyError:
# The value hasn't been computed, now we have to lock.
with self.lock:
try:
# Check again whether another thread has already computed the value.
return obj_dict[name]
except KeyError:
# Otherwise call the function, cache the result, and return it
return obj_dict.setdefault(name, self.fget(obj))
# A decorator for base.Observables methods returning an observable. This
# decorator should be used by abstract base classes to indicate sub-classes need
# to implement a corresponding @observavble annotated method.
abstract_observable = abc.abstractproperty # pylint: disable=invalid-name
class observable(cached_property): # pylint: disable=invalid-name
"""A decorator for base.Observables methods returning an observable.
The body of the decorated function is evaluated at Entity construction time
and the observable is cached.
"""
pass
| dm_control-main | dm_control/composer/define.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Module defining constant values for Composer."""
SENSOR_SITES_GROUP = 4
| dm_control-main | dm_control/composer/constants.py |
# Copyright 2018-2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Module containing abstract base classes for Composer environments."""
from dm_control.composer.arena import Arena
from dm_control.composer.constants import * # pylint: disable=wildcard-import
from dm_control.composer.define import cached_property
from dm_control.composer.define import observable
from dm_control.composer.entity import Entity
from dm_control.composer.entity import FreePropObservableMixin
from dm_control.composer.entity import ModelWrapperEntity
from dm_control.composer.entity import Observables
from dm_control.composer.environment import Environment
from dm_control.composer.environment import EpisodeInitializationError
from dm_control.composer.environment import HOOK_NAMES
from dm_control.composer.environment import ObservationPadding
from dm_control.composer.initializer import Initializer
from dm_control.composer.robot import Robot
from dm_control.composer.task import NullTask
from dm_control.composer.task import Task
| dm_control-main | dm_control/composer/__init__.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for composer.Entity."""
import itertools
from absl.testing import absltest
from absl.testing import parameterized
from dm_control import mjcf
from dm_control.composer import arena
from dm_control.composer import define
from dm_control.composer import entity
from dm_control.composer.observation.observable import base as observable
import numpy as np
_NO_ROTATION = (1, 0, 0, 0) # Tests support for non-arrays and non-floats.
_NINETY_DEGREES_ABOUT_X = np.array(
[np.cos(np.pi / 4), np.sin(np.pi / 4), 0., 0.])
_NINETY_DEGREES_ABOUT_Y = np.array(
[np.cos(np.pi / 4), 0., np.sin(np.pi / 4), 0.])
_NINETY_DEGREES_ABOUT_Z = np.array(
[np.cos(np.pi / 4), 0., 0., np.sin(np.pi / 4)])
_FORTYFIVE_DEGREES_ABOUT_X = np.array(
[np.cos(np.pi / 8), np.sin(np.pi / 8), 0., 0.])
_TEST_ROTATIONS = [
# Triplets of original rotation, new rotation and final rotation.
(None, _NO_ROTATION, _NO_ROTATION),
(_NO_ROTATION, _NINETY_DEGREES_ABOUT_Z, _NINETY_DEGREES_ABOUT_Z),
(_FORTYFIVE_DEGREES_ABOUT_X, _NINETY_DEGREES_ABOUT_Y,
np.array([0.65328, 0.2706, 0.65328, -0.2706])),
]
def _param_product(**param_lists):
keys, values = zip(*param_lists.items())
for combination in itertools.product(*values):
yield dict(zip(keys, combination))
class TestEntity(entity.Entity):
"""Simple test entity that does nothing but declare some observables."""
def _build(self, name='test_entity'):
self._mjcf_root = mjcf.element.RootElement(model=name)
self._mjcf_root.worldbody.add('geom', type='sphere', size=(0.1,))
def _build_observables(self):
return TestEntityObservables(self)
@property
def mjcf_model(self):
return self._mjcf_root
class TestEntityObservables(entity.Observables):
"""Trivial observables for the test entity."""
@define.observable
def observable0(self):
return observable.Generic(lambda phys: 0.0)
@define.observable
def observable1(self):
return observable.Generic(lambda phys: 1.0)
class EntityTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.entity = TestEntity()
def testNumObservables(self):
"""Tests that the observables dict has the right number of entries."""
self.assertLen(self.entity.observables.as_dict(), 2)
def testObservableNames(self):
"""Tests that the observables dict keys correspond to the observable names.
"""
obs = self.entity.observables.as_dict()
self.assertIn('observable0', obs)
self.assertIn('observable1', obs)
subentity = TestEntity(name='subentity')
self.entity.attach(subentity)
self.assertIn('subentity/observable0', subentity.observables.as_dict())
self.assertEqual(subentity.observables.dict_keys.observable0,
'subentity/observable0')
self.assertIn('observable0', dir(subentity.observables.dict_keys))
self.assertIn('subentity/observable1', subentity.observables.as_dict())
self.assertEqual(subentity.observables.dict_keys.observable1,
'subentity/observable1')
self.assertIn('observable1', dir(subentity.observables.dict_keys))
def testEnableDisableObservables(self):
"""Test the enabling and disable functionality for observables."""
all_obs = self.entity.observables.as_dict()
self.entity.observables.enable_all()
for obs in all_obs.values():
self.assertTrue(obs.enabled)
self.entity.observables.disable_all()
for obs in all_obs.values():
self.assertFalse(obs.enabled)
self.entity.observables.observable0.enabled = True
self.assertTrue(all_obs['observable0'].enabled)
def testObservableDefaultOptions(self):
corruptor = lambda x: x
options = {
'update_interval': 2,
'buffer_size': 10,
'delay': 1,
'aggregator': 'max',
'corruptor': corruptor,
'enabled': True
}
self.entity.observables.set_options(options)
for obs in self.entity.observables.as_dict().values():
self.assertEqual(obs.update_interval, 2)
self.assertEqual(obs.delay, 1)
self.assertEqual(obs.buffer_size, 10)
self.assertEqual(obs.aggregator, observable.AGGREGATORS['max'])
self.assertEqual(obs.corruptor, corruptor)
self.assertTrue(obs.enabled)
def testObservablePartialDefaultOptions(self):
options = {'update_interval': 2, 'delay': 1}
self.entity.observables.set_options(options)
for obs in self.entity.observables.as_dict().values():
self.assertEqual(obs.update_interval, 2)
self.assertEqual(obs.delay, 1)
self.assertIsNone(obs.buffer_size)
self.assertIsNone(obs.aggregator)
self.assertIsNone(obs.corruptor)
def testObservableOptionsInvalidName(self):
options = {'asdf': None}
with self.assertRaisesRegex(KeyError, 'No observable with name \'asdf\''):
self.entity.observables.set_options(options)
def testObservableInvalidOptions(self):
options = {'observable0': {'asdf': 2}}
with self.assertRaisesRegex(AttributeError,
'Cannot add attribute asdf in configure.'):
self.entity.observables.set_options(options)
def testObservableOptions(self):
options = {
'observable0': {
'update_interval': 2,
'delay': 3
},
'observable1': {
'update_interval': 4,
'delay': 5
}
}
self.entity.observables.set_options(options)
observables = self.entity.observables.as_dict()
self.assertEqual(observables['observable0'].update_interval, 2)
self.assertEqual(observables['observable0'].delay, 3)
self.assertIsNone(observables['observable0'].buffer_size)
self.assertIsNone(observables['observable0'].aggregator)
self.assertIsNone(observables['observable0'].corruptor)
self.assertFalse(observables['observable0'].enabled)
self.assertEqual(observables['observable1'].update_interval, 4)
self.assertEqual(observables['observable1'].delay, 5)
self.assertIsNone(observables['observable1'].buffer_size)
self.assertIsNone(observables['observable1'].aggregator)
self.assertIsNone(observables['observable1'].corruptor)
self.assertFalse(observables['observable1'].enabled)
def testObservableOptionsEntityConstructor(self):
options = {
'observable0': {
'update_interval': 2,
'delay': 3
},
'observable1': {
'update_interval': 4,
'delay': 5
}
}
ent = TestEntity(observable_options=options)
observables = ent.observables.as_dict()
self.assertEqual(observables['observable0'].update_interval, 2)
self.assertEqual(observables['observable0'].delay, 3)
self.assertIsNone(observables['observable0'].buffer_size)
self.assertIsNone(observables['observable0'].aggregator)
self.assertIsNone(observables['observable0'].corruptor)
self.assertFalse(observables['observable0'].enabled)
self.assertEqual(observables['observable1'].update_interval, 4)
self.assertEqual(observables['observable1'].delay, 5)
self.assertIsNone(observables['observable1'].buffer_size)
self.assertIsNone(observables['observable1'].aggregator)
self.assertIsNone(observables['observable1'].corruptor)
self.assertFalse(observables['observable1'].enabled)
def testObservablePartialOptions(self):
options = {'observable0': {'update_interval': 2, 'delay': 3}}
self.entity.observables.set_options(options)
observables = self.entity.observables.as_dict()
self.assertEqual(observables['observable0'].update_interval, 2)
self.assertEqual(observables['observable0'].delay, 3)
self.assertIsNone(observables['observable0'].buffer_size)
self.assertIsNone(observables['observable0'].aggregator)
self.assertIsNone(observables['observable0'].corruptor)
self.assertFalse(observables['observable0'].enabled)
self.assertEqual(observables['observable1'].update_interval, 1)
self.assertIsNone(observables['observable1'].delay)
self.assertIsNone(observables['observable1'].buffer_size)
self.assertIsNone(observables['observable1'].aggregator)
self.assertIsNone(observables['observable1'].corruptor)
self.assertFalse(observables['observable1'].enabled)
def testAttach(self):
entities = [TestEntity() for _ in range(4)]
entities[0].attach(entities[1])
entities[1].attach(entities[2])
entities[0].attach(entities[3])
self.assertIsNone(entities[0].parent)
self.assertIs(entities[1].parent, entities[0])
self.assertIs(entities[2].parent, entities[1])
self.assertIs(entities[3].parent, entities[0])
self.assertIsNone(entities[0].mjcf_model.parent_model)
self.assertIs(entities[1].mjcf_model.parent_model, entities[0].mjcf_model)
self.assertIs(entities[2].mjcf_model.parent_model, entities[1].mjcf_model)
self.assertIs(entities[3].mjcf_model.parent_model, entities[0].mjcf_model)
self.assertEqual(list(entities[0].iter_entities()), entities)
def testDetach(self):
entities = [TestEntity() for _ in range(4)]
entities[0].attach(entities[1])
entities[1].attach(entities[2])
entities[0].attach(entities[3])
entities[1].detach()
with self.assertRaisesRegex(RuntimeError, 'not attached'):
entities[1].detach()
self.assertIsNone(entities[0].parent)
self.assertIsNone(entities[1].parent)
self.assertIs(entities[2].parent, entities[1])
self.assertIs(entities[3].parent, entities[0])
self.assertIsNone(entities[0].mjcf_model.parent_model)
self.assertIsNone(entities[1].mjcf_model.parent_model)
self.assertIs(entities[2].mjcf_model.parent_model, entities[1].mjcf_model)
self.assertIs(entities[3].mjcf_model.parent_model, entities[0].mjcf_model)
self.assertEqual(list(entities[0].iter_entities()),
[entities[0], entities[3]])
def testIterEntitiesExcludeSelf(self):
entities = [TestEntity() for _ in range(4)]
entities[0].attach(entities[1])
entities[1].attach(entities[2])
entities[0].attach(entities[3])
self.assertEqual(
list(entities[0].iter_entities(exclude_self=True)), entities[1:])
def testGlobalVectorToLocalFrame(self):
parent = TestEntity()
parent.mjcf_model.worldbody.add(
'site', xyaxes=[0, 1, 0, -1, 0, 0]).attach(self.entity.mjcf_model)
physics = mjcf.Physics.from_mjcf_model(parent.mjcf_model)
# 3D vectors
np.testing.assert_allclose(
self.entity.global_vector_to_local_frame(physics, [0, 1, 0]),
[1, 0, 0], atol=1e-10)
np.testing.assert_allclose(
self.entity.global_vector_to_local_frame(physics, [-1, 0, 0]),
[0, 1, 0], atol=1e-10)
np.testing.assert_allclose(
self.entity.global_vector_to_local_frame(physics, [0, 0, 1]),
[0, 0, 1], atol=1e-10)
# 2D vectors; z-component is ignored
np.testing.assert_allclose(
self.entity.global_vector_to_local_frame(physics, [0, 1]),
[1, 0], atol=1e-10)
np.testing.assert_allclose(
self.entity.global_vector_to_local_frame(physics, [-1, 0]),
[0, 1], atol=1e-10)
def testGlobalMatrixToLocalFrame(self):
parent = TestEntity()
parent.mjcf_model.worldbody.add(
'site', xyaxes=[0, 1, 0, -1, 0, 0]).attach(self.entity.mjcf_model)
physics = mjcf.Physics.from_mjcf_model(parent.mjcf_model)
rotation_atob = np.array([[0, 1, 0], [0, 0, -1], [-1, 0, 0]])
ego_rotation_atob = np.array([[0, 0, -1], [0, -1, 0], [-1, 0, 0]])
np.testing.assert_allclose(
self.entity.global_xmat_to_local_frame(physics, rotation_atob),
ego_rotation_atob, atol=1e-10)
flat_rotation_atob = np.reshape(rotation_atob, -1)
flat_rotation_ego_atob = np.reshape(ego_rotation_atob, -1)
np.testing.assert_allclose(
self.entity.global_xmat_to_local_frame(
physics, flat_rotation_atob),
flat_rotation_ego_atob, atol=1e-10)
@parameterized.parameters(*_param_product(
position=[None, [1., 0., -1.]],
quaternion=[None, _FORTYFIVE_DEGREES_ABOUT_X, _NINETY_DEGREES_ABOUT_Z],
freejoint=[False, True],
))
def testSetPose(self, position, quaternion, freejoint):
# Setup entity.
test_arena = arena.Arena()
subentity = TestEntity(name='subentity')
frame = test_arena.attach(subentity)
if freejoint:
frame.add('freejoint')
physics = mjcf.Physics.from_mjcf_model(test_arena.mjcf_model)
if quaternion is None:
ground_truth_quat = _NO_ROTATION
else:
ground_truth_quat = quaternion
if position is None:
ground_truth_pos = np.zeros(shape=(3,))
else:
ground_truth_pos = position
subentity.set_pose(physics, position=position, quaternion=quaternion)
np.testing.assert_allclose(physics.bind(frame).xpos, ground_truth_pos)
np.testing.assert_allclose(physics.bind(frame).xquat, ground_truth_quat)
@parameterized.parameters(*_param_product(
original_position=[[-2, -1, -1.], [1., 0., -1.]],
position=[None, [1., 0., -1.]],
original_quaternion=_TEST_ROTATIONS[0],
quaternion=_TEST_ROTATIONS[1],
expected_quaternion=_TEST_ROTATIONS[2],
freejoint=[False, True],
))
def testShiftPose(self, original_position, position, original_quaternion,
quaternion, expected_quaternion, freejoint):
# Setup entity.
test_arena = arena.Arena()
subentity = TestEntity(name='subentity')
frame = test_arena.attach(subentity)
if freejoint:
frame.add('freejoint')
physics = mjcf.Physics.from_mjcf_model(test_arena.mjcf_model)
# Set the original position
subentity.set_pose(
physics, position=original_position, quaternion=original_quaternion)
if position is None:
ground_truth_pos = original_position
else:
ground_truth_pos = original_position + np.array(position)
subentity.shift_pose(physics, position=position, quaternion=quaternion)
np.testing.assert_array_equal(physics.bind(frame).xpos, ground_truth_pos)
updated_quat = physics.bind(frame).xquat
np.testing.assert_array_almost_equal(updated_quat, expected_quaternion,
1e-4)
@parameterized.parameters(False, True)
def testShiftPoseWithVelocity(self, rotate_velocity):
# Setup entity.
test_arena = arena.Arena()
subentity = TestEntity(name='subentity')
frame = test_arena.attach(subentity)
frame.add('freejoint')
physics = mjcf.Physics.from_mjcf_model(test_arena.mjcf_model)
# Set the original position
subentity.set_pose(physics, position=[0., 0., 0.])
# Set velocity in y dim.
subentity.set_velocity(physics, [0., 1., 0.])
# Rotate the entity around the z axis.
subentity.shift_pose(
physics, quaternion=[0., 0., 0., 1.], rotate_velocity=rotate_velocity)
physics.forward()
updated_position, _ = subentity.get_pose(physics)
if rotate_velocity:
# Should not have moved in the y dim.
np.testing.assert_array_almost_equal(updated_position[1], 0.)
else:
# Should not have moved in the x dim.
np.testing.assert_array_almost_equal(updated_position[0], 0.)
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/composer/entity_test.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Module defining the abstract initializer."""
import abc
class Initializer(metaclass=abc.ABCMeta):
"""The abstract base class for an initializer."""
@abc.abstractmethod
def __call__(self, physics, random_state):
raise NotImplementedError
| dm_control-main | dm_control/composer/initializer.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Utilities for testing environment hooks."""
import collections
import contextlib
import inspect
from dm_control import composer
from dm_control import mjcf
def add_bodies_and_actuators(mjcf_model, num_actuators):
if num_actuators % 2:
raise ValueError('num_actuators is not a multiple of 2')
for _ in range(num_actuators // 2):
body = mjcf_model.worldbody.add('body')
body.add('inertial', pos=[0, 0, 0], mass=1, diaginertia=[1, 1, 1])
joint_x = body.add('joint', axis=[1, 0, 0])
mjcf_model.actuator.add('position', joint=joint_x)
joint_y = body.add('joint', axis=[0, 1, 0])
mjcf_model.actuator.add('position', joint=joint_y)
class HooksTracker:
"""Helper class for tracking call order of callbacks."""
def __init__(self, test_case, physics_timestep, control_timestep,
*args, **kwargs):
super().__init__(*args, **kwargs)
self.tracked = False
self._test_case = test_case
self._call_count = collections.defaultdict(lambda: 0)
self._physics_timestep = physics_timestep
self._physics_steps_per_control_step = (
round(int(control_timestep / physics_timestep)))
mro = inspect.getmro(type(self))
self._has_super = mro[mro.index(HooksTracker) + 1] != object
def assertEqual(self, actual, expected, msg=''):
msg = '{}: {}: {!r} != {!r}'.format(type(self), msg, actual, expected)
self._test_case.assertEqual(actual, expected, msg)
def assertHooksNotCalled(self, *hook_names):
for hook_name in hook_names:
self.assertEqual(
self._call_count[hook_name], 0,
'assertHooksNotCalled: hook_name = {!r}'.format(hook_name))
def assertHooksCalledOnce(self, *hook_names):
for hook_name in hook_names:
self.assertEqual(
self._call_count[hook_name], 1,
'assertHooksCalledOnce: hook_name = {!r}'.format(hook_name))
def assertCompleteEpisode(self, control_steps):
self.assertHooksCalledOnce('initialize_episode_mjcf',
'after_compile',
'initialize_episode')
physics_steps = control_steps * self._physics_steps_per_control_step
self.assertEqual(self._call_count['before_step'], control_steps)
self.assertEqual(self._call_count['before_substep'], physics_steps)
self.assertEqual(self._call_count['after_substep'], physics_steps)
self.assertEqual(self._call_count['after_step'], control_steps)
def assertPhysicsStepCountEqual(self, physics, expected_count):
actual_count = int(round(physics.time() / self._physics_timestep))
self.assertEqual(actual_count, expected_count)
def reset_call_counts(self):
self._call_count = collections.defaultdict(lambda: 0)
def initialize_episode_mjcf(self, random_state):
"""Implements `initialize_episode_mjcf` Composer callback."""
if self._has_super:
super().initialize_episode_mjcf(random_state)
if not self.tracked:
return
self.assertHooksNotCalled('after_compile',
'initialize_episode',
'before_step',
'before_substep',
'after_substep',
'after_step')
self._call_count['initialize_episode_mjcf'] += 1
def after_compile(self, physics, random_state):
"""Implements `after_compile` Composer callback."""
if self._has_super:
super().after_compile(physics, random_state)
if not self.tracked:
return
self.assertHooksCalledOnce('initialize_episode_mjcf')
self.assertHooksNotCalled('initialize_episode',
'before_step',
'before_substep',
'after_substep',
'after_step')
# Number of physics steps is always consistent with `before_substep`.
self.assertPhysicsStepCountEqual(physics,
self._call_count['before_substep'])
self._call_count['after_compile'] += 1
def initialize_episode(self, physics, random_state):
"""Implements `initialize_episode` Composer callback."""
if self._has_super:
super().initialize_episode(physics, random_state)
if not self.tracked:
return
self.assertHooksCalledOnce('initialize_episode_mjcf',
'after_compile')
self.assertHooksNotCalled('before_step',
'before_substep',
'after_substep',
'after_step')
# Number of physics steps is always consistent with `before_substep`.
self.assertPhysicsStepCountEqual(physics,
self._call_count['before_substep'])
self._call_count['initialize_episode'] += 1
def before_step(self, physics, *args):
"""Implements `before_step` Composer callback."""
if self._has_super:
super().before_step(physics, *args)
if not self.tracked:
return
self.assertHooksCalledOnce('initialize_episode_mjcf',
'after_compile',
'initialize_episode')
# `before_step` is only called in between complete control steps.
self.assertEqual(
self._call_count['after_step'], self._call_count['before_step'])
# Complete control steps imply complete physics steps.
self.assertEqual(
self._call_count['after_substep'], self._call_count['before_substep'])
# Number of physics steps is always consistent with `before_substep`.
self.assertPhysicsStepCountEqual(physics,
self._call_count['before_substep'])
self._call_count['before_step'] += 1
def before_substep(self, physics, *args):
"""Implements `before_substep` Composer callback."""
if self._has_super:
super().before_substep(physics, *args)
if not self.tracked:
return
self.assertHooksCalledOnce('initialize_episode_mjcf',
'after_compile',
'initialize_episode')
# We are inside a partial control step, so `after_step` should lag behind.
self.assertEqual(
self._call_count['after_step'], self._call_count['before_step'] - 1)
# `before_substep` is only called in between complete physics steps.
self.assertEqual(
self._call_count['after_substep'], self._call_count['before_substep'])
# Number of physics steps is always consistent with `before_substep`.
self.assertPhysicsStepCountEqual(
physics, self._call_count['before_substep'])
self._call_count['before_substep'] += 1
def after_substep(self, physics, random_state):
"""Implements `after_substep` Composer callback."""
if self._has_super:
super().after_substep(physics, random_state)
if not self.tracked:
return
self.assertHooksCalledOnce('initialize_episode_mjcf',
'after_compile',
'initialize_episode')
# We are inside a partial control step, so `after_step` should lag behind.
self.assertEqual(
self._call_count['after_step'], self._call_count['before_step'] - 1)
# We are inside a partial physics step, so `after_substep` should be behind.
self.assertEqual(self._call_count['after_substep'],
self._call_count['before_substep'] - 1)
# Number of physics steps is always consistent with `before_substep`.
self.assertPhysicsStepCountEqual(
physics, self._call_count['before_substep'])
self._call_count['after_substep'] += 1
def after_step(self, physics, random_state):
"""Implements `after_step` Composer callback."""
if self._has_super:
super().after_step(physics, random_state)
if not self.tracked:
return
self.assertHooksCalledOnce('initialize_episode_mjcf',
'after_compile',
'initialize_episode')
# We are inside a partial control step, so `after_step` should lag behind.
self.assertEqual(
self._call_count['after_step'], self._call_count['before_step'] - 1)
# `after_step` is only called in between complete physics steps.
self.assertEqual(
self._call_count['after_substep'], self._call_count['before_substep'])
# Number of physics steps is always consistent with `before_substep`.
self.assertPhysicsStepCountEqual(
physics, self._call_count['before_substep'])
# Check that the number of physics steps is consistent with control steps.
self.assertEqual(
self._call_count['before_substep'],
self._call_count['before_step'] * self._physics_steps_per_control_step)
self._call_count['after_step'] += 1
class TrackedEntity(HooksTracker, composer.Entity):
"""A `composer.Entity` that tracks call order of callbacks."""
def _build(self, name):
self._mjcf_root = mjcf.RootElement(model=name)
@property
def mjcf_model(self):
return self._mjcf_root
@property
def name(self):
return self._mjcf_root.model
class TrackedTask(HooksTracker, composer.NullTask):
"""A `composer.Task` that tracks call order of callbacks."""
def __init__(self, physics_timestep, control_timestep, *args, **kwargs):
super().__init__(
physics_timestep=physics_timestep,
control_timestep=control_timestep,
*args,
**kwargs)
self.set_timesteps(
physics_timestep=physics_timestep, control_timestep=control_timestep)
add_bodies_and_actuators(self.root_entity.mjcf_model, num_actuators=4)
class HooksTestMixin:
"""A mixin for an `absltest.TestCase` to track call order of callbacks."""
def setUp(self):
"""Sets up the test case."""
super().setUp()
self.num_episodes = 5
self.steps_per_episode = 100
self.control_timestep = 0.05
self.physics_timestep = 0.002
self.extra_hooks = HooksTracker(physics_timestep=self.physics_timestep,
control_timestep=self.control_timestep,
test_case=self)
self.entities = []
for i in range(9):
self.entities.append(TrackedEntity(name='entity_{}'.format(i),
physics_timestep=self.physics_timestep,
control_timestep=self.control_timestep,
test_case=self))
########################################
# Make the following entity hierarchy #
# 0 #
# 1 2 3 #
# 4 5 6 7 #
# 8 #
########################################
self.entities[4].attach(self.entities[8])
self.entities[1].attach(self.entities[4])
self.entities[1].attach(self.entities[5])
self.entities[0].attach(self.entities[1])
self.entities[2].attach(self.entities[6])
self.entities[2].attach(self.entities[7])
self.entities[0].attach(self.entities[2])
self.entities[0].attach(self.entities[3])
self.task = TrackedTask(root_entity=self.entities[0],
physics_timestep=self.physics_timestep,
control_timestep=self.control_timestep,
test_case=self)
@contextlib.contextmanager
def track_episode(self):
tracked_objects = [self.task, self.extra_hooks] + self.entities
for obj in tracked_objects:
obj.reset_call_counts()
obj.tracked = True
yield
for obj in tracked_objects:
obj.assertCompleteEpisode(self.steps_per_episode)
obj.tracked = False
| dm_control-main | dm_control/composer/hooks_test_utils.py |
# Copyright 2018-2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""RL environment classes for Composer tasks."""
import enum
import warnings
import weakref
from absl import logging
from dm_control import mjcf
from dm_control.composer import observation
from dm_control.rl import control
import dm_env
import numpy as np
warnings.simplefilter('always', DeprecationWarning)
_STEPS_LOGGING_INTERVAL = 10000
HOOK_NAMES = ('initialize_episode_mjcf',
'after_compile',
'initialize_episode',
'before_step',
'before_substep',
'after_substep',
'after_step')
_empty_function = lambda: None
def _empty_function_with_docstring():
"""Some docstring."""
_EMPTY_CODE = _empty_function.__code__.co_code
_EMPTY_WITH_DOCSTRING_CODE = _empty_function_with_docstring.__code__.co_code
def _callable_is_trivial(f):
return (f.__code__.co_code == _EMPTY_CODE or
f.__code__.co_code == _EMPTY_WITH_DOCSTRING_CODE)
class ObservationPadding(enum.Enum):
INITIAL_VALUE = -1
ZERO = 0
class EpisodeInitializationError(RuntimeError):
"""Raised by a `composer.Task` when it fails to initialize an episode."""
class _Hook:
__slots__ = ('entity_hooks', 'extra_hooks')
def __init__(self):
self.entity_hooks = []
self.extra_hooks = []
class _EnvironmentHooks:
"""Helper object that scans and memoizes various hooks in a task.
This object exist to ensure that we do not incur a substantial overhead in
calling empty entity hooks in more complicated tasks.
"""
__slots__ = (('_task', '_episode_step_count') +
tuple('_' + hook_name for hook_name in HOOK_NAMES))
def __init__(self, task):
self._task = task
self._episode_step_count = 0
for hook_name in HOOK_NAMES:
slot_name = '_' + hook_name
setattr(self, slot_name, _Hook())
self.refresh_entity_hooks()
def refresh_entity_hooks(self):
"""Scans and memoizes all non-trivial entity hooks."""
for hook_name in HOOK_NAMES:
hooks = []
for entity in self._task.root_entity.iter_entities():
entity_hook = getattr(entity, hook_name)
# Ignore any hook that is a no-op to avoid function call overhead.
if not _callable_is_trivial(entity_hook):
hooks.append(entity_hook)
getattr(self, '_' + hook_name).entity_hooks = hooks
def add_extra_hook(self, hook_name, hook_callable):
if hook_name not in HOOK_NAMES:
raise ValueError('{!r} is not a valid hook name'.format(hook_name))
if not callable(hook_callable):
raise ValueError('{!r} is not a callable'.format(hook_callable))
getattr(self, '_' + hook_name).extra_hooks.append(hook_callable)
def initialize_episode_mjcf(self, random_state):
self._task.initialize_episode_mjcf(random_state)
for entity_hook in self._initialize_episode_mjcf.entity_hooks:
entity_hook(random_state)
for extra_hook in self._initialize_episode_mjcf.extra_hooks:
extra_hook(random_state)
def after_compile(self, physics, random_state):
self._task.after_compile(physics, random_state)
for entity_hook in self._after_compile.entity_hooks:
entity_hook(physics, random_state)
for extra_hook in self._after_compile.extra_hooks:
extra_hook(physics, random_state)
def initialize_episode(self, physics, random_state):
self._episode_step_count = 0
self._task.initialize_episode(physics, random_state)
for entity_hook in self._initialize_episode.entity_hooks:
entity_hook(physics, random_state)
for extra_hook in self._initialize_episode.extra_hooks:
extra_hook(physics, random_state)
def before_step(self, physics, action, random_state):
self._episode_step_count += 1
if self._episode_step_count % _STEPS_LOGGING_INTERVAL == 0:
logging.info('The current episode has been running for %d steps.',
self._episode_step_count)
self._task.before_step(physics, action, random_state)
for entity_hook in self._before_step.entity_hooks:
entity_hook(physics, random_state)
for extra_hook in self._before_step.extra_hooks:
extra_hook(physics, action, random_state)
def before_substep(self, physics, action, random_state):
self._task.before_substep(physics, action, random_state)
for entity_hook in self._before_substep.entity_hooks:
entity_hook(physics, random_state)
for extra_hooks in self._before_substep.extra_hooks:
extra_hooks(physics, action, random_state)
def after_substep(self, physics, random_state):
self._task.after_substep(physics, random_state)
for entity_hook in self._after_substep.entity_hooks:
entity_hook(physics, random_state)
for extra_hook in self._after_substep.extra_hooks:
extra_hook(physics, random_state)
def after_step(self, physics, random_state):
self._task.after_step(physics, random_state)
for entity_hook in self._after_step.entity_hooks:
entity_hook(physics, random_state)
for extra_hook in self._after_step.extra_hooks:
extra_hook(physics, random_state)
class _CommonEnvironment:
"""Common components for RL environments."""
def __init__(self, task, time_limit=float('inf'), random_state=None,
n_sub_steps=None,
raise_exception_on_physics_error=True,
strip_singleton_obs_buffer_dim=False,
delayed_observation_padding=ObservationPadding.ZERO,
legacy_step: bool = True):
"""Initializes an instance of `_CommonEnvironment`.
Args:
task: Instance of `composer.base.Task`.
time_limit: (optional) A float, the time limit in seconds beyond which an
episode is forced to terminate.
random_state: Optional, either an int seed or an `np.random.RandomState`
object. If None (default), the random number generator will self-seed
from a platform-dependent source of entropy.
n_sub_steps: (DEPRECATED) An integer, number of physics steps to take per
agent control step. New code should instead override the
`control_substep` property of the task.
raise_exception_on_physics_error: (optional) A boolean, indicating whether
`PhysicsError` should be raised as an exception. If `False`, physics
errors will result in the current episode being terminated with a
warning logged, and a new episode started.
strip_singleton_obs_buffer_dim: (optional) A boolean, if `True`,
the array shape of observations with `buffer_size == 1` will not have a
leading buffer dimension.
delayed_observation_padding: (optional) An `ObservationPadding` enum value
specifying the padding behavior of the initial buffers for delayed
observables. If `ZERO` then the buffer is initially filled with zeroes.
If `INITIAL_VALUE` then the buffer is initially filled with the first
observation values.
legacy_step: If True, steps the state with up-to-date position and
velocity dependent fields. See Page 6 of
https://arxiv.org/abs/2006.12983 for more information.
"""
if not isinstance(delayed_observation_padding, ObservationPadding):
raise ValueError(
f'`delayed_observation_padding` should be an `ObservationPadding` '
f'enum value: got {delayed_observation_padding}')
self._task = task
if not isinstance(random_state, np.random.RandomState):
self._random_state = np.random.RandomState(random_state)
else:
self._random_state = random_state
self._hooks = _EnvironmentHooks(self._task)
self._time_limit = time_limit
self._raise_exception_on_physics_error = raise_exception_on_physics_error
self._strip_singleton_obs_buffer_dim = strip_singleton_obs_buffer_dim
self._delayed_observation_padding = delayed_observation_padding
self._legacy_step = legacy_step
if n_sub_steps is not None:
warnings.simplefilter('once', DeprecationWarning)
warnings.warn('The `n_sub_steps` argument is deprecated. Please override '
'the `control_timestep` property of the task instead.',
DeprecationWarning)
self._overridden_n_sub_steps = n_sub_steps
self._recompile_physics_and_update_observables()
def add_extra_hook(self, hook_name, hook_callable):
self._hooks.add_extra_hook(hook_name, hook_callable)
def _recompile_physics_and_update_observables(self):
"""Sets up the environment for latest MJCF model from the task."""
self._physics_proxy = None
self._recompile_physics()
if isinstance(self._physics, weakref.ProxyType):
self._physics_proxy = self._physics
else:
self._physics_proxy = weakref.proxy(self._physics)
if self._overridden_n_sub_steps is not None:
self._n_sub_steps = self._overridden_n_sub_steps
else:
self._n_sub_steps = self._task.physics_steps_per_control_step
self._hooks.refresh_entity_hooks()
self._hooks.after_compile(self._physics_proxy, self._random_state)
self._observation_updater = self._make_observation_updater()
self._observation_updater.reset(self._physics_proxy, self._random_state)
def _recompile_physics(self):
"""Creates a new Physics using the latest MJCF model from the task."""
if getattr(self, '_physics', None):
self._physics.free()
self._physics = mjcf.Physics.from_mjcf_model(
self._task.root_entity.mjcf_model)
self._physics.legacy_step = self._legacy_step
def _make_observation_updater(self):
pad_with_initial_value = (
self._delayed_observation_padding == ObservationPadding.INITIAL_VALUE)
return observation.Updater(
self._task.observables, self._task.physics_steps_per_control_step,
self._strip_singleton_obs_buffer_dim, pad_with_initial_value)
@property
def physics(self):
"""Returns a `weakref.ProxyType` pointing to the current `mjcf.Physics`.
Note that the underlying `mjcf.Physics` will be destroyed whenever the MJCF
model is recompiled. It is therefore unsafe for external objects to hold a
reference to `environment.physics`. Attempting to access attributes of a
dead `Physics` instance will result in a `ReferenceError`.
"""
return self._physics_proxy
@property
def task(self):
return self._task
@property
def random_state(self):
return self._random_state
def control_timestep(self):
"""Returns the interval between agent actions in seconds."""
if self._overridden_n_sub_steps is not None:
return self.physics.timestep() * self._overridden_n_sub_steps
else:
return self.task.control_timestep
class Environment(_CommonEnvironment, dm_env.Environment):
"""Reinforcement learning environment for Composer tasks."""
def __init__(self, task, time_limit=float('inf'), random_state=None,
n_sub_steps=None,
raise_exception_on_physics_error=True,
strip_singleton_obs_buffer_dim=False,
max_reset_attempts=1,
delayed_observation_padding=ObservationPadding.ZERO,
legacy_step: bool = True):
"""Initializes an instance of `Environment`.
Args:
task: Instance of `composer.base.Task`.
time_limit: (optional) A float, the time limit in seconds beyond which
an episode is forced to terminate.
random_state: (optional) an int seed or `np.random.RandomState` instance.
n_sub_steps: (DEPRECATED) An integer, number of physics steps to take per
agent control step. New code should instead override the
`control_substep` property of the task.
raise_exception_on_physics_error: (optional) A boolean, indicating whether
`PhysicsError` should be raised as an exception. If `False`, physics
errors will result in the current episode being terminated with a
warning logged, and a new episode started.
strip_singleton_obs_buffer_dim: (optional) A boolean, if `True`,
the array shape of observations with `buffer_size == 1` will not have a
leading buffer dimension.
max_reset_attempts: (optional) Maximum number of times to try resetting
the environment. If an `EpisodeInitializationError` is raised
during this process, an environment reset is reattempted up to this
number of times. If this count is exceeded then the most recent
exception will be allowed to propagate. Defaults to 1, i.e. no failure
is allowed.
delayed_observation_padding: (optional) An `ObservationPadding` enum value
specifying the padding behavior of the initial buffers for delayed
observables. If `ZERO` then the buffer is initially filled with zeroes.
If `INITIAL_VALUE` then the buffer is initially filled with the first
observation values.
legacy_step: If True, steps the state with up-to-date position and
velocity dependent fields.
"""
super().__init__(
task=task,
time_limit=time_limit,
random_state=random_state,
n_sub_steps=n_sub_steps,
raise_exception_on_physics_error=raise_exception_on_physics_error,
strip_singleton_obs_buffer_dim=strip_singleton_obs_buffer_dim,
delayed_observation_padding=delayed_observation_padding,
legacy_step=legacy_step)
self._max_reset_attempts = max_reset_attempts
self._reset_next_step = True
def reset(self):
failed_attempts = 0
while True:
try:
return self._reset_attempt()
except EpisodeInitializationError as e:
failed_attempts += 1
if failed_attempts < self._max_reset_attempts:
logging.error('Error during episode reset: %s', repr(e))
else:
raise
def _reset_attempt(self):
self._hooks.initialize_episode_mjcf(self._random_state)
self._recompile_physics_and_update_observables()
with self._physics.reset_context():
self._hooks.initialize_episode(self._physics_proxy, self._random_state)
self._observation_updater.reset(self._physics_proxy, self._random_state)
self._reset_next_step = False
return dm_env.TimeStep(
step_type=dm_env.StepType.FIRST,
reward=None,
discount=None,
observation=self._observation_updater.get_observation())
# TODO(b/129061424): Remove this method.
def step_spec(self):
"""DEPRECATED: please use `reward_spec` and `discount_spec` instead."""
warnings.warn('`step_spec` is deprecated, please use `reward_spec` and '
'`discount_spec` instead.', DeprecationWarning)
if (self._task.get_reward_spec() is None or
self._task.get_discount_spec() is None):
raise NotImplementedError
return dm_env.TimeStep(
step_type=None,
reward=self._task.get_reward_spec(),
discount=self._task.get_discount_spec(),
observation=self._observation_updater.observation_spec(),
)
def step(self, action):
"""Updates the environment using the action and returns a `TimeStep`."""
if self._reset_next_step:
self._reset_next_step = False
return self.reset()
self._hooks.before_step(self._physics_proxy, action, self._random_state)
self._observation_updater.prepare_for_next_control_step()
try:
for i in range(self._n_sub_steps):
self._substep(action)
# The final observation update must happen after all the hooks in
# `self._hooks.after_step` is called. Otherwise, if any of these hooks
# modify the physics state then we might capture an observation that is
# inconsistent with the final physics state.
if i < self._n_sub_steps - 1:
self._observation_updater.update()
physics_is_divergent = False
except control.PhysicsError as e:
if not self._raise_exception_on_physics_error:
logging.warning(e)
physics_is_divergent = True
else:
raise
self._hooks.after_step(self._physics_proxy, self._random_state)
self._observation_updater.update()
if not physics_is_divergent:
reward = self._task.get_reward(self._physics_proxy)
discount = self._task.get_discount(self._physics_proxy)
terminating = (
self._task.should_terminate_episode(self._physics_proxy)
or self._physics.time() >= self._time_limit
)
else:
reward = 0.0
discount = 0.0
terminating = True
obs = self._observation_updater.get_observation()
if not terminating:
return dm_env.TimeStep(dm_env.StepType.MID, reward, discount, obs)
else:
self._reset_next_step = True
return dm_env.TimeStep(dm_env.StepType.LAST, reward, discount, obs)
def _substep(self, action):
self._hooks.before_substep(
self._physics_proxy, action, self._random_state)
self._physics.step()
self._hooks.after_substep(self._physics_proxy, self._random_state)
def action_spec(self):
"""Returns the action specification for this environment."""
return self._task.action_spec(self._physics_proxy)
def reward_spec(self):
"""Describes the reward returned by this environment.
This will be the output of `self.task.reward_spec()` if it is not None,
otherwise it will be the default spec returned by
`dm_env.Environment.reward_spec()`.
Returns:
A `specs.Array` instance, or a nested dict, list or tuple of
`specs.Array`s.
"""
task_reward_spec = self._task.get_reward_spec()
if task_reward_spec is not None:
return task_reward_spec
else:
return super().reward_spec()
def discount_spec(self):
"""Describes the discount returned by this environment.
This will be the output of `self.task.discount_spec()` if it is not None,
otherwise it will be the default spec returned by
`dm_env.Environment.discount_spec()`.
Returns:
A `specs.Array` instance, or a nested dict, list or tuple of
`specs.Array`s.
"""
task_discount_spec = self._task.get_discount_spec()
if task_discount_spec is not None:
return task_discount_spec
else:
return super().discount_spec()
def observation_spec(self):
"""Returns the observation specification for this environment.
Returns:
An `OrderedDict` mapping observation name to `specs.Array` containing
observation shape and dtype.
"""
return self._observation_updater.observation_spec()
| dm_control-main | dm_control/composer/environment.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Module defining the abstract entity class."""
import abc
import collections
import os
import weakref
from absl import logging
from dm_control import mjcf
from dm_control.composer import define
from dm_control.mujoco.wrapper import mjbindings
import numpy as np
_OPTION_KEYS = set(['update_interval', 'buffer_size', 'delay', 'aggregator',
'corruptor', 'enabled'])
_NO_ATTACHMENT_FRAME = 'No attachment frame found.'
# The component order differs from that used by the open-source `tf` package.
def _multiply_quaternions(quat1, quat2):
result = np.empty_like(quat1)
mjbindings.mjlib.mju_mulQuat(result, quat1, quat2)
return result
def _rotate_vector(vec, quat):
"""Rotates a vector by the given quaternion."""
result = np.empty_like(vec)
mjbindings.mjlib.mju_rotVecQuat(result, vec, quat)
return result
class _ObservableKeys:
"""Helper object that implements the `observables.dict_keys` functionality."""
def __init__(self, entity, observables):
self._entity = entity
self._observables = observables
def __getattr__(self, name):
try:
model_identifier = self._entity.mjcf_model.full_identifier
except AttributeError as exc:
raise ValueError(
'cannot retrieve the full identifier of mjcf_model') from exc
return os.path.join(model_identifier, name)
def __dir__(self):
out = set(self._observables.keys())
out.update(dir(super()))
return list(out)
class Observables:
"""Base-class for Entity observables.
Subclasses should declare getter methods annotated with @define.observable
decorator and returning an observable object.
"""
def __init__(self, entity):
self._entity = weakref.proxy(entity)
self._observables = collections.OrderedDict()
self._keys_helper = _ObservableKeys(self._entity, self._observables)
# Ensure consistent ordering.
for attr_name in sorted(dir(type(self))):
type_attr = getattr(type(self), attr_name)
if isinstance(type_attr, define.observable):
self._observables[attr_name] = getattr(self, attr_name)
@property
def dict_keys(self):
return self._keys_helper
def as_dict(self, fully_qualified=True):
"""Returns an OrderedDict of observables belonging to this Entity.
The returned observables will include any added using the _add_observable
method, as well as any generated by a method decorated with the
@define.observable annotation.
Args:
fully_qualified: (bool) Whether the dict keys should be prefixed with the
parent entity's full model identifier.
"""
if fully_qualified:
# We need to make sure that this property doesn't raise an AttributeError,
# otherwise __getattr__ is executed and we get a very funky error.
try:
model_identifier = self._entity.mjcf_model.full_identifier
except AttributeError as exc:
raise ValueError(
'Cannot retrieve the full identifier of mjcf_model.') from exc
return collections.OrderedDict(
[(os.path.join(model_identifier, name), observable)
for name, observable in self._observables.items()])
else:
# Return a copy to prevent dict being edited.
return self._observables.copy()
def get_observable(self, name, name_fully_qualified=False):
"""Returns the observable with the given name.
Args:
name: (str) The identifier of the observable.
name_fully_qualified: (bool) Whether the provided name is prefixed by the
model's full identifier.
"""
if name_fully_qualified:
try:
model_identifier = self._entity.mjcf_model.full_identifier
except AttributeError as exc:
raise ValueError(
'Cannot retrieve the full identifier of mjcf_model.') from exc
return self._observables[name.replace(model_identifier, '')]
else:
return self._observables[name]
def set_options(self, options):
"""Configure Observables with an options dict.
Args:
options: A dict of dicts of configuration options keyed on
observable names, or a dict of configuration options, which will
propagate those options to all observables.
"""
if options is None:
options = {}
elif options.keys() and set(options.keys()).issubset(_OPTION_KEYS):
options = dict([(key, options) for key in self._observables.keys()])
for obs_key, obs_options in options.items():
try:
obs = self._observables[obs_key]
except KeyError as exc:
raise KeyError('No observable with name {!r}'.format(obs_key)) from exc
obs.configure(**obs_options)
def enable_all(self):
"""Enable all observables of this entity."""
for obs in self._observables.values():
obs.enabled = True
def disable_all(self):
"""Disable all observables of this entity."""
for obs in self._observables.values():
obs.enabled = False
def add_observable(self, name, observable, enabled=True):
self._observables[name] = observable
self._observables[name].enabled = enabled
class FreePropObservableMixin(metaclass=abc.ABCMeta):
"""Enforce observables of a free-moving object."""
@property
@abc.abstractmethod
def position(self):
pass
@property
@abc.abstractmethod
def orientation(self):
pass
@property
@abc.abstractmethod
def linear_velocity(self):
pass
@property
@abc.abstractmethod
def angular_velocity(self):
pass
class Entity(metaclass=abc.ABCMeta):
"""The abstract base class for an entity in a Composer environment."""
def __init__(self, *args, **kwargs):
"""Entity constructor.
Subclasses should not override this method, instead implement a _build
method.
Args:
*args: Arguments passed through to the _build method.
**kwargs: Keyword arguments. Passed through to the _build method, apart
from the following.
`observable_options`: A dictionary of Observable
configuration options.
"""
self._post_init_hooks = []
self._parent = None
self._attached = []
try:
observable_options = kwargs.pop('observable_options')
except KeyError:
observable_options = None
self._build(*args, **kwargs)
self._observables = self._build_observables()
self._observables.set_options(observable_options)
@abc.abstractmethod
def _build(self, *args, **kwargs):
"""Entity initialization method to be overridden by subclasses."""
raise NotImplementedError
def _build_observables(self):
"""Entity observables initialization method.
Returns:
An object subclassing the Observables class.
"""
return Observables(self)
def iter_entities(self, exclude_self=False):
"""An iterator that recursively iterates through all attached entities.
Args:
exclude_self: (optional) Whether to exclude this `Entity` itself from the
iterator.
Yields:
If `exclude_self` is `False`, the first value yielded is this Entity
itself. The following Entities are then yielded recursively in a
depth-first fashion, following the order in which the Entities are
attached.
"""
if not exclude_self:
yield self
for attached_entity in self._attached:
for attached_entity_of_attached_entity in attached_entity.iter_entities():
yield attached_entity_of_attached_entity
@property
def observables(self):
"""The observables defined by this entity."""
return self._observables
def initialize_episode_mjcf(self, random_state):
"""Callback executed when the MJCF model is modified between episodes."""
pass
def after_compile(self, physics, random_state):
"""Callback executed after the Mujoco Physics is recompiled."""
pass
def initialize_episode(self, physics, random_state):
"""Callback executed during episode initialization."""
pass
def before_step(self, physics, random_state):
"""Callback executed before an agent control step."""
pass
def before_substep(self, physics, random_state):
"""Callback executed before a simulation step."""
pass
def after_substep(self, physics, random_state):
"""A callback which is executed after a simulation step."""
pass
def after_step(self, physics, random_state):
"""Callback executed after an agent control step."""
pass
@property
@abc.abstractmethod
def mjcf_model(self):
raise NotImplementedError
def attach(self, entity, attach_site=None):
"""Attaches an `Entity` without any additional degrees of freedom.
Args:
entity: The `Entity` to attach.
attach_site: (optional) The site to which to attach the entity's model. If
not set, defaults to self.attachment_site.
Returns:
The frame of the attached model.
"""
if attach_site is None:
attach_site = self.attachment_site
frame = attach_site.attach(entity.mjcf_model)
self._attached.append(entity)
entity._parent = weakref.ref(self) # pylint: disable=protected-access
return frame
def detach(self):
"""Detaches this entity if it has previously been attached."""
if self._parent is not None:
parent = self._parent() # pylint: disable=not-callable
if parent: # Weakref might dereference to None during garbage collection.
self.mjcf_model.detach()
parent._attached.remove(self) # pylint: disable=protected-access
self._parent = None
else:
raise RuntimeError('Cannot detach an entity that is not attached.')
@property
def parent(self):
"""Returns the `Entity` to which this entity is attached, or `None`."""
return self._parent() if self._parent else None # pylint: disable=not-callable
@property
def attachment_site(self):
return self.mjcf_model
@property
def root_body(self):
if self.parent:
return mjcf.get_attachment_frame(self.mjcf_model)
else:
return self.mjcf_model.worldbody
def global_vector_to_local_frame(self, physics, vec_in_world_frame):
"""Linearly transforms a world-frame vector into entity's local frame.
Note that this function does not perform an affine transformation of the
vector. In other words, the input vector is assumed to be specified with
respect to the same origin as this entity's local frame. This function
can also be applied to matrices whose innermost dimensions are either 2 or
3. In this case, a matrix with the same leading dimensions is returned
where the innermost vectors are replaced by their values computed in the
local frame.
Args:
physics: An `mjcf.Physics` instance.
vec_in_world_frame: A NumPy array with last dimension of shape (2,) or
(3,) that represents a vector quantity in the world frame.
Returns:
The same quantity as `vec_in_world_frame` but reexpressed in this
entity's local frame. The returned np.array has the same shape as
np.asarray(vec_in_world_frame).
Raises:
ValueError: if `vec_in_world_frame` does not have shape ending with (2,)
or (3,).
"""
vec_in_world_frame = np.asarray(vec_in_world_frame)
xmat = np.reshape(physics.bind(self.root_body).xmat, (3, 3))
# The ordering of the np.dot is such that the transformation holds for any
# matrix whose final dimensions are (2,) or (3,).
if vec_in_world_frame.shape[-1] == 2:
return np.dot(vec_in_world_frame, xmat[:2, :2])
elif vec_in_world_frame.shape[-1] == 3:
return np.dot(vec_in_world_frame, xmat)
else:
raise ValueError('`vec_in_world_frame` should have shape with final '
'dimension 2 or 3: got {}'.format(
vec_in_world_frame.shape))
def global_xmat_to_local_frame(self, physics, xmat):
"""Transforms another entity's `xmat` into this entity's local frame.
This function takes another entity's (E) xmat, which is an SO(3) matrix
from E's frame to the world frame, and turns it to a matrix that transforms
from E's frame into this entity's local frame.
Args:
physics: An `mjcf.Physics` instance.
xmat: A NumPy array of shape (3, 3) or (9,) that represents another
entity's xmat.
Returns:
The `xmat` reexpressed in this entity's local frame. The returned
np.array has the same shape as np.asarray(xmat).
Raises:
ValueError: if `xmat` does not have shape (3, 3) or (9,).
"""
xmat = np.asarray(xmat)
input_shape = xmat.shape
if xmat.shape == (9,):
xmat = np.reshape(xmat, (3, 3))
self_xmat = np.reshape(physics.bind(self.root_body).xmat, (3, 3))
if xmat.shape == (3, 3):
return np.reshape(np.dot(self_xmat.T, xmat), input_shape)
else:
raise ValueError('`xmat` should have shape (3, 3) or (9,): got {}'.format(
xmat.shape))
def get_pose(self, physics):
"""Get the position and orientation of this entity relative to its parent.
Note that the semantics differ slightly depending on whether or not the
entity has a free joint:
* If it has a free joint the position and orientation are always given in
global coordinates.
* If the entity is fixed or attached with a different joint type then the
position and orientation are given relative to the parent frame.
For entities that are either attached directly to the worldbody, or to other
entities that are positioned at the global origin (e.g. the arena) the
global and relative poses are equivalent.
Args:
physics: An instance of `mjcf.Physics`.
Returns:
A 2-tuple where the first entry is a (3,) numpy array representing the
position and the second is a (4,) numpy array representing orientation as
a quaternion.
Raises:
RuntimeError: If the entity is not attached.
"""
root_joint = mjcf.get_frame_freejoint(self.mjcf_model)
if root_joint:
position = physics.bind(root_joint).qpos[:3]
quaternion = physics.bind(root_joint).qpos[3:]
else:
attachment_frame = mjcf.get_attachment_frame(self.mjcf_model)
if attachment_frame is None:
raise RuntimeError(_NO_ATTACHMENT_FRAME)
position = physics.bind(attachment_frame).pos
quaternion = physics.bind(attachment_frame).quat
return position, quaternion
def set_pose(self, physics, position=None, quaternion=None):
"""Sets position and/or orientation of this entity relative to its parent.
If the entity is attached with a free joint, this method will set the
respective DoFs of the joint. If the entity is either fixed or attached with
a different joint type, this method will update the position and/or
quaternion of the attachment frame.
Note that the semantics differ slightly between the two cases: the DoFs of a
free body are specified in global coordinates, whereas the position of a
non-free body is specified in relative coordinates with respect to the
parent frame. However, for entities that are either attached directly to the
worldbody, or to other entities that are positioned at the global origin
(e.g. the arena), there is no difference between the two cases.
Args:
physics: An instance of `mjcf.Physics`.
position: (optional) A NumPy array of size 3.
quaternion: (optional) A NumPy array of size 4.
Raises:
RuntimeError: If the entity is not attached.
"""
root_joint = mjcf.get_frame_freejoint(self.mjcf_model)
if root_joint:
if position is not None:
physics.bind(root_joint).qpos[:3] = position
if quaternion is not None:
physics.bind(root_joint).qpos[3:] = quaternion
else:
attachment_frame = mjcf.get_attachment_frame(self.mjcf_model)
if attachment_frame is None:
raise RuntimeError(_NO_ATTACHMENT_FRAME)
if position is not None:
physics.bind(attachment_frame).pos = position
if quaternion is not None:
normalised_quaternion = quaternion / np.linalg.norm(quaternion)
physics.bind(attachment_frame).quat = normalised_quaternion
def shift_pose(self,
physics,
position=None,
quaternion=None,
rotate_velocity=False):
"""Shifts the position and/or orientation from its current configuration.
This is a convenience function that performs the same operation as
`set_pose`, but where the specified `position` is added to the current
position, and the specified `quaternion` is premultiplied to the current
quaternion.
Args:
physics: An instance of `mjcf.Physics`.
position: (optional) A NumPy array of size 3.
quaternion: (optional) A NumPy array of size 4.
rotate_velocity: (optional) A bool, whether to shift the current linear
velocity along with the pose. This will rotate the current linear
velocity, which is expressed relative to the world frame. The angular
velocity, which is expressed relative to the local frame is left
unchanged.
Raises:
RuntimeError: If the entity is not attached.
"""
current_position, current_quaternion = self.get_pose(physics)
new_position, new_quaternion = None, None
if position is not None:
new_position = current_position + position
if quaternion is not None:
quaternion = np.array(quaternion, dtype=np.float64, copy=False)
new_quaternion = _multiply_quaternions(quaternion, current_quaternion)
root_joint = mjcf.get_frame_freejoint(self.mjcf_model)
if root_joint and rotate_velocity:
# Rotate the linear velocity. The angular velocity (qvel[3:])
# is left unchanged, as it is expressed in the local frame.
# When rotatating the body frame the angular velocity already
# tracks the rotation but the linear velocity does not.
velocity = physics.bind(root_joint).qvel[:3]
rotated_velocity = _rotate_vector(velocity, quaternion)
self.set_velocity(physics, rotated_velocity)
self.set_pose(physics, new_position, new_quaternion)
def get_velocity(self, physics):
"""Gets the linear and angular velocity of this free entity.
Args:
physics: An instance of `mjcf.Physics`.
Returns:
A 2-tuple where the first entry is a (3,) numpy array representing the
linear velocity and the second is a (3,) numpy array representing the
angular velocity.
"""
root_joint = mjcf.get_frame_freejoint(self.mjcf_model)
if root_joint:
velocity = physics.bind(root_joint).qvel[:3]
angular_velocity = physics.bind(root_joint).qvel[3:]
return velocity, angular_velocity
else:
raise ValueError('get_velocity cannot be used on a non-free entity')
def set_velocity(self, physics, velocity=None, angular_velocity=None):
"""Sets the linear velocity and/or angular velocity of this free entity.
If the entity is attached with a free joint, this method will set the
respective DoFs of the joint. Otherwise a warning is logged.
Args:
physics: An instance of `mjcf.Physics`.
velocity: (optional) A NumPy array of size 3 specifying the
linear velocity.
angular_velocity: (optional) A NumPy array of size 3 specifying the
angular velocity
"""
root_joint = mjcf.get_frame_freejoint(self.mjcf_model)
if root_joint:
if velocity is not None:
physics.bind(root_joint).qvel[:3] = velocity
if angular_velocity is not None:
physics.bind(root_joint).qvel[3:] = angular_velocity
else:
logging.warning('Cannot set velocity on Entity with no free joint.')
def configure_joints(self, physics, position):
"""Configures this entity's internal joints.
The default implementation of this method simply sets the `qpos` of all
joints in this entity to the values specified in the `position` argument.
Entity subclasses with actuated joints may override this method to achieve a
stable reconfiguration of joint positions, for example the control signal
of position actuators may be changed to match the new joint positions.
Args:
physics: An instance of `mjcf.Physics`.
position: The desired position of this entity's joints.
"""
joints = self.mjcf_model.find_all('joint', exclude_attachments=True)
physics.bind(joints).qpos = position
class ModelWrapperEntity(Entity):
"""An entity class that wraps an MJCF model without any additional logic."""
def _build(self, mjcf_model):
self._mjcf_model = mjcf_model
@property
def mjcf_model(self):
return self._mjcf_model
| dm_control-main | dm_control/composer/entity.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for dm_control.composer.environment."""
from absl.testing import absltest
from absl.testing import parameterized
from dm_control import composer
from dm_control import mjcf
from dm_control.composer.observation import observable
import dm_env
import mock
import numpy as np
class DummyTask(composer.NullTask):
def __init__(self):
null_entity = composer.ModelWrapperEntity(mjcf.RootElement())
super().__init__(null_entity)
@property
def task_observables(self):
time = observable.Generic(lambda physics: physics.time())
time.enabled = True
return {'time': time}
class DummyTaskWithResetFailures(DummyTask):
def __init__(self, num_reset_failures):
super().__init__()
self.num_reset_failures = num_reset_failures
self.reset_counter = 0
def initialize_episode_mjcf(self, random_state):
self.reset_counter += 1
def initialize_episode(self, physics, random_state):
if self.reset_counter <= self.num_reset_failures:
raise composer.EpisodeInitializationError()
class EnvironmentTest(parameterized.TestCase):
def test_failed_resets(self):
total_reset_failures = 5
env_reset_attempts = 2
task = DummyTaskWithResetFailures(num_reset_failures=total_reset_failures)
env = composer.Environment(task, max_reset_attempts=env_reset_attempts)
for _ in range(total_reset_failures // env_reset_attempts):
with self.assertRaises(composer.EpisodeInitializationError):
env.reset()
env.reset() # should not raise an exception
self.assertEqual(task.reset_counter, total_reset_failures + 1)
@parameterized.parameters(
dict(name='reward_spec', defined_in_task=True),
dict(name='reward_spec', defined_in_task=False),
dict(name='discount_spec', defined_in_task=True),
dict(name='discount_spec', defined_in_task=False))
def test_get_spec(self, name, defined_in_task):
task = DummyTask()
env = composer.Environment(task)
with mock.patch.object(task, 'get_' + name) as mock_task_get_spec:
if defined_in_task:
expected_spec = mock.Mock()
mock_task_get_spec.return_value = expected_spec
else:
expected_spec = getattr(dm_env.Environment, name)(env)
mock_task_get_spec.return_value = None
spec = getattr(env, name)()
mock_task_get_spec.assert_called_once_with()
self.assertSameStructure(spec, expected_spec)
def test_can_provide_observation(self):
task = DummyTask()
env = composer.Environment(task)
obs = env.reset().observation
self.assertLen(obs, 1)
np.testing.assert_array_equal(obs['time'], env.physics.time())
for _ in range(20):
obs = env.step([]).observation
self.assertLen(obs, 1)
np.testing.assert_array_equal(obs['time'], env.physics.time())
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/composer/environment_test.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Module defining the abstract robot class."""
import abc
from dm_control.composer import entity
import numpy as np
DOWN_QUATERNION = np.array([0., 0.70710678118, 0.70710678118, 0.])
class Robot(entity.Entity, metaclass=abc.ABCMeta):
"""The abstract base class for robots."""
@property
@abc.abstractmethod
def actuators(self):
"""Returns the actuator elements of the robot."""
raise NotImplementedError
| dm_control-main | dm_control/composer/robot.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""The base empty arena that defines global settings for Composer."""
import os
from dm_control import mjcf
from dm_control.composer import entity as entity_module
_ARENA_XML_PATH = os.path.join(os.path.dirname(__file__), 'arena.xml')
class Arena(entity_module.Entity):
"""The base empty arena that defines global settings for Composer."""
def __init__(self, *args, **kwargs):
self._mjcf_root = None # Declare that _mjcf_root exists to allay pytype.
super().__init__(*args, **kwargs)
# _build uses *args and **kwargs rather than named arguments, to get
# around a signature-mismatch error from pytype in derived classes.
def _build(self, *args, **kwargs) -> None:
"""Initializes this arena.
The function takes two arguments through args, kwargs:
name: A string, the name of this arena. If `None`, use the model name
defined in the MJCF file.
xml_path: An optional path to an XML file that will override the default
composer arena MJCF.
Args:
*args: See above.
**kwargs: See above.
"""
if args:
name = args[0]
else:
name = kwargs.get('name', None)
if len(args) > 1:
xml_path = args[1]
else:
xml_path = kwargs.get('xml_path', None)
self._mjcf_root = mjcf.from_path(xml_path or _ARENA_XML_PATH)
if name:
self._mjcf_root.model = name
def add_free_entity(self, entity):
"""Includes an entity in the arena as a free-moving body."""
frame = self.attach(entity)
frame.add('freejoint')
return frame
@property
def mjcf_model(self):
return self._mjcf_root
| dm_control-main | dm_control/composer/arena.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for base variation operations."""
import operator
from absl.testing import absltest
from absl.testing import parameterized
from dm_control.composer import variation
from dm_control.composer.variation import deterministic
import numpy as np
class VariationTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.value_1 = 3
self.variation_1 = deterministic.Constant(self.value_1)
self.value_2 = 5
self.variation_2 = deterministic.Constant(self.value_2)
@parameterized.parameters(['neg'])
def test_unary_operator(self, name):
func = getattr(operator, name)
self.assertEqual(
variation.evaluate(func(self.variation_1)),
func(self.value_1))
@parameterized.parameters(['add', 'sub', 'mul', 'truediv', 'floordiv', 'pow'])
def test_binary_operator(self, name):
func = getattr(operator, name)
self.assertEqual(
variation.evaluate(func(self.value_1, self.variation_2)),
func(self.value_1, self.value_2))
self.assertEqual(
variation.evaluate(func(self.variation_1, self.value_2)),
func(self.value_1, self.value_2))
self.assertEqual(
variation.evaluate(func(self.variation_1, self.variation_2)),
func(self.value_1, self.value_2))
def test_getitem(self):
value = deterministic.Constant(np.array([4, 5, 6, 7, 8]))
np.testing.assert_array_equal(
variation.evaluate(value[[3, 1]]),
[7, 5])
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/composer/variation/variation_test.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for distributions."""
from absl.testing import absltest
from absl.testing import parameterized
from dm_control.composer.variation import distributions
import numpy as np
RANDOM_SEED = 123
NUM_ITERATIONS = 100
def _make_random_state():
return np.random.RandomState(RANDOM_SEED)
class DistributionsTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self._variation_random_state = _make_random_state()
self._np_random_state = _make_random_state()
def testUniform(self):
lower, upper = [2, 3, 4], [5, 6, 7]
variation = distributions.Uniform(low=lower, high=upper)
for _ in range(NUM_ITERATIONS):
np.testing.assert_array_equal(
variation(random_state=self._variation_random_state),
self._np_random_state.uniform(lower, upper))
def testUniformChoice(self):
choices = ['apple', 'banana', 'cherry']
variation = distributions.UniformChoice(choices)
for _ in range(NUM_ITERATIONS):
self.assertEqual(
variation(random_state=self._variation_random_state),
self._np_random_state.choice(choices))
def testUniformPointOnSphere(self):
variation = distributions.UniformPointOnSphere()
samples = []
for _ in range(NUM_ITERATIONS):
sample = variation(random_state=self._variation_random_state)
self.assertEqual(sample.size, 3)
np.testing.assert_approx_equal(np.linalg.norm(sample), 1.0)
samples.append(sample)
# Make sure that none of the samples are the same.
self.assertLen(
set(np.reshape(np.asarray(samples), -1)), 3 * NUM_ITERATIONS)
def testNormal(self):
loc, scale = 1, 2
variation = distributions.Normal(loc=loc, scale=scale)
for _ in range(NUM_ITERATIONS):
self.assertEqual(
variation(random_state=self._variation_random_state),
self._np_random_state.normal(loc, scale))
def testExponential(self):
scale = 3
variation = distributions.Exponential(scale=scale)
for _ in range(NUM_ITERATIONS):
self.assertEqual(
variation(random_state=self._variation_random_state),
self._np_random_state.exponential(scale))
def testPoisson(self):
lam = 4
variation = distributions.Poisson(lam=lam)
for _ in range(NUM_ITERATIONS):
self.assertEqual(
variation(random_state=self._variation_random_state),
self._np_random_state.poisson(lam))
@parameterized.parameters(0, 10)
def testBiasedRandomWalk(self, timescale):
stdev = 1.
variation = distributions.BiasedRandomWalk(stdev=stdev, timescale=timescale)
sequence = [variation(random_state=self._variation_random_state)
for _ in range(int(max(timescale, 1)*NUM_ITERATIONS*1000))]
self.assertAlmostEqual(np.mean(sequence), 0., delta=0.01)
self.assertAlmostEqual(np.std(sequence), stdev, delta=0.01)
@parameterized.parameters(
dict(arg_name='stdev', template=distributions._NEGATIVE_STDEV),
dict(arg_name='timescale', template=distributions._NEGATIVE_TIMESCALE))
def testBiasedRandomWalkExceptions(self, arg_name, template):
bad_value = -1.
with self.assertRaisesWithLiteralMatch(
ValueError, template.format(bad_value)):
_ = distributions.BiasedRandomWalk(**{arg_name: bad_value})
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/composer/variation/distributions_test.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Deterministic variations."""
from dm_control.composer.variation import base
from dm_control.composer.variation.variation_values import evaluate
class Constant(base.Variation):
"""Wraps a constant value into a Variation object.
This class is provided mainly for use in tests, to check that variations are
invoked correctly without having to introduce randomness in test cases.
"""
def __init__(self, value):
self._value = value
def __call__(self, initial_value=None, current_value=None, random_state=None):
return self._value
class Sequence(base.Variation):
"""Variation representing a fixed sequence of values."""
def __init__(self, values):
self._values = values
self._iterator = iter(self._values)
def __call__(self, initial_value=None, current_value=None, random_state=None):
try:
return evaluate(next(self._iterator), initial_value=initial_value,
current_value=current_value, random_state=random_state)
except StopIteration:
self._iterator = iter(self._values)
return evaluate(next(self._iterator), initial_value=initial_value,
current_value=current_value, random_state=random_state)
class Identity(base.Variation):
def __call__(self, initial_value=None, current_value=None, random_state=None):
return current_value
| dm_control-main | dm_control/composer/variation/deterministic.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""A module that helps manage model variation in Composer environments."""
import collections
import copy
from dm_control.composer.variation.base import Variation
from dm_control.composer.variation.variation_values import evaluate
class _VariationInfo:
__slots__ = ['initial_value', 'variation']
def __init__(self, initial_value=None, variation=None):
self.initial_value = initial_value
self.variation = variation
class MJCFVariator:
"""Helper object for applying variations to MJCF attributes.
An instance of this class remembers the original value of each MJCF attribute
the first time a variation is applied. The original value is then passed as an
argument to each variation callable.
"""
def __init__(self):
self._variations = collections.defaultdict(dict)
def bind_attributes(self, element, **kwargs):
"""Binds variations to attributes of an MJCF element.
Args:
element: An `mjcf.Element` object.
**kwargs: Keyword arguments mapping attribute names to the corresponding
variations. A variation is either a fixed value or a callable that
optionally takes the original value of an attribute and returns a
new value.
"""
for attribute_name, variation in kwargs.items():
if variation is None and attribute_name in self._variations[element]:
del self._variations[element][attribute_name]
else:
initial_value = copy.copy(getattr(element, attribute_name))
self._variations[element][attribute_name] = (
_VariationInfo(initial_value, variation))
def apply_variations(self, random_state):
"""Applies variations in-place to the specified MJCF element.
Args:
random_state: A `numpy.random.RandomState` instance.
"""
for element, attribute_variations in self._variations.items():
new_values = {}
for attribute_name, variation_info in attribute_variations.items():
current_value = getattr(element, attribute_name)
if variation_info.initial_value is None:
variation_info.initial_value = copy.copy(current_value)
new_values[attribute_name] = evaluate(
variation_info.variation, variation_info.initial_value,
current_value, random_state)
element.set_attributes(**new_values)
def clear(self):
"""Clears all bound attribute variations."""
self._variations.clear()
def reset_initial_values(self):
for variations in self._variations.values():
for variation_info in variations.values():
variation_info.initial_value = None
class PhysicsVariator:
"""Helper object for applying variations to MjModel and MjData.
An instance of this class remembers the original value of each attribute
the first time a variation is applied. The original value is then passed as an
argument to each variation callable.
"""
def __init__(self):
self._variations = collections.defaultdict(dict)
def bind_attributes(self, element, **kwargs):
"""Binds variations to attributes of an MJCF element.
Args:
element: An `mjcf.Element` object.
**kwargs: Keyword arguments mapping attribute names to the corresponding
variations. A variation is either a fixed value or a callable that
optionally takes the original value of an attribute and returns a
new value.
"""
for attribute_name, variation in kwargs.items():
if variation is None and attribute_name in self._variations[element]:
del self._variations[element][attribute_name]
else:
self._variations[element][attribute_name] = (
_VariationInfo(None, variation))
def apply_variations(self, physics, random_state):
for element, variations in self._variations.items():
binding = physics.bind(element)
for attribute_name, variation_info in variations.items():
current_value = getattr(binding, attribute_name)
if variation_info.initial_value is None:
variation_info.initial_value = copy.copy(current_value)
setattr(binding, attribute_name, evaluate(
variation_info.variation, variation_info.initial_value,
current_value, random_state))
def clear(self):
"""Clears all bound attribute variations."""
self._variations.clear()
def reset_initial_values(self):
for variations in self._variations.values():
for variation_info in variations.values():
variation_info.initial_value = None
| dm_control-main | dm_control/composer/variation/__init__.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Variations in 3D rotations."""
from dm_control.composer.variation import base
from dm_control.composer.variation import variation_values
import numpy as np
IDENTITY_QUATERNION = np.array([1., 0., 0., 0.])
class UniformQuaternion(base.Variation):
"""Uniformly distributed unit quaternions."""
def __call__(self, initial_value=None, current_value=None, random_state=None):
random_state = random_state or np.random
u1, u2, u3 = random_state.uniform([0.] * 3, [1., 2. * np.pi, 2. * np.pi])
return np.array([np.sqrt(1. - u1) * np.sin(u2),
np.sqrt(1. - u1) * np.cos(u2),
np.sqrt(u1) * np.sin(u3),
np.sqrt(u1) * np.cos(u3)])
class QuaternionFromAxisAngle(base.Variation):
"""Quaternion variation specified in terms of variations in axis and angle."""
def __init__(self, axis, angle):
self._axis = axis
self._angle = angle
def __call__(self, initial_value=None, current_value=None, random_state=None):
random_state = random_state or np.random
axis = variation_values.evaluate(
self._axis, initial_value, current_value, random_state)
angle = variation_values.evaluate(
self._angle, initial_value, current_value, random_state)
sine, cosine = np.sin(angle / 2), np.cos(angle / 2)
return np.array([cosine, axis[0] * sine, axis[1] * sine, axis[2] * sine])
class QuaternionPreMultiply(base.Variation):
"""A variation that pre-multiplies an existing quaternion value.
This variation takes a quaternion value generated by another variation and
pre-multiplies it to an existing value. In cumulative mode, the new quaternion
is pre-multiplied to the current value being varied. In non-cumulative mode,
the new quaternion is pre-multiplied to a fixed initial value.
"""
def __init__(self, quat, cumulative=False):
self._quat = quat
self._cumulative = cumulative
def __call__(self, initial_value=None, current_value=None, random_state=None):
random_state = random_state or np.random
q1 = variation_values.evaluate(self._quat, initial_value, current_value,
random_state)
q2 = current_value if self._cumulative else initial_value
return np.array([
q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3],
q1[0]*q2[1] + q1[1]*q2[0] + q1[2]*q2[3] - q1[3]*q2[2],
q1[0]*q2[2] - q1[1]*q2[3] + q1[2]*q2[0] + q1[3]*q2[1],
q1[0]*q2[3] + q1[1]*q2[2] - q1[2]*q2[1] + q1[3]*q2[0]])
| dm_control-main | dm_control/composer/variation/rotations.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Standard statistical distributions that conform to the Variation API."""
import abc
import functools
from dm_control.composer.variation import base
from dm_control.composer.variation.variation_values import evaluate
import numpy as np
class Distribution(base.Variation, metaclass=abc.ABCMeta):
"""Base Distribution class for sampling a parametrized distribution.
Subclasses need to implement `_callable`, which needs to return a callable
based on the random_state passed as arg. This callable then gets called using
the arguments passed to the constructor, after being evaluated. This allows
the distribution parameters themselves to be instances of `base.Variation`.
By default samples are drawn in the shape of `initial_value`, unless the
optional `single_sample` constructor arg is set to `True`, in which case only
a single sample is drawn.
"""
__slots__ = ('_single_sample', '_args', '_kwargs')
def __init__(self, *args, **kwargs):
self._single_sample = kwargs.pop('single_sample', False)
self._args = args
self._kwargs = kwargs
def __call__(self, initial_value=None, current_value=None, random_state=None):
local_random_state = random_state or np.random
size = (
None if self._single_sample or initial_value is None # pylint: disable=g-long-ternary
else np.shape(initial_value))
local_args = evaluate(
self._args,
initial_value=initial_value,
current_value=current_value,
random_state=random_state)
local_kwargs = evaluate(
self._kwargs,
initial_value=initial_value,
current_value=current_value,
random_state=random_state)
return self._callable(local_random_state)(
*local_args, size=size, **local_kwargs)
def __getattr__(self, name):
if name.startswith('__'):
raise AttributeError # Stops infinite recursion during deepcopy.
elif name in self._kwargs:
return self._kwargs[name]
else:
raise AttributeError('{!r} object has no attribute {!r}'.format(
type(self).__name__, name))
@abc.abstractmethod
def _callable(self, random_state):
raise NotImplementedError
class Uniform(Distribution):
__slots__ = ()
def __init__(self, low=0.0, high=1.0, single_sample=False):
super().__init__(low=low, high=high, single_sample=single_sample)
def _callable(self, random_state):
return random_state.uniform
class UniformInteger(Distribution):
__slots__ = ()
def __init__(self, low, high=None, single_sample=False):
super().__init__(low, high=high, single_sample=single_sample)
def _callable(self, random_state):
return random_state.randint
class UniformChoice(Distribution):
__slots__ = ()
def __init__(self, choices, single_sample=False):
super().__init__(choices, single_sample=single_sample)
def _callable(self, random_state):
return random_state.choice
class UniformPointOnSphere(base.Variation):
"""Samples a point on the unit sphere, i.e. a 3D vector with norm 1."""
__slots__ = ()
def __init__(self, single_sample=False):
self._single_sample = single_sample
def __call__(self, initial_value=None, current_value=None, random_state=None):
random_state = random_state or np.random
size = (
3 if self._single_sample or initial_value is None # pylint: disable=g-long-ternary
else np.append(np.shape(initial_value), 3))
axis = random_state.normal(size=size)
axis /= np.linalg.norm(axis, axis=-1, keepdims=True)
return axis
class Normal(Distribution):
__slots__ = ()
def __init__(self, loc=0.0, scale=1.0, single_sample=False):
super().__init__(loc=loc, scale=scale, single_sample=single_sample)
def _callable(self, random_state):
return random_state.normal
class LogNormal(Distribution):
__slots__ = ()
def __init__(self, mean=0.0, sigma=1.0, single_sample=False):
super().__init__(mean=mean, sigma=sigma, single_sample=single_sample)
def _callable(self, random_state):
return random_state.lognormal
class Exponential(Distribution):
__slots__ = ()
def __init__(self, scale=1.0, single_sample=False):
super().__init__(scale=scale, single_sample=single_sample)
def _callable(self, random_state):
return random_state.exponential
class Poisson(Distribution):
__slots__ = ()
def __init__(self, lam=1.0, single_sample=False):
super().__init__(lam=lam, single_sample=single_sample)
def _callable(self, random_state):
return random_state.poisson
class Bernoulli(Distribution):
__slots__ = ()
def __init__(self, prob=0.5, single_sample=False):
super().__init__(prob, single_sample=single_sample)
def _callable(self, random_state):
return functools.partial(random_state.binomial, 1)
_NEGATIVE_STDEV = '`stdev` must be >= 0, got {}.'
_NEGATIVE_TIMESCALE = '`timescale` must be >= 0, got {}.'
class BiasedRandomWalk(base.Variation):
"""A Class for generating noise from a zero-mean Ornstein-Uhlenbeck process.
Let
`retain = np.exp(-1. / timescale)`
and
`scale = stdev * sqrt(1 - (retain * retain))`
Then the discete-time first-order filtered diffusion process
`x_next = retain * x + N(0, scale))`
has standard deviation `stdev` and characteristic timescale `timescale`.
"""
__slots__ = ('_scale', '_value')
def __init__(self, stdev=0.1, timescale=10.):
"""Initializes a `BiasedRandomWalk`.
Args:
stdev: Float. Standard deviation of the output sequence.
timescale: Integer. Number of timesteps characteristic of the random walk.
After `timescale` steps the correlation is reduced by exp(-1). Larger or
equal to 0, where a value of 0 is an uncorrelated normal distribution.
Raises:
ValueError: if either `stdev` or `timescale` is negative.
"""
if stdev < 0:
raise ValueError(_NEGATIVE_STDEV.format(stdev))
if timescale < 0:
raise ValueError(_NEGATIVE_TIMESCALE.format(timescale))
elif timescale == 0:
self._retain = 0.
else:
self._retain = np.exp(-1. / timescale)
self._scale = stdev * np.sqrt(1 - (self._retain * self._retain))
self._value = 0.0
def __call__(self, initial_value=None, current_value=None, random_state=None):
random_state = random_state or np.random
self._value = (
self._retain * self._value +
random_state.normal(loc=0.0, scale=self._scale))
return self._value
| dm_control-main | dm_control/composer/variation/distributions.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for noises."""
from absl.testing import absltest
from absl.testing import parameterized
from dm_control.composer.variation import deterministic
from dm_control.composer.variation import noises
NUM_ITERATIONS = 100
class NoisesTest(parameterized.TestCase):
@parameterized.parameters(False, True)
def testAdditive(self, use_constant_variation_object):
amount = 2
if use_constant_variation_object:
variation = noises.Additive(deterministic.Constant(amount))
else:
variation = noises.Additive(amount)
initial_value = 0
current_value = initial_value
for _ in range(NUM_ITERATIONS):
current_value = variation(
initial_value=initial_value, current_value=current_value)
self.assertEqual(current_value, initial_value + amount)
@parameterized.parameters(False, True)
def testAdditiveCumulative(self, use_constant_variation_object):
amount = 3
if use_constant_variation_object:
variation = noises.Additive(
deterministic.Constant(amount), cumulative=True)
else:
variation = noises.Additive(amount, cumulative=True)
initial_value = 1
current_value = initial_value
for i in range(NUM_ITERATIONS):
current_value = variation(
initial_value=initial_value, current_value=current_value)
self.assertEqual(current_value, initial_value + amount * (i + 1))
@parameterized.parameters(False, True)
def testMultiplicative(self, use_constant_variation_object):
amount = 23
if use_constant_variation_object:
variation = noises.Multiplicative(deterministic.Constant(amount))
else:
variation = noises.Multiplicative(amount)
initial_value = 3
current_value = initial_value
for _ in range(NUM_ITERATIONS):
current_value = variation(
initial_value=initial_value, current_value=current_value)
self.assertEqual(current_value, initial_value * amount)
@parameterized.parameters(False, True)
def testMultiplicativeCumulative(self, use_constant_variation_object):
amount = 2
if use_constant_variation_object:
variation = noises.Multiplicative(
deterministic.Constant(amount), cumulative=True)
else:
variation = noises.Multiplicative(amount, cumulative=True)
initial_value = 3
current_value = initial_value
for i in range(NUM_ITERATIONS):
current_value = variation(
initial_value=initial_value, current_value=current_value)
self.assertEqual(current_value, initial_value * amount ** (i + 1))
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/composer/variation/noises_test.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Utilities for handling nested structures of callables or constants."""
import tree
def evaluate(structure, *args, **kwargs):
"""Evaluates a arbitrarily nested structure of callables or constant values.
Args:
structure: An arbitrarily nested structure of callables or constant values.
By "structures", we mean lists, tuples, namedtuples, or dicts.
*args: Positional arguments passed to each callable in `structure`.
**kwargs: Keyword arguments passed to each callable in `structure.
Returns:
The same nested structure, with each callable replaced by the value returned
by calling it.
"""
return tree.map_structure(
lambda x: x(*args, **kwargs) if callable(x) else x, structure)
| dm_control-main | dm_control/composer/variation/variation_values.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Math operations on variation objects."""
import abc
from dm_control.composer.variation import base
from dm_control.composer.variation.variation_values import evaluate
import numpy as np
class MathOp(base.Variation):
"""Base MathOp class for applying math operations on variation objects.
Subclasses need to implement `_op`, which takes in a single value and applies
the desired math operation. This operation gets applied to the result of the
evaluated base variation object passed at construction. Structured variation
objects are automatically traversed.
"""
def __init__(self, *args, **kwargs):
self._args = args
self._kwargs = kwargs
def __call__(self, initial_value=None, current_value=None, random_state=None):
local_args = evaluate(
self._args,
initial_value=initial_value,
current_value=current_value,
random_state=random_state)
local_kwargs = evaluate(
self._kwargs,
initial_value=initial_value,
current_value=current_value,
random_state=random_state)
return self._callable(*local_args, **local_kwargs)
@property
@abc.abstractmethod
def _callable(self):
pass
class Log(MathOp):
@property
def _callable(self):
return np.log
class Max(MathOp):
@property
def _callable(self):
return np.max
class Min(MathOp):
@property
def _callable(self):
return np.min
class Norm(MathOp):
@property
def _callable(self):
return np.linalg.norm
| dm_control-main | dm_control/composer/variation/math.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Base class for variations and binary operations on variations."""
import abc
import operator
from dm_control.composer.variation import variation_values
import numpy as np
class Variation(metaclass=abc.ABCMeta):
"""Abstract base class for variations."""
@abc.abstractmethod
def __call__(self, initial_value, current_value, random_state):
"""Generates a value for this variation.
Args:
initial_value: The original value of the attribute being varied.
Absolute variations may ignore this argument.
current_value: The current value of the attribute being varied.
Absolute variations may ignore this argument.
random_state: A `numpy.RandomState` used to generate the value.
Deterministic variations may ignore this argument.
Returns:
The next value for this variation.
"""
def __add__(self, other):
return _BinaryOperation(operator.add, self, other)
def __radd__(self, other):
return _BinaryOperation(operator.add, other, self)
def __sub__(self, other):
return _BinaryOperation(operator.sub, self, other)
def __rsub__(self, other):
return _BinaryOperation(operator.sub, other, self)
def __mul__(self, other):
return _BinaryOperation(operator.mul, self, other)
def __rmul__(self, other):
return _BinaryOperation(operator.mul, other, self)
def __truediv__(self, other):
return _BinaryOperation(operator.truediv, self, other)
def __rtruediv__(self, other):
return _BinaryOperation(operator.truediv, other, self)
def __floordiv__(self, other):
return _BinaryOperation(operator.floordiv, self, other)
def __rfloordiv__(self, other):
return _BinaryOperation(operator.floordiv, other, self)
def __pow__(self, other):
return _BinaryOperation(operator.pow, self, other)
def __rpow__(self, other):
return _BinaryOperation(operator.pow, other, self)
def __getitem__(self, index):
return _GetItemOperation(self, index)
def __neg__(self):
return _UnaryOperation(operator.neg, self)
class _UnaryOperation(Variation):
"""Represents the result of applying a unary operator to a Variation."""
def __init__(self, op, variation):
self._op = op
self._variation = variation
def __call__(self, initial_value=None, current_value=None, random_state=None):
value = variation_values.evaluate(
self._variation, initial_value, current_value, random_state)
return self._op(value)
class _BinaryOperation(Variation):
"""Represents the result of applying a binary operator to two Variations."""
def __init__(self, op, first, second):
self._first = first
self._second = second
self._op = op
def __call__(self, initial_value=None, current_value=None, random_state=None):
first_value = variation_values.evaluate(
self._first, initial_value, current_value, random_state)
second_value = variation_values.evaluate(
self._second, initial_value, current_value, random_state)
return self._op(first_value, second_value)
class _GetItemOperation(Variation):
def __init__(self, variation, index):
self._variation = variation
self._index = index
def __call__(self, initial_value=None, current_value=None, random_state=None):
value = variation_values.evaluate(
self._variation, initial_value, current_value, random_state)
return np.asarray(value)[self._index]
| dm_control-main | dm_control/composer/variation/base.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Meta-variations that modify original values by a specified variation."""
from dm_control.composer.variation import base
from dm_control.composer.variation import variation_values
class Additive(base.Variation):
"""A variation that adds to an existing value.
This variation takes a value generated by another variation and adds it to an
existing value. In cumulative mode, the generated value is added to the
current value being varied. In non-cumulative mode, the generated value is
added to a fixed initial value.
"""
def __init__(self, variation, cumulative=False):
self._variation = variation
self._cumulative = cumulative
def __call__(self, initial_value=None, current_value=None, random_state=None):
base_value = current_value if self._cumulative else initial_value
return base_value + (
variation_values.evaluate(self._variation, initial_value, current_value,
random_state))
class Multiplicative(base.Variation):
"""A variation that multiplies to an existing value.
This variation takes a value generated by another variation and multiplies it
to an existing value. In cumulative mode, the generated value is multiplied to
the current value being varied. In non-cumulative mode, the generated value is
multiplied to a fixed initial value.
"""
def __init__(self, variation, cumulative=False):
self._variation = variation
self._cumulative = cumulative
def __call__(self, initial_value=None, current_value=None, random_state=None):
base_value = current_value if self._cumulative else initial_value
return base_value * (
variation_values.evaluate(self._variation, initial_value, current_value,
random_state))
| dm_control-main | dm_control/composer/variation/noises.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Variations in colors.
Classes in this module allow users to specify a variations for each channel in
a variety of color spaces. The generated values are always RGBA arrays.
"""
import colorsys
from dm_control.composer.variation import base
from dm_control.composer.variation import variation_values
import numpy as np
class RgbVariation(base.Variation):
"""Represents a variation in the RGB color space.
This class allows users to specify independent variations in the R, G, B, and
alpha channels of a color, and generates the corresponding array of RGBA
values.
"""
def __init__(self, r, g, b, alpha=1.0):
self._r, self._g, self._b = r, g, b
self._alpha = alpha
def __call__(self, initial_value=None, current_value=None, random_state=None):
return np.asarray(
variation_values.evaluate([self._r, self._g, self._b, self._alpha],
initial_value, current_value, random_state))
class HsvVariation(base.Variation):
"""Represents a variation in the HSV color space.
This class allows users to specify independent variations in the H, S, V, and
alpha channels of a color, and generates the corresponding array of RGBA
values.
"""
def __init__(self, h, s, v, alpha=1.0):
self._h, self._s, self._v = h, s, v
self._alpha = alpha
def __call__(self, initial_value=None, current_value=None, random_state=None):
h, s, v, alpha = variation_values.evaluate(
(self._h, self._s, self._v, self._alpha), initial_value, current_value,
random_state)
return np.asarray(list(colorsys.hsv_to_rgb(h, s, v)) + [alpha])
class GrayVariation(HsvVariation):
"""Represents a variation in gray level.
This class allows users to specify independent variations in the gray level
and alpha channels of a color, and generates the corresponding array of RGBA
values.
"""
def __init__(self, gray_level, alpha=1.0):
super().__init__(h=0.0, s=0.0, v=gray_level, alpha=alpha)
| dm_control-main | dm_control/composer/variation/colors.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Multi-rate observation and buffering framework for Composer environments."""
from dm_control.composer.observation import observable
from dm_control.composer.observation.obs_buffer import Buffer
from dm_control.composer.observation.updater import DEFAULT_BUFFER_SIZE
from dm_control.composer.observation.updater import DEFAULT_DELAY
from dm_control.composer.observation.updater import DEFAULT_UPDATE_INTERVAL
from dm_control.composer.observation.updater import Updater
| dm_control-main | dm_control/composer/observation/__init__.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for observation.obs_buffer."""
from absl.testing import absltest
from absl.testing import parameterized
from dm_control.composer.observation import obs_buffer
import numpy as np
def _generate_constant_schedule(update_timestep, delay, control_timestep,
n_observed_steps):
first = update_timestep
last = control_timestep * n_observed_steps + 1
return [(i, delay) for i in range(first, last, update_timestep)]
class BufferTest(parameterized.TestCase):
def testOutOfOrderArrival(self):
buf = obs_buffer.Buffer(buffer_size=3, shape=(), dtype=float)
buf.insert(timestamp=0, delay=4, value=1)
buf.insert(timestamp=1, delay=2, value=2)
buf.insert(timestamp=2, delay=3, value=3)
np.testing.assert_array_equal(buf.read(current_time=2), [0., 0., 0.])
np.testing.assert_array_equal(buf.read(current_time=3), [0., 0., 2.])
np.testing.assert_array_equal(buf.read(current_time=4), [0., 2., 1.])
np.testing.assert_array_equal(buf.read(current_time=5), [2., 1., 3.])
np.testing.assert_array_equal(buf.read(current_time=6), [2., 1., 3.])
@parameterized.parameters(((3, 3),), ((),))
def testStripSingletonDimension(self, shape):
buf = obs_buffer.Buffer(
buffer_size=1,
shape=shape,
dtype=float,
strip_singleton_buffer_dim=True)
expected_value = np.full(shape, 42, dtype=float)
buf.insert(timestamp=0, delay=0, value=expected_value)
np.testing.assert_array_equal(buf.read(current_time=1), expected_value)
def testPlanToSingleUndelayedObservation(self):
buf = obs_buffer.Buffer(buffer_size=1, shape=(), dtype=float)
control_timestep = 20
observation_schedule = _generate_constant_schedule(
update_timestep=1,
delay=0,
control_timestep=control_timestep,
n_observed_steps=1)
buf.drop_unobserved_upcoming_items(
observation_schedule, read_interval=control_timestep)
self.assertEqual(observation_schedule, [(20, 0)])
def testPlanTwoStepsAhead(self):
buf = obs_buffer.Buffer(buffer_size=1, shape=(), dtype=float)
control_timestep = 5
observation_schedule = _generate_constant_schedule(
update_timestep=2,
delay=3,
control_timestep=control_timestep,
n_observed_steps=2)
buf.drop_unobserved_upcoming_items(
observation_schedule, read_interval=control_timestep)
self.assertEqual(observation_schedule, [(2, 3), (6, 3), (10, 3)])
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/composer/observation/obs_buffer_test.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""An object that creates and updates buffers for enabled observables."""
import collections
import functools
from absl import logging
from dm_control.composer import variation
from dm_control.composer.observation import obs_buffer
from dm_env import specs
import numpy as np
DEFAULT_BUFFER_SIZE = 1
DEFAULT_UPDATE_INTERVAL = 1
DEFAULT_DELAY = 0
class _EnabledObservable:
"""Encapsulates an enabled observable, its buffer, and its update schedule."""
__slots__ = ('observable', 'observation_callable',
'update_interval', 'delay', 'buffer_size',
'buffer', 'update_schedule')
def __init__(self, observable, physics, random_state,
strip_singleton_buffer_dim, pad_with_initial_value):
self.observable = observable
self.observation_callable = (
observable.observation_callable(physics, random_state))
self._bind_attribute_from_observable('update_interval',
DEFAULT_UPDATE_INTERVAL,
random_state)
self._bind_attribute_from_observable('delay',
DEFAULT_DELAY,
random_state)
self._bind_attribute_from_observable('buffer_size',
DEFAULT_BUFFER_SIZE,
random_state)
obs_spec = self.observable.array_spec
if obs_spec is None:
# We take an observation to determine the shape and dtype of the array.
# This occurs outside of an episode and doesn't affect environment
# behavior. At this point the physics state is not guaranteed to be valid,
# so we might get a `PhysicsError` if the observation callable calls
# `physics.forward`. We suppress such errors since they do not matter as
# far as the shape and dtype of the observation are concerned.
with physics.suppress_physics_errors():
obs_array = self.observation_callable()
obs_array = np.asarray(obs_array)
obs_spec = specs.Array(shape=obs_array.shape, dtype=obs_array.dtype)
self.buffer = obs_buffer.Buffer(
buffer_size=self.buffer_size,
shape=obs_spec.shape, dtype=obs_spec.dtype,
pad_with_initial_value=pad_with_initial_value,
strip_singleton_buffer_dim=strip_singleton_buffer_dim)
self.update_schedule = collections.deque()
def _bind_attribute_from_observable(self, attr, default_value, random_state):
obs_attr = getattr(self.observable, attr)
if obs_attr:
if isinstance(obs_attr, variation.Variation):
setattr(self, attr,
functools.partial(obs_attr, random_state=random_state))
else:
setattr(self, attr, obs_attr)
else:
setattr(self, attr, default_value)
def _call_if_callable(arg):
if callable(arg):
return arg()
else:
return arg
def _validate_structure(structure):
"""Validates the structure of the given observables collection.
The collection must either be a dict, or a (list or tuple) of dicts.
Args:
structure: A candidate collection of observables.
Returns:
A boolean that is `True` if `structure` is either a list or a tuple, or
`False` otherwise.
Raises:
ValueError: If `structure` is neither a dict nor a (list or tuple) of dicts.
"""
is_nested = isinstance(structure, (list, tuple))
if is_nested:
is_valid = all(isinstance(obj, dict) for obj in structure)
else:
is_valid = isinstance(structure, dict)
if not is_valid:
raise ValueError(
'`observables` should be a dict, or a (list or tuple) of dicts'
': got {}'.format(structure))
return is_nested
class Updater:
"""Creates and updates buffers for enabled observables."""
def __init__(self, observables, physics_steps_per_control_step=1,
strip_singleton_buffer_dim=False,
pad_with_initial_value=False):
self._physics_steps_per_control_step = physics_steps_per_control_step
self._strip_singleton_buffer_dim = strip_singleton_buffer_dim
self._pad_with_initial_value = pad_with_initial_value
self._step_counter = 0
self._observables = observables
self._is_nested = _validate_structure(observables)
self._enabled_structure = None
self._enabled_list = None
def reset(self, physics, random_state):
"""Resets this updater's state."""
def make_buffers_dict(observables):
"""Makes observable states in a dict."""
# Use `type(observables)` so that our output structure respects the
# original dict subclass (e.g. OrderedDict).
out_dict = type(observables)()
for key, value in observables.items():
if value.enabled:
out_dict[key] = _EnabledObservable(value, physics, random_state,
self._strip_singleton_buffer_dim,
self._pad_with_initial_value)
return out_dict
if self._is_nested:
self._enabled_structure = type(self._observables)(
make_buffers_dict(obs_dict) for obs_dict in self._observables)
self._enabled_list = []
for enabled_dict in self._enabled_structure:
self._enabled_list.extend(enabled_dict.values())
else:
self._enabled_structure = make_buffers_dict(self._observables)
self._enabled_list = self._enabled_structure.values()
self._step_counter = 0
for enabled in self._enabled_list:
first_delay = _call_if_callable(enabled.delay)
enabled.buffer.insert(
0, first_delay,
enabled.observation_callable())
def observation_spec(self):
"""The observation specification for this environment.
Returns a dict mapping the names of enabled observations to their
corresponding `Array` or `BoundedArray` specs.
If an obs has a BoundedArray spec, but uses an aggregator that
does not preserve those bounds (such as `sum`), it will be mapped to an
(unbounded) `Array` spec. If using a bounds-preserving custom aggregator
`my_agg`, give it an attribute `my_agg.preserves_bounds = True` to indicate
to this method that it is bounds-preserving.
The returned specification is only valid as of the previous call
to `reset`. In particular, it is an error to call this function before
the first call to `reset`.
Returns:
A dict mapping observation name to `Array` or `BoundedArray` spec
containing the observation shape and dtype, and possibly bounds.
Raises:
RuntimeError: If this method is called before `reset` has been called.
"""
if self._enabled_structure is None:
raise RuntimeError('`reset` must be called before `observation_spec`.')
def make_observation_spec_dict(enabled_dict):
"""Makes a dict of enabled observation specs from of observables."""
out_dict = type(enabled_dict)()
for name, enabled in enabled_dict.items():
if (enabled.observable.aggregator is None
and enabled.observable.array_spec is not None):
# If possible, keep the original array spec, just updating the name
# and modifying the dimension for buffering. Doing this allows for
# custom spec types to be exposed by the environment where possible.
out_dict[name] = enabled.observable.array_spec.replace(
name=name, shape=enabled.buffer.shape
)
continue
if isinstance(enabled.observable.array_spec, specs.BoundedArray):
bounds = (enabled.observable.array_spec.minimum,
enabled.observable.array_spec.maximum)
else:
bounds = None
if enabled.observable.aggregator:
aggregator = enabled.observable.aggregator
aggregated = aggregator(np.zeros(enabled.buffer.shape,
dtype=enabled.buffer.dtype))
shape = aggregated.shape
dtype = aggregated.dtype
# Ditch bounds if the aggregator isn't known to be bounds-preserving.
if bounds:
if not hasattr(aggregator, 'preserves_bounds'):
logging.warning('Ignoring the bounds of this observable\'s spec, '
'as its aggregator method has no boolean '
'`preserves_bounds` attrubute.')
bounds = None
elif not aggregator.preserves_bounds:
bounds = None
else:
shape = enabled.buffer.shape
dtype = enabled.buffer.dtype
if bounds:
spec = specs.BoundedArray(minimum=bounds[0],
maximum=bounds[1],
shape=shape,
dtype=dtype,
name=name)
else:
spec = specs.Array(shape=shape, dtype=dtype, name=name)
out_dict[name] = spec
return out_dict
if self._is_nested:
enabled_specs = type(self._enabled_structure)(
make_observation_spec_dict(enabled_dict)
for enabled_dict in self._enabled_structure)
else:
enabled_specs = make_observation_spec_dict(self._enabled_structure)
return enabled_specs
def prepare_for_next_control_step(self):
"""Simulates the next control step and optimizes the update schedule."""
if self._enabled_structure is None:
raise RuntimeError('`reset` must be called before `before_step`.')
for enabled in self._enabled_list:
if (enabled.update_interval == DEFAULT_UPDATE_INTERVAL
and enabled.delay == DEFAULT_DELAY
and enabled.buffer_size < self._physics_steps_per_control_step):
for i in reversed(range(enabled.buffer_size)):
next_step = (
self._step_counter + self._physics_steps_per_control_step - i)
next_delay = DEFAULT_DELAY
enabled.update_schedule.append((next_step, next_delay))
else:
if enabled.update_schedule:
last_scheduled_step = enabled.update_schedule[-1][0]
else:
last_scheduled_step = self._step_counter
max_step = self._step_counter + 2 * self._physics_steps_per_control_step
while last_scheduled_step < max_step:
next_update_interval = _call_if_callable(enabled.update_interval)
next_step = last_scheduled_step + next_update_interval
next_delay = _call_if_callable(enabled.delay)
enabled.update_schedule.append((next_step, next_delay))
last_scheduled_step = next_step
# Optimize the schedule by planning ahead and dropping unseen entries.
enabled.buffer.drop_unobserved_upcoming_items(
enabled.update_schedule, self._physics_steps_per_control_step)
def update(self):
if self._enabled_structure is None:
raise RuntimeError('`reset` must be called before `after_substep`.')
self._step_counter += 1
for enabled in self._enabled_list:
if (enabled.update_schedule and
enabled.update_schedule[0][0] == self._step_counter):
timestamp, delay = enabled.update_schedule.popleft()
enabled.buffer.insert(
timestamp, delay,
enabled.observation_callable())
def get_observation(self):
"""Gets the current observation.
The returned observation is only valid as of the previous call
to `reset`. In particular, it is an error to call this function before
the first call to `reset`.
Returns:
A dict, or list of dicts, or tuple of dicts, of observation values.
The returned structure corresponds to the structure of the `observables`
that was given at initialization time.
Raises:
RuntimeError: If this method is called before `reset` has been called.
"""
if self._enabled_structure is None:
raise RuntimeError('`reset` must be called before `observation`.')
def aggregate_dict(enabled_dict):
out_dict = type(enabled_dict)()
for name, enabled in enabled_dict.items():
if enabled.observable.aggregator:
aggregated = enabled.observable.aggregator(
enabled.buffer.read(self._step_counter))
else:
aggregated = enabled.buffer.read(self._step_counter)
out_dict[name] = aggregated
return out_dict
if self._is_nested:
return type(self._enabled_structure)(
aggregate_dict(enabled_dict)
for enabled_dict in self._enabled_structure)
else:
return aggregate_dict(self._enabled_structure)
| dm_control-main | dm_control/composer/observation/updater.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for observation.observation_updater."""
import collections
import itertools
import math
from absl.testing import absltest
from absl.testing import parameterized
from dm_control.composer.observation import fake_physics
from dm_control.composer.observation import observable
from dm_control.composer.observation import updater
from dm_env import specs
import numpy as np
class DeterministicSequence:
def __init__(self, sequence):
self._iter = itertools.cycle(sequence)
def __call__(self, random_state=None):
del random_state # unused
return next(self._iter)
class BoundedGeneric(observable.Generic):
def __init__(self, raw_observation_callable, minimum, maximum, **kwargs):
super().__init__(
raw_observation_callable=raw_observation_callable, **kwargs)
self._bounds = (minimum, maximum)
@property
def array_spec(self):
datum = np.array(self(None, None))
return specs.BoundedArray(shape=datum.shape,
dtype=datum.dtype,
minimum=self._bounds[0],
maximum=self._bounds[1])
class MyArraySpec(specs.Array):
pass
class GenericObservableWithMyArraySpec(observable.Generic):
@property
def array_spec(self):
datum = np.array(self(None, None))
return MyArraySpec(shape=datum.shape, dtype=datum.dtype)
class UpdaterTest(parameterized.TestCase):
@parameterized.parameters(list, tuple)
def testNestedSpecsAndValues(self, list_or_tuple):
observables = list_or_tuple((
{'one': observable.Generic(lambda _: 1.),
'two': observable.Generic(lambda _: [2, 2]),
}, collections.OrderedDict([
('three', observable.Generic(lambda _: np.full((2, 2), 3))),
('four', observable.Generic(lambda _: [4.])),
('five', observable.Generic(lambda _: 5)),
('six', BoundedGeneric(lambda _: [2, 2], 1, 4)),
('seven', BoundedGeneric(lambda _: 2, 1, 4, aggregator='sum')),
])
))
observables[0]['two'].enabled = True
observables[1]['three'].enabled = True
observables[1]['five'].enabled = True
observables[1]['six'].enabled = True
observables[1]['seven'].enabled = True
observation_updater = updater.Updater(observables)
observation_updater.reset(physics=fake_physics.FakePhysics(),
random_state=None)
def make_spec(obs):
array = np.array(obs.observation_callable(None, None)())
shape = array.shape if obs.aggregator else (1,) + array.shape
if (isinstance(obs, BoundedGeneric) and
obs.aggregator is not observable.base.AGGREGATORS['sum']):
return specs.BoundedArray(shape=shape,
dtype=array.dtype,
minimum=obs.array_spec.minimum,
maximum=obs.array_spec.maximum)
else:
return specs.Array(shape=shape, dtype=array.dtype)
expected_specs = list_or_tuple((
{'two': make_spec(observables[0]['two'])},
collections.OrderedDict([
('three', make_spec(observables[1]['three'])),
('five', make_spec(observables[1]['five'])),
('six', make_spec(observables[1]['six'])),
('seven', make_spec(observables[1]['seven'])),
])
))
actual_specs = observation_updater.observation_spec()
self.assertIs(type(actual_specs), type(expected_specs))
for actual_dict, expected_dict in zip(actual_specs, expected_specs):
self.assertIs(type(actual_dict), type(expected_dict))
self.assertEqual(actual_dict, expected_dict)
def make_value(obs):
value = obs(physics=None, random_state=None)
if obs.aggregator:
return value
else:
value = np.array(value)
value = value[np.newaxis, ...]
return value
expected_values = list_or_tuple((
{'two': make_value(observables[0]['two'])},
collections.OrderedDict([
('three', make_value(observables[1]['three'])),
('five', make_value(observables[1]['five'])),
('six', make_value(observables[1]['six'])),
('seven', make_value(observables[1]['seven'])),
])
))
actual_values = observation_updater.get_observation()
self.assertIs(type(actual_values), type(expected_values))
for actual_dict, expected_dict in zip(actual_values, expected_values):
self.assertIs(type(actual_dict), type(expected_dict))
self.assertLen(actual_dict, len(expected_dict))
for actual, expected in zip(actual_dict.items(), expected_dict.items()):
actual_name, actual_value = actual
expected_name, expected_value = expected
self.assertEqual(actual_name, expected_name)
np.testing.assert_array_equal(actual_value, expected_value)
def assertCorrectSpec(
self, spec, expected_shape, expected_dtype, expected_name):
self.assertEqual(spec.shape, expected_shape)
self.assertEqual(spec.dtype, expected_dtype)
self.assertEqual(spec.name, expected_name)
def testObservationSpecInference(self):
physics = fake_physics.FakePhysics()
physics.observables['repeated'].buffer_size = 5
physics.observables['matrix'].buffer_size = 4
physics.observables['sqrt'] = observable.Generic(
fake_physics.FakePhysics.sqrt, buffer_size=3)
for obs in physics.observables.values():
obs.enabled = True
observation_updater = updater.Updater(physics.observables)
observation_updater.reset(physics=physics, random_state=None)
spec = observation_updater.observation_spec()
self.assertCorrectSpec(spec['repeated'], (5, 2), int, 'repeated')
self.assertCorrectSpec(spec['matrix'], (4, 2, 3), int, 'matrix')
self.assertCorrectSpec(spec['sqrt'], (3,), float, 'sqrt')
def testCustomSpecTypePassedThrough(self):
physics = fake_physics.FakePhysics()
physics.observables['two_twos'] = GenericObservableWithMyArraySpec(
lambda _: [2.0, 2.0], buffer_size=3
)
physics.observables['two_twos'].enabled = True
observation_updater = updater.Updater(physics.observables)
observation_updater.reset(physics=physics, random_state=None)
spec = observation_updater.observation_spec()
self.assertIsInstance(spec['two_twos'], MyArraySpec)
self.assertEqual(spec['two_twos'].shape, (3, 2))
self.assertEqual(spec['two_twos'].dtype, float)
self.assertEqual(spec['two_twos'].name, 'two_twos')
@parameterized.parameters(True, False)
def testObservation(self, pad_with_initial_value):
physics = fake_physics.FakePhysics()
physics.observables['repeated'].buffer_size = 5
physics.observables['matrix'].delay = 1
physics.observables['sqrt_plus_one'] = observable.Generic(
fake_physics.FakePhysics.sqrt_plus_one, update_interval=7,
buffer_size=3, delay=2)
for obs in physics.observables.values():
obs.enabled = True
with physics.reset_context():
pass
physics_steps_per_control_step = 5
observation_updater = updater.Updater(
physics.observables, physics_steps_per_control_step,
pad_with_initial_value=pad_with_initial_value)
observation_updater.reset(physics=physics, random_state=None)
for control_step in range(0, 200):
observation_updater.prepare_for_next_control_step()
for _ in range(physics_steps_per_control_step):
physics.step()
observation_updater.update()
step_counter = (control_step + 1) * physics_steps_per_control_step
observation = observation_updater.get_observation()
def assert_correct_buffer(obs_name, expected_callable,
observation=observation,
step_counter=step_counter):
update_interval = (physics.observables[obs_name].update_interval
or updater.DEFAULT_UPDATE_INTERVAL)
buffer_size = (physics.observables[obs_name].buffer_size
or updater.DEFAULT_BUFFER_SIZE)
delay = (physics.observables[obs_name].delay
or updater.DEFAULT_DELAY)
# The final item in the buffer is the current time, less the delay,
# rounded _down_ to the nearest multiple of the update interval.
end = update_interval * int(
math.floor((step_counter - delay) / update_interval))
# Figure out the first item in the buffer by working backwards from
# the final item in multiples of the update interval.
start = end - (buffer_size - 1) * update_interval
# Clamp both the start and end step number below by zero.
buffer_range = range(max(0, start), max(0, end + 1), update_interval)
# Arrays with expected shapes, filled with expected default values.
expected_value_spec = observation_updater.observation_spec()[obs_name]
if pad_with_initial_value:
expected_values = np.full(shape=expected_value_spec.shape,
fill_value=expected_callable(0),
dtype=expected_value_spec.dtype)
else:
expected_values = np.zeros(shape=expected_value_spec.shape,
dtype=expected_value_spec.dtype)
# The arrays are filled from right to left, such that the most recent
# entry is the rightmost one, and any padding is on the left.
for index, timestamp in enumerate(reversed(buffer_range)):
expected_values[-(index+1)] = expected_callable(timestamp)
np.testing.assert_array_equal(observation[obs_name], expected_values)
assert_correct_buffer('twice', lambda x: 2*x)
assert_correct_buffer('matrix', lambda x: [[x]*3]*2)
assert_correct_buffer('repeated', lambda x: [x, x])
assert_correct_buffer('sqrt_plus_one', lambda x: np.sqrt(x) + 1)
def testVariableRatesAndDelays(self):
physics = fake_physics.FakePhysics()
physics.observables['time'] = observable.Generic(
lambda physics: physics.time(),
buffer_size=3,
# observations produced on step numbers 20*N + [0, 3, 5, 8, 11, 15, 16]
update_interval=DeterministicSequence([3, 2, 3, 3, 4, 1, 4]),
# observations arrive on step numbers 20*N + [3, 8, 7, 12, 11, 17, 20]
delay=DeterministicSequence([3, 5, 2, 5, 1, 2, 4]))
physics.observables['time'].enabled = True
physics_steps_per_control_step = 10
observation_updater = updater.Updater(
physics.observables, physics_steps_per_control_step)
observation_updater.reset(physics=physics, random_state=None)
# Run through a few cycles of the variation sequences to make sure that
# cross-control-boundary behaviour is correct.
for i in range(5):
observation_updater.prepare_for_next_control_step()
for _ in range(physics_steps_per_control_step):
physics.step()
observation_updater.update()
np.testing.assert_array_equal(
observation_updater.get_observation()['time'],
20*i + np.array([0, 5, 3]))
observation_updater.prepare_for_next_control_step()
for _ in range(physics_steps_per_control_step):
physics.step()
observation_updater.update()
# Note that #11 is dropped since it arrives after #8,
# whose large delay caused it to cross the control step boundary at #10.
np.testing.assert_array_equal(
observation_updater.get_observation()['time'],
20*i + np.array([8, 15, 16]))
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/composer/observation/updater_test.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
""""An object that manages the buffering and delaying of observation."""
import collections
import numpy as np
class InFlightObservation:
"""Represents a delayed observation that may not have arrived yet.
Attributes:
arrival: The time at which this observation will be delivered.
timestamp: The time at which this observation was made.
delay: The amount of delay between the time at which this observation was
made and the time at which it is delivered.
value: The value of this observation.
"""
__slots__ = ('arrival', 'timestamp', 'delay', 'value')
def __init__(self, timestamp, delay, value):
self.arrival = timestamp + delay
self.timestamp = timestamp
self.delay = delay
self.value = value
def __lt__(self, other):
# This is implemented to facilitate sorting.
return self.arrival < other.arrival
class Buffer:
"""An object that manages the buffering and delaying of observation."""
def __init__(self, buffer_size, shape, dtype, pad_with_initial_value=False,
strip_singleton_buffer_dim=False):
"""Initializes this observation buffer.
Args:
buffer_size: The size of the buffer returned by `read`. Note
that this does *not* affect size of the internal buffer held by this
object, which always grow as large as is necessary in the presence of
large delays.
shape: The shape of a single observation held by this buffer, which can
either be a single integer or an iterable of integers. The shape of the
buffer returned by `read` will then be
`(buffer_size, shape[0], ..., shape[n])`, unless `buffer_size == 1`
and `strip_singleton_buffer_dim == True`.
dtype: The NumPy dtype of observation entries.
pad_with_initial_value: (optional) A boolean. If `True` then the buffer
returned by `read` is padded with the first observation value when there
are fewer observation entries than `buffer_size`. If `False` then the
buffer returned by `read` is padded with zeroes.
strip_singleton_buffer_dim: (optional) A boolean, if `True` and
`buffer_size == 1` then the leading dimension will not be added to the
shape of the array returned by `read`.
"""
self._buffer_size = buffer_size
try:
shape = tuple(shape)
except TypeError:
if isinstance(shape, int):
shape = (shape,)
else:
raise
self._has_buffer_dim = not (strip_singleton_buffer_dim and buffer_size == 1)
if self._has_buffer_dim:
self._buffered_shape = (buffer_size,) + shape
else:
self._buffered_shape = shape
self._dtype = dtype
# The "arrived" deque contains entries that are due to be delivered now.
# This deque should never grow beyond buffer_size.
self._arrived_deque = collections.deque(maxlen=buffer_size)
if not pad_with_initial_value:
for _ in range(buffer_size):
self._arrived_deque.append(
InFlightObservation(-np.inf, 0, np.full(shape, 0, dtype)))
# The "pending" deque contains entries that are stored for future delivery.
# This deque can grow arbitrarily large in presence of long delays.
self._pending_deque = collections.deque()
def _update_arrived_deque(self, timestamp):
while self._pending_deque and self._pending_deque[0].arrival <= timestamp:
self._arrived_deque.append(self._pending_deque.popleft())
@property
def shape(self):
return self._buffered_shape
@property
def dtype(self):
return self._dtype
def insert(self, timestamp, delay, value):
"""Inserts a new observation to the buffer.
This function implicitly updates the internal "clock" of this buffer to
the timestamp of the new observation, and the internal buffer is trimmed
accordingly, i.e. at most `buffer_size` items whose delayed arrival time
preceeds `timestamp` are kept.
Args:
timestamp: The time at which this observation was made.
delay: The amount of delay between the time at which this observation was
made and the time at which it is delivered.
value: The value of this observation.
Raises:
ValueError: if `delay` is negative.
"""
# If using `pad_with_initial_value`, the `arrived_deque` would be empty.
# We can now pad it with the initial value now.
if not self._arrived_deque:
for _ in range(self._buffer_size):
self._arrived_deque.append(InFlightObservation(-np.inf, 0, value))
self._update_arrived_deque(timestamp)
new_obs = InFlightObservation(timestamp, delay, np.array(value))
arrival = new_obs.arrival
if delay == 0:
# No delay, so the new observation is due for immediate delivery.
# Add it to the arrived deque.
self._arrived_deque.append(new_obs)
elif delay > 0:
if not self._pending_deque or arrival > self._pending_deque[-1].arrival:
# New observation's arrival time is monotonic.
# Technically, we can handle this in the general code branch below,
# but since this is assumed to be the "typical" case, the special
# handling here saves us from repeatedly allocating and deallocating
# an empty temporary deque.
self._pending_deque.append(new_obs)
else:
# General, out-of-order observation.
arriving_after_new_obs = collections.deque()
while self._pending_deque and arrival < self._pending_deque[-1].arrival:
arriving_after_new_obs.appendleft(self._pending_deque.pop())
self._pending_deque.append(new_obs)
for existing_obs in arriving_after_new_obs:
self._pending_deque.append(existing_obs)
else:
raise ValueError('`delay` should not be negative: '
'got {!r}'.format(delay))
def read(self, current_time):
"""Reads the content of the buffer at the given timestamp."""
self._update_arrived_deque(current_time)
if self._has_buffer_dim:
out = np.empty(self._buffered_shape, dtype=self._dtype)
for i, obs in enumerate(self._arrived_deque):
out[i] = obs.value
else:
out = self._arrived_deque[0].value.copy()
return out
def drop_unobserved_upcoming_items(self, observation_schedule, read_interval):
"""Plans an optimal observation schedule for an upcoming control period.
This function determines which of the proposed upcoming observations will
never in fact be delivered and removes them from the observation schedule.
We assume that observations will only be queried at times that are integer
multiples of `read_interval`. If more observations are generated during
the upcoming control step than the `buffer_size` of this `Buffer`
then of those new observations will never be required. This function takes
into account the delayed arrival time and existing buffered items in the
planning process.
Args:
observation_schedule: An list of `(timestamp, delay)` tuples, where
`timestamp` is the time at which the observation value will be produced,
and `delay` is the amount of time the observation will be delayed by.
This list will be modified in place.
read_interval: The time interval between successive calls to `read`.
We assume that observations will only be queried at times that are
integer multiples of `read_interval`.
"""
# Private deques to simulate what the deques will look like in the future,
# according to the proposed upcoming observation schedule.
future_arrived_deque = collections.deque()
future_pending_deque = collections.deque()
# Take existing buffered observations into account when planning the
# upcoming schedule.
def get_next_existing_timestamp():
for obs in reversed(self._pending_deque):
yield InFlightObservation(obs.timestamp, obs.delay, None)
while True:
yield InFlightObservation(-np.inf, 0, None)
existing_timestamp_iter = get_next_existing_timestamp()
existing_timestamp = next(existing_timestamp_iter)
# Build the simulated state of the pending deque at the end of the proposed
# schedule.
sorted_schedule = sorted([InFlightObservation(time[0], time[1], None)
for time in observation_schedule])
for new_timestamp in reversed(sorted_schedule):
# We don't need to worry about any existing item that are delivered before
# the first new item, since those are purged independently of our
# proposed new observations.
while existing_timestamp.arrival > new_timestamp.arrival:
future_pending_deque.appendleft(existing_timestamp)
existing_timestamp = next(existing_timestamp_iter)
future_pending_deque.appendleft(new_timestamp)
# Find the next timestep at which `read` is called.
first_proposed_timestamp = min(t for t, _ in observation_schedule)
next_read_time = read_interval * int(np.ceil(
first_proposed_timestamp // read_interval))
# Build the simulated state of the arrived deque at each subsequent
# control steps.
while future_pending_deque:
# Keep track of observations that are delivered for the first time
# during this control timestep.
newly_arrived = collections.deque()
while (future_pending_deque and
future_pending_deque[0].arrival <= next_read_time):
# `fake_observation` is an `InFlightObservation` without `value`.
fake_observation = future_pending_deque.popleft()
future_arrived_deque.append(fake_observation)
newly_arrived.append(fake_observation)
while len(future_arrived_deque) > self._buffer_size:
stale = future_arrived_deque.popleft()
# Newly-arrived items that become immediately stale are never actually
# delivered.
if newly_arrived and stale == newly_arrived[0]:
newly_arrived.popleft()
# `stale` might either be one of the existing pending observations or
# from the proposed schedule.
if stale.timestamp >= first_proposed_timestamp:
observation_schedule.remove((stale.timestamp, stale.delay))
next_read_time += read_interval
| dm_control-main | dm_control/composer/observation/obs_buffer.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""A fake Physics class for unit testing observation framework."""
import contextlib
from dm_control.composer.observation import observable
from dm_control.rl import control
import numpy as np
class FakePhysics(control.Physics):
"""A fake Physics class for unit testing observation framework."""
def __init__(self):
self._step_counter = 0
self._observables = {
'twice': observable.Generic(FakePhysics.twice),
'repeated': observable.Generic(FakePhysics.repeated, update_interval=5),
'matrix': observable.Generic(FakePhysics.matrix, update_interval=3)
}
def step(self, sub_steps=1):
self._step_counter += 1
@property
def observables(self):
return self._observables
def twice(self):
return 2*self._step_counter
def repeated(self):
return [self._step_counter, self._step_counter]
def sqrt(self):
return np.sqrt(self._step_counter)
def sqrt_plus_one(self):
return np.sqrt(self._step_counter) + 1
def matrix(self):
return [[self._step_counter] * 3] * 2
def time(self):
return self._step_counter
def timestep(self):
return 1.0
def set_control(self, ctrl):
pass
def reset(self):
self._step_counter = 0
def after_reset(self):
pass
@contextlib.contextmanager
def suppress_physics_errors(self):
yield
| dm_control-main | dm_control/composer/observation/fake_physics.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for observable classes."""
from absl.testing import absltest
from dm_control import mujoco
from dm_control.composer.observation import fake_physics
from dm_control.composer.observation.observable import base
import numpy as np
_MJCF = """
<mujoco>
<worldbody>
<light pos="0 0 1"/>
<body name="body" pos="0 0 0">
<joint name="my_hinge" type="hinge" pos="-.1 -.2 -.3" axis="1 -1 0"/>
<geom name="my_box" type="box" size=".1 .2 .3" rgba="0 0 1 1"/>
<geom name="small_sphere" type="sphere" size=".12" pos=".1 .2 .3"/>
</body>
<camera name="world" mode="targetbody" target="body" pos="1 1 1" />
</worldbody>
</mujoco>
"""
class _FakeBaseObservable(base.Observable):
def _callable(self, physics):
pass
class ObservableTest(absltest.TestCase):
def testBaseProperties(self):
fake_observable = _FakeBaseObservable(update_interval=42,
buffer_size=5,
delay=10,
aggregator=None,
corruptor=None)
self.assertEqual(fake_observable.update_interval, 42)
self.assertEqual(fake_observable.buffer_size, 5)
self.assertEqual(fake_observable.delay, 10)
fake_observable.update_interval = 48
self.assertEqual(fake_observable.update_interval, 48)
fake_observable.buffer_size = 7
self.assertEqual(fake_observable.buffer_size, 7)
fake_observable.delay = 13
self.assertEqual(fake_observable.delay, 13)
enabled = not fake_observable.enabled
fake_observable.enabled = not fake_observable.enabled
self.assertEqual(fake_observable.enabled, enabled)
def testGeneric(self):
physics = fake_physics.FakePhysics()
repeated_observable = base.Generic(
fake_physics.FakePhysics.repeated, update_interval=42)
repeated_observation = repeated_observable.observation_callable(physics)()
self.assertEqual(repeated_observable.update_interval, 42)
np.testing.assert_array_equal(repeated_observation, [0, 0])
def testMujocoFeature(self):
physics = mujoco.Physics.from_xml_string(_MJCF)
hinge_observable = base.MujocoFeature(
kind='qpos', feature_name='my_hinge')
hinge_observation = hinge_observable.observation_callable(physics)()
np.testing.assert_array_equal(
hinge_observation, physics.named.data.qpos['my_hinge'])
box_observable = base.MujocoFeature(
kind='geom_xpos', feature_name='small_sphere', update_interval=5)
box_observation = box_observable.observation_callable(physics)()
self.assertEqual(box_observable.update_interval, 5)
np.testing.assert_array_equal(
box_observation, physics.named.data.geom_xpos['small_sphere'])
observable_from_callable = base.MujocoFeature(
kind='geom_xpos', feature_name=lambda: ['my_box', 'small_sphere'])
observation_from_callable = (
observable_from_callable.observation_callable(physics)())
np.testing.assert_array_equal(
observation_from_callable,
physics.named.data.geom_xpos[['my_box', 'small_sphere']])
def testMujocoCamera(self):
physics = mujoco.Physics.from_xml_string(_MJCF)
camera_observable = base.MujocoCamera(
camera_name='world', height=480, width=640, update_interval=7)
self.assertEqual(camera_observable.update_interval, 7)
camera_observation = camera_observable.observation_callable(physics)()
np.testing.assert_array_equal(
camera_observation, physics.render(480, 640, 'world'))
self.assertEqual(camera_observation.shape,
camera_observable.array_spec.shape)
self.assertEqual(camera_observation.dtype,
camera_observable.array_spec.dtype)
camera_observable.height = 300
camera_observable.width = 400
camera_observation = camera_observable.observation_callable(physics)()
self.assertEqual(camera_observable.height, 300)
self.assertEqual(camera_observable.width, 400)
np.testing.assert_array_equal(
camera_observation, physics.render(300, 400, 'world'))
self.assertEqual(camera_observation.shape,
camera_observable.array_spec.shape)
self.assertEqual(camera_observation.dtype,
camera_observable.array_spec.dtype)
def testCorruptor(self):
physics = fake_physics.FakePhysics()
def add_twelve(old_value, random_state):
del random_state # Unused.
return [x + 12 for x in old_value]
repeated_observable = base.Generic(
fake_physics.FakePhysics.repeated, corruptor=add_twelve)
corrupted = repeated_observable.observation_callable(
physics=physics, random_state=None)()
np.testing.assert_array_equal(corrupted, [12, 12])
def testInvalidAggregatorName(self):
name = 'invalid_name'
with self.assertRaisesRegex(KeyError, 'Unrecognized aggregator name'):
_ = _FakeBaseObservable(update_interval=3, buffer_size=2, delay=1,
aggregator=name, corruptor=None)
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/composer/observation/observable/base_test.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Module for observables in the Composer library."""
from dm_control.composer.observation.observable.base import Generic
from dm_control.composer.observation.observable.base import MujocoCamera
from dm_control.composer.observation.observable.base import MujocoFeature
from dm_control.composer.observation.observable.base import Observable
from dm_control.composer.observation.observable.mjcf import MJCFCamera
from dm_control.composer.observation.observable.mjcf import MJCFFeature
| dm_control-main | dm_control/composer/observation/observable/__init__.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for mjcf observables."""
from absl.testing import absltest
from absl.testing import parameterized
from dm_control import mjcf
from dm_control.composer.observation.observable import mjcf as mjcf_observable
from dm_env import specs
import numpy as np
_MJCF = """
<mujoco>
<worldbody>
<light pos="0 0 1"/>
<body name="body" pos="0 0 0">
<joint name="my_hinge" type="hinge" pos="-.1 -.2 -.3" axis="1 -1 0"/>
<geom name="my_box" type="box" size=".1 .2 .3" rgba="0 0 1 1"/>
<geom name="small_sphere" type="sphere" size=".12" pos=".1 .2 .3"/>
</body>
<camera name="world" mode="targetbody" target="body" pos="1 1 1" />
</worldbody>
</mujoco>
"""
class ObservableTest(parameterized.TestCase):
def testMJCFFeature(self):
mjcf_root = mjcf.from_xml_string(_MJCF)
physics = mjcf.Physics.from_mjcf_model(mjcf_root)
my_hinge = mjcf_root.find('joint', 'my_hinge')
hinge_observable = mjcf_observable.MJCFFeature(
kind='qpos', mjcf_element=my_hinge)
hinge_observation = hinge_observable.observation_callable(physics)()
np.testing.assert_array_equal(
hinge_observation, physics.named.data.qpos[my_hinge.full_identifier])
small_sphere = mjcf_root.find('geom', 'small_sphere')
sphere_observable = mjcf_observable.MJCFFeature(
kind='xpos', mjcf_element=small_sphere, update_interval=5)
sphere_observation = sphere_observable.observation_callable(physics)()
self.assertEqual(sphere_observable.update_interval, 5)
np.testing.assert_array_equal(
sphere_observation, physics.named.data.geom_xpos[
small_sphere.full_identifier])
my_box = mjcf_root.find('geom', 'my_box')
list_observable = mjcf_observable.MJCFFeature(
kind='xpos', mjcf_element=[my_box, small_sphere])
list_observation = (
list_observable.observation_callable(physics)())
np.testing.assert_array_equal(
list_observation,
physics.named.data.geom_xpos[[my_box.full_identifier,
small_sphere.full_identifier]])
with self.assertRaisesRegex(ValueError, 'expected an `mjcf.Element`'):
mjcf_observable.MJCFFeature('qpos', 'my_hinge')
with self.assertRaisesRegex(ValueError, 'expected an `mjcf.Element`'):
mjcf_observable.MJCFFeature('geom_xpos', [my_box, 'small_sphere'])
def testMJCFFeatureIndex(self):
mjcf_root = mjcf.from_xml_string(_MJCF)
physics = mjcf.Physics.from_mjcf_model(mjcf_root)
small_sphere = mjcf_root.find('geom', 'small_sphere')
sphere_xmat = np.array(
physics.named.data.geom_xmat[small_sphere.full_identifier])
observable_xrow = mjcf_observable.MJCFFeature(
'xmat', small_sphere, index=[1, 3, 5, 7])
np.testing.assert_array_equal(
observable_xrow.observation_callable(physics)(),
sphere_xmat[[1, 3, 5, 7]])
observable_yyzz = mjcf_observable.MJCFFeature('xmat', small_sphere)[2:6]
np.testing.assert_array_equal(
observable_yyzz.observation_callable(physics)(), sphere_xmat[2:6])
def testMJCFCamera(self):
mjcf_root = mjcf.from_xml_string(_MJCF)
physics = mjcf.Physics.from_mjcf_model(mjcf_root)
camera = mjcf_root.find('camera', 'world')
camera_observable = mjcf_observable.MJCFCamera(
mjcf_element=camera, height=480, width=640, update_interval=7)
self.assertEqual(camera_observable.update_interval, 7)
camera_observation = camera_observable.observation_callable(physics)()
np.testing.assert_array_equal(
camera_observation, physics.render(480, 640, 'world'))
self.assertEqual(camera_observation.shape,
camera_observable.array_spec.shape)
self.assertEqual(camera_observation.dtype,
camera_observable.array_spec.dtype)
camera_observable.height = 300
camera_observable.width = 400
camera_observation = camera_observable.observation_callable(physics)()
self.assertEqual(camera_observable.height, 300)
self.assertEqual(camera_observable.width, 400)
np.testing.assert_array_equal(
camera_observation, physics.render(300, 400, 'world'))
self.assertEqual(camera_observation.shape,
camera_observable.array_spec.shape)
self.assertEqual(camera_observation.dtype,
camera_observable.array_spec.dtype)
with self.assertRaisesRegex(ValueError, 'expected an `mjcf.Element`'):
mjcf_observable.MJCFCamera('world')
with self.assertRaisesRegex(ValueError, 'expected an `mjcf.Element`'):
mjcf_observable.MJCFCamera([camera])
with self.assertRaisesRegex(ValueError, 'expected a <camera>'):
mjcf_observable.MJCFCamera(mjcf_root.find('body', 'body'))
@parameterized.parameters(
dict(camera_type='rgb', channels=3, dtype=np.uint8,
minimum=0, maximum=255),
dict(camera_type='depth', channels=1, dtype=np.float32,
minimum=0., maximum=np.inf),
dict(camera_type='segmentation', channels=2, dtype=np.int32,
minimum=-1, maximum=np.iinfo(np.int32).max),
)
def testMJCFCameraSpecs(self, camera_type, channels, dtype, minimum, maximum):
width = 640
height = 480
shape = (height, width, channels)
expected_spec = specs.BoundedArray(
shape=shape, dtype=dtype, minimum=minimum, maximum=maximum)
mjcf_root = mjcf.from_xml_string(_MJCF)
camera = mjcf_root.find('camera', 'world')
observable_kwargs = {} if camera_type == 'rgb' else {camera_type: True}
camera_observable = mjcf_observable.MJCFCamera(
mjcf_element=camera, height=height, width=width, update_interval=7,
**observable_kwargs)
self.assertEqual(camera_observable.array_spec, expected_spec)
def testMJCFSegCamera(self):
mjcf_root = mjcf.from_xml_string(_MJCF)
physics = mjcf.Physics.from_mjcf_model(mjcf_root)
camera = mjcf_root.find('camera', 'world')
camera_observable = mjcf_observable.MJCFCamera(
mjcf_element=camera, height=480, width=640, update_interval=7,
segmentation=True)
self.assertEqual(camera_observable.update_interval, 7)
camera_observation = camera_observable.observation_callable(physics)()
np.testing.assert_array_equal(
camera_observation,
physics.render(480, 640, 'world', segmentation=True))
camera_observable.array_spec.validate(camera_observation)
def testErrorIfSegmentationAndDepthBothEnabled(self):
camera = mjcf.from_xml_string(_MJCF).find('camera', 'world')
with self.assertRaisesWithLiteralMatch(
ValueError, mjcf_observable._BOTH_SEGMENTATION_AND_DEPTH_ENABLED):
mjcf_observable.MJCFCamera(mjcf_element=camera, segmentation=True,
depth=True)
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/composer/observation/observable/mjcf_test.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Classes representing observables."""
import abc
import functools
from dm_env import specs
import numpy as np
def _make_aggregator(np_reducer_func, bounds_preserving):
result = functools.partial(np_reducer_func, axis=0)
setattr(result, 'bounds_reserving', bounds_preserving)
return result
AGGREGATORS = {
'min': _make_aggregator(np.min, True),
'max': _make_aggregator(np.max, True),
'mean': _make_aggregator(np.mean, True),
'median': _make_aggregator(np.median, True),
'sum': _make_aggregator(np.sum, False),
}
def _get_aggregator(name_or_callable):
"""Returns aggregator from predefined set by name, else returns callable."""
if name_or_callable is None:
return None
elif not callable(name_or_callable):
try:
return AGGREGATORS[name_or_callable]
except KeyError:
raise KeyError('Unrecognized aggregator name: {!r}. Valid names: {}.'
.format(name_or_callable, AGGREGATORS.keys()))
else:
return name_or_callable
class Observable(metaclass=abc.ABCMeta):
"""Abstract base class for an observable."""
def __init__(self, update_interval, buffer_size, delay,
aggregator, corruptor):
self._update_interval = update_interval
self._buffer_size = buffer_size
self._delay = delay
self._aggregator = _get_aggregator(aggregator)
self._corruptor = corruptor
self._enabled = False
@property
def update_interval(self):
return self._update_interval
@update_interval.setter
def update_interval(self, value):
self._update_interval = value
@property
def buffer_size(self):
return self._buffer_size
@buffer_size.setter
def buffer_size(self, value):
self._buffer_size = value
@property
def delay(self):
return self._delay
@delay.setter
def delay(self, value):
self._delay = value
@property
def aggregator(self):
return self._aggregator
@aggregator.setter
def aggregator(self, value):
self._aggregator = _get_aggregator(value)
@property
def corruptor(self):
return self._corruptor
@corruptor.setter
def corruptor(self, value):
self._corruptor = value
@property
def enabled(self):
return self._enabled
@enabled.setter
def enabled(self, value):
self._enabled = value
@property
def array_spec(self):
"""The `ArraySpec` which describes observation arrays from this observable.
If this property is `None`, then the specification should be inferred by
actually retrieving an observation from this observable.
"""
return None
@abc.abstractmethod
def _callable(self, physics):
pass
def observation_callable(self, physics, random_state=None):
"""A callable which returns a (potentially corrupted) observation."""
raw_callable = self._callable(physics)
if self._corruptor:
def _corrupted():
return self._corruptor(raw_callable(), random_state=random_state)
return _corrupted
else:
return raw_callable
def __call__(self, physics, random_state=None):
"""Convenience function to just call an observable."""
return self.observation_callable(physics, random_state)()
def configure(self, **kwargs):
"""Sets multiple attributes of this observable.
Args:
**kwargs: The keyword argument names correspond to the attributes
being modified.
Raises:
AttributeError: If kwargs contained an attribute not in the observable.
"""
for key, value in kwargs.items():
if not hasattr(self, key):
raise AttributeError('Cannot add attribute %s in configure.' % key)
self.__setattr__(key, value)
class Generic(Observable):
"""A generic observable defined via a callable."""
def __init__(self, raw_observation_callable, update_interval=1,
buffer_size=None, delay=None,
aggregator=None, corruptor=None):
"""Initializes this observable.
Args:
raw_observation_callable: A callable which accepts a single argument of
type `control.base.Physics` and returns the observation value.
update_interval: (optional) An integer, number of simulation steps between
successive updates to the value of this observable.
buffer_size: (optional) The maximum size of the returned buffer.
This option is only relevant when used in conjunction with an
`observation.Updater`. If None, `observation.DEFAULT_BUFFER_SIZE` will
be used.
delay: (optional) Number of additional simulation steps that must be
taken before an observation is returned. This option is only relevant
when used in conjunction with an`observation.Updater`. If None,
`observation.DEFAULT_DELAY` will be used.
aggregator: (optional) Name of an item in `AGGREGATORS` or a callable that
performs a reduction operation over the first dimension of the buffered
observation before it is returned. A value of `None` means that no
aggregation will be performed and the whole buffer will be returned.
corruptor: (optional) A callable which takes a single observation as
an argument, modifies it, and returns it. An example use case for this
is to add random noise to the observation. When used in a
`BufferedWrapper`, the corruptor is applied to the observation before
it is added to the buffer. In particular, this means that the aggregator
operates on corrupted observations.
"""
self._raw_callable = raw_observation_callable
super().__init__(update_interval, buffer_size, delay, aggregator, corruptor)
def _callable(self, physics):
return lambda: self._raw_callable(physics)
class MujocoFeature(Observable):
"""An observable corresponding to a named MuJoCo feature."""
def __init__(self, kind, feature_name, update_interval=1,
buffer_size=None, delay=None,
aggregator=None, corruptor=None):
"""Initializes this observable.
Args:
kind: A string corresponding to a field name in MuJoCo's mjData struct.
feature_name: A string, or list of strings, or a callable returning
either, corresponding to the name(s) of an entity in the
MuJoCo XML model.
update_interval: (optional) An integer, number of simulation steps between
successive updates to the value of this observable.
buffer_size: (optional) The maximum size of the returned buffer.
This option is only relevant when used in conjunction with an
`observation.Updater`. If None, `observation.DEFAULT_BUFFER_SIZE` will
be used.
delay: (optional) Number of additional simulation steps that must be
taken before an observation is returned. This option is only relevant
when used in conjunction with an`observation.Updater`. If None,
`observation.DEFAULT_DELAY` will be used.
aggregator: (optional) Name of an item in `AGGREGATORS` or a callable that
performs a reduction operation over the first dimension of the buffered
observation before it is returned. A value of `None` means that no
aggregation will be performed and the whole buffer will be returned.
corruptor: (optional) A callable which takes a single observation as
an argument, modifies it, and returns it. An example use case for this
is to add random noise to the observation. When used in a
`BufferedWrapper`, the corruptor is applied to the observation before
it is added to the buffer. In particular, this means that the aggregator
operates on corrupted observations.
"""
self._kind = kind
self._feature_name = feature_name
super().__init__(update_interval, buffer_size, delay, aggregator, corruptor)
def _callable(self, physics):
named_indexer_for_kind = physics.named.data.__getattribute__(self._kind)
if callable(self._feature_name):
return lambda: named_indexer_for_kind[self._feature_name()]
else:
return lambda: named_indexer_for_kind[self._feature_name]
class MujocoCamera(Observable):
"""An observable corresponding to a MuJoCo camera."""
def __init__(self, camera_name, height=240, width=320, update_interval=1,
buffer_size=None, delay=None,
aggregator=None, corruptor=None, depth=False):
"""Initializes this observable.
Args:
camera_name: A string corresponding to the name of a camera in the
MuJoCo XML model.
height: (optional) An integer, the height of the rendered image.
width: (optional) An integer, the width of the rendered image.
update_interval: (optional) An integer, number of simulation steps between
successive updates to the value of this observable.
buffer_size: (optional) The maximum size of the returned buffer.
This option is only relevant when used in conjunction with an
`observation.Updater`. If None, `observation.DEFAULT_BUFFER_SIZE` will
be used.
delay: (optional) Number of additional simulation steps that must be
taken before an observation is returned. This option is only relevant
when used in conjunction with an`observation.Updater`. If None,
`observation.DEFAULT_DELAY` will be used.
aggregator: (optional) Name of an item in `AGGREGATORS` or a callable that
performs a reduction operation over the first dimension of the buffered
observation before it is returned. A value of `None` means that no
aggregation will be performed and the whole buffer will be returned.
corruptor: (optional) A callable which takes a single observation as
an argument, modifies it, and returns it. An example use case for this
is to add random noise to the observation. When used in a
`BufferedWrapper`, the corruptor is applied to the observation before
it is added to the buffer. In particular, this means that the aggregator
operates on corrupted observations.
depth: (optional) A boolean. If `True`, renders a depth image (1-channel)
instead of RGB (3-channel).
"""
self._camera_name = camera_name
self._height = height
self._width = width
self._n_channels = 1 if depth else 3
self._dtype = np.float32 if depth else np.uint8
self._depth = depth
super().__init__(update_interval, buffer_size, delay, aggregator, corruptor)
@property
def height(self):
return self._height
@height.setter
def height(self, value):
self._height = value
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
@property
def array_spec(self):
return specs.Array(
shape=(self._height, self._width, self._n_channels), dtype=self._dtype)
def _callable(self, physics):
return lambda: physics.render( # pylint: disable=g-long-lambda
self._height, self._width, self._camera_name, depth=self._depth)
| dm_control-main | dm_control/composer/observation/observable/base.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Observables that are defined in terms of MJCF elements."""
import collections
from dm_control import mjcf
from dm_control.composer.observation.observable import base
from dm_env import specs
import numpy as np
_BOTH_SEGMENTATION_AND_DEPTH_ENABLED = (
'`segmentation` and `depth` cannot both be `True`.')
def _check_mjcf_element(obj):
if not isinstance(obj, mjcf.Element):
raise ValueError(
'expected an `mjcf.Element`, got type {}: {}'.format(type(obj), obj))
def _check_mjcf_element_iterable(obj_iterable):
if not isinstance(obj_iterable, collections.abc.Iterable):
obj_iterable = (obj_iterable,)
for obj in obj_iterable:
_check_mjcf_element(obj)
class MJCFFeature(base.Observable):
"""An observable corresponding to an element in an MJCF model."""
def __init__(self, kind, mjcf_element, update_interval=1,
buffer_size=None, delay=None,
aggregator=None, corruptor=None, index=None):
"""Initializes this observable.
Args:
kind: The name of an attribute of a bound `mjcf.Physics` instance. See the
docstring for `mjcf.Physics.bind()` for examples showing this syntax.
mjcf_element: An `mjcf.Element`, or iterable of `mjcf.Element`.
update_interval: (optional) An integer, number of simulation steps between
successive updates to the value of this observable.
buffer_size: (optional) The maximum size of the returned buffer.
This option is only relevant when used in conjunction with an
`observation.Updater`. If None, `observation.DEFAULT_BUFFER_SIZE` will
be used.
delay: (optional) Number of additional simulation steps that must be
taken before an observation is returned. This option is only relevant
when used in conjunction with an`observation.Updater`. If None,
`observation.DEFAULT_DELAY` will be used.
aggregator: (optional) Name of an item in `AGGREGATORS` or a callable that
performs a reduction operation over the first dimension of the buffered
observation before it is returned. A value of `None` means that no
aggregation will be performed and the whole buffer will be returned.
corruptor: (optional) A callable which takes a single observation as
an argument, modifies it, and returns it. An example use case for this
is to add random noise to the observation. When used in a
`BufferedWrapper`, the corruptor is applied to the observation before
it is added to the buffer. In particular, this means that the aggregator
operates on corrupted observations.
index: (optional) An index that is to be applied to an array attribute
to pick out a slice or particular items. As a syntactic sugar,
`MJCFFeature` also implements `__getitem__` that returns a copy of the
same observable with an index applied.
Raises:
ValueError: if `mjcf_element` is not an `mjcf.Element`.
"""
_check_mjcf_element_iterable(mjcf_element)
self._kind = kind
self._mjcf_element = mjcf_element
self._index = index
super().__init__(update_interval, buffer_size, delay, aggregator, corruptor)
def _callable(self, physics):
binding = physics.bind(self._mjcf_element)
if self._index is not None:
return lambda: getattr(binding, self._kind)[self._index]
else:
return lambda: getattr(binding, self._kind)
def __getitem__(self, key):
if self._index is not None:
raise NotImplementedError(
'slicing an already-sliced MJCFFeature observable is not supported')
return MJCFFeature(self._kind, self._mjcf_element, self._update_interval,
self._buffer_size, self._delay, self._aggregator,
self._corruptor, key)
class MJCFCamera(base.Observable):
"""An observable corresponding to a camera in an MJCF model."""
def __init__(self,
mjcf_element,
height=240,
width=320,
update_interval=1,
buffer_size=None,
delay=None,
aggregator=None,
corruptor=None,
depth=False,
segmentation=False,
scene_option=None,
render_flag_overrides=None):
"""Initializes this observable.
Args:
mjcf_element: A <camera> `mjcf.Element`.
height: (optional) An integer, the height of the rendered image.
width: (optional) An integer, the width of the rendered image.
update_interval: (optional) An integer, number of simulation steps between
successive updates to the value of this observable.
buffer_size: (optional) The maximum size of the returned buffer.
This option is only relevant when used in conjunction with an
`observation.Updater`. If None, `observation.DEFAULT_BUFFER_SIZE` will
be used.
delay: (optional) Number of additional simulation steps that must be
taken before an observation is returned. This option is only relevant
when used in conjunction with an`observation.Updater`. If None,
`observation.DEFAULT_DELAY` will be used.
aggregator: (optional) Name of an item in `AGGREGATORS` or a callable that
performs a reduction operation over the first dimension of the buffered
observation before it is returned. A value of `None` means that no
aggregation will be performed and the whole buffer will be returned.
corruptor: (optional) A callable which takes a single observation as
an argument, modifies it, and returns it. An example use case for this
is to add random noise to the observation. When used in a
`BufferedWrapper`, the corruptor is applied to the observation before
it is added to the buffer. In particular, this means that the aggregator
operates on corrupted observations.
depth: (optional) A boolean. If `True`, renders a depth image (1-channel)
instead of RGB (3-channel).
segmentation: (optional) A boolean. If `True`, renders a segmentation mask
(2-channel, int32) labeling the objects in the scene with their
(mjModel ID, mjtObj enum object type) pair. Background pixels are
set to (-1, -1).
scene_option: An optional `wrapper.MjvOption` instance that can be used to
render the scene with custom visualization options. If None then the
default options will be used.
render_flag_overrides: Optional mapping specifying rendering flags to
override. The keys can be either lowercase strings or `mjtRndFlag` enum
values, and the values are the overridden flag values, e.g.
`{'wireframe': True}` or `{mujoco.mjtRndFlag.mjRND_WIREFRAME: True}`.
See `mujoco.mjtRndFlag` for the set of valid flags. Must be None if
either `depth` or `segmentation` is True.
Raises:
ValueError: if `mjcf_element` is not a <camera> element.
ValueError: if segmentation and depth flags are both set to True.
"""
_check_mjcf_element(mjcf_element)
if mjcf_element.tag != 'camera':
raise ValueError(
'expected a <camera> element: got {}'.format(mjcf_element))
self._mjcf_element = mjcf_element
self._height = height
self._width = width
if segmentation and depth:
raise ValueError(_BOTH_SEGMENTATION_AND_DEPTH_ENABLED)
if segmentation:
self._dtype = np.int32
self._n_channels = 2
elif depth:
self._dtype = np.float32
self._n_channels = 1
else:
self._dtype = np.uint8
self._n_channels = 3
self._depth = depth
self._segmentation = segmentation
self._scene_option = scene_option
self._render_flag_overrides = render_flag_overrides
super().__init__(update_interval, buffer_size, delay, aggregator, corruptor)
@property
def height(self):
return self._height
@height.setter
def height(self, value):
self._height = value
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
@property
def depth(self):
return self._depth
@depth.setter
def depth(self, value):
self._depth = value
@property
def segmentation(self):
return self._segmentation
@segmentation.setter
def segmentation(self, value):
self._segmentation = value
@property
def scene_option(self):
return self._scene_option
@scene_option.setter
def scene_option(self, value):
self._scene_option = value
@property
def render_flag_overrides(self):
return self._render_flag_overrides
@render_flag_overrides.setter
def render_flag_overrides(self, value):
self._render_flag_overrides = value
@property
def array_spec(self):
if self._depth:
# Note that these are loose bounds - the exact bounds are given by:
# extent*(znear, zfar), however the values of these parameters are unknown
# since we don't have access to the compiled model within this method.
minimum = 0.0
maximum = np.inf
elif self._segmentation:
# -1 denotes background pixels. See dm_control.mujoco.Camera.render for
# further details.
minimum = -1
maximum = np.iinfo(self._dtype).max
else:
minimum = np.iinfo(self._dtype).min
maximum = np.iinfo(self._dtype).max
return specs.BoundedArray(
minimum=minimum,
maximum=maximum,
shape=(self._height, self._width, self._n_channels),
dtype=self._dtype)
def _callable(self, physics):
def get_observation():
pixels = physics.render(
height=self._height,
width=self._width,
camera_id=self._mjcf_element.full_identifier,
depth=self._depth,
segmentation=self._segmentation,
scene_option=self._scene_option,
render_flag_overrides=self._render_flag_overrides)
return np.atleast_3d(pixels)
return get_observation
| dm_control-main | dm_control/composer/observation/observable/mjcf.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for prop_initializer."""
from absl.testing import absltest
from absl.testing import parameterized
from dm_control import composer
from dm_control import mjcf
from dm_control.composer.initializers import prop_initializer
from dm_control.composer.variation import distributions
from dm_control.entities import props
import numpy as np
class _SequentialChoice(distributions.Distribution):
"""Helper class to return samples in order for deterministic testing."""
__slots__ = ()
def __init__(self, choices, single_sample=False):
super().__init__(choices, single_sample=single_sample)
self._idx = 0
def _callable(self, random_state):
def next_item(*args, **kwargs):
del args, kwargs # Unused.
result = self._args[0][self._idx]
self._idx = (self._idx + 1) % len(self._args[0])
return result
return next_item
def _make_spheres(num_spheres, radius, nconmax):
spheres = []
arena = composer.Arena()
arena.mjcf_model.worldbody.add('geom', type='plane', size=[1, 1, 0.1],
pos=[0., 0., -2 * radius], name='ground')
for i in range(num_spheres):
sphere = props.Primitive(
geom_type='sphere', size=[radius], name='sphere_{}'.format(i))
arena.add_free_entity(sphere)
spheres.append(sphere)
arena.mjcf_model.size.nconmax = nconmax
physics = mjcf.Physics.from_mjcf_model(arena.mjcf_model)
return physics, spheres
class PropPlacerTest(parameterized.TestCase):
"""Tests for PropPlacer."""
def assertNoContactsInvolvingEntities(self, physics, entities):
all_colliding_geoms = set()
for contact in physics.data.contact:
all_colliding_geoms.add(contact.geom1)
all_colliding_geoms.add(contact.geom2)
for entity in entities:
entity_geoms = physics.bind(entity.mjcf_model.find_all('geom')).element_id
colliding_entity_geoms = all_colliding_geoms.intersection(entity_geoms)
if colliding_entity_geoms:
names = ', '.join(
physics.model.id2name(i, 'geom') for i in colliding_entity_geoms)
self.fail('Entity {} has colliding geoms: {}'
.format(entity.mjcf_model.model, names))
def assertPositionsWithinBounds(self, physics, entities, lower, upper):
for entity in entities:
position, _ = entity.get_pose(physics)
if np.any(position < lower) or np.any(position > upper):
self.fail('Entity {} is out of bounds: position={}, bounds={}'
.format(entity.mjcf_model.model, position, (lower, upper)))
def test_sample_non_colliding_positions(self):
halfwidth = 0.05
radius = halfwidth / 4.
offset = np.array([0, 0, halfwidth + radius*1.1])
lower = -np.full(3, halfwidth) + offset
upper = np.full(3, halfwidth) + offset
position_variation = distributions.Uniform(lower, upper)
physics, spheres = _make_spheres(num_spheres=8, radius=radius, nconmax=1000)
prop_placer = prop_initializer.PropPlacer(
props=spheres,
position=position_variation,
ignore_collisions=False,
settle_physics=False)
prop_placer(physics, random_state=np.random.RandomState(0))
self.assertNoContactsInvolvingEntities(physics, spheres)
self.assertPositionsWithinBounds(physics, spheres, lower, upper)
def test_rejection_sampling_failure(self):
max_attempts_per_prop = 2
fixed_position = (0, 0, 0.1) # Guaranteed to always have collisions.
physics, spheres = _make_spheres(num_spheres=2, radius=0.01, nconmax=1000)
prop_placer = prop_initializer.PropPlacer(
props=spheres,
position=fixed_position,
ignore_collisions=False,
max_attempts_per_prop=max_attempts_per_prop)
expected_message = prop_initializer._REJECTION_SAMPLING_FAILED.format(
model_name=spheres[1].mjcf_model.model, # Props are placed in order.
max_attempts=max_attempts_per_prop)
with self.assertRaisesWithLiteralMatch(RuntimeError, expected_message):
prop_placer(physics, random_state=np.random.RandomState(0))
def test_ignore_contacts_with_entities(self):
physics, spheres = _make_spheres(num_spheres=2, radius=0.01, nconmax=1000)
# Target position of both spheres (non-colliding).
fixed_positions = [(0, 0, 0.1), (0, 0.1, 0.1)]
# Placer that initializes both spheres to (0, 0, 0.1), ignoring contacts.
prop_placer_init = prop_initializer.PropPlacer(
props=spheres,
position=fixed_positions[0],
ignore_collisions=True,
max_attempts_per_prop=1)
# Sequence of placers that will move the spheres to their target positions.
prop_placer_seq = []
for prop, target_position in zip(spheres, fixed_positions):
placer = prop_initializer.PropPlacer(
props=[prop],
position=target_position,
ignore_collisions=False,
max_attempts_per_prop=1)
prop_placer_seq.append(placer)
# We expect the first placer in the sequence to fail without
# `ignore_contacts_with_entities` because the second sphere is already at
# the same location.
prop_placer_init(physics, random_state=np.random.RandomState(0))
expected_message = prop_initializer._REJECTION_SAMPLING_FAILED.format(
model_name=spheres[0].mjcf_model.model, max_attempts=1)
with self.assertRaisesWithLiteralMatch(RuntimeError, expected_message):
prop_placer_seq[0](physics, random_state=np.random.RandomState(0))
# Placing the first sphere should succeed if we ignore contacts involving
# the second sphere.
prop_placer_init(physics, random_state=np.random.RandomState(0))
prop_placer_seq[0](physics, random_state=np.random.RandomState(0),
ignore_contacts_with_entities=[spheres[1]])
# Now place the second sphere with all collisions active.
prop_placer_seq[1](physics, random_state=np.random.RandomState(0),
ignore_contacts_with_entities=None)
self.assertNoContactsInvolvingEntities(physics, spheres)
@parameterized.parameters([False, True])
def test_settle_physics(self, settle_physics):
radius = 0.1
physics, spheres = _make_spheres(num_spheres=2, radius=radius, nconmax=1)
# Only place the first sphere.
prop_placer = prop_initializer.PropPlacer(
props=spheres[:1],
position=np.array([2.01 * radius, 0., 0.]),
settle_physics=settle_physics)
prop_placer(physics, random_state=np.random.RandomState(0))
first_position, first_quaternion = spheres[0].get_pose(physics)
del first_quaternion # Unused.
# If we allowed the physics to settle then the first sphere should be
# resting on the ground, otherwise it should be at the target height.
expected_first_z_pos = -radius if settle_physics else 0.
self.assertAlmostEqual(first_position[2], expected_first_z_pos, places=3)
second_position, second_quaternion = spheres[1].get_pose(physics)
del second_quaternion # Unused.
# The sphere that we were not placing should not have moved.
self.assertEqual(second_position[2], 0.)
@parameterized.parameters([0, 1, 2, 3])
def test_settle_physics_multiple_attempts(self, max_settle_physics_attempts):
# Tests the multiple-reset mechanism for `settle_physics`.
# Rather than testing the mechanic itself, which is tested above, we instead
# test that the mechanism correctly makes several attempts when it fails
# to settle. We force it to fail by making the settling time short, and
# test that the position is repeatedly called using a deterministic
# sequential pose distribution.
radius = 0.1
physics, spheres = _make_spheres(num_spheres=1, radius=radius, nconmax=1)
# Generate sequence of positions that will be sampled in order.
positions = [
np.array([2.01 * radius, 1., 0.]),
np.array([2.01 * radius, 2., 0.]),
np.array([2.01 * radius, 3., 0.]),
]
positions_dist = _SequentialChoice(positions)
def build_placer():
return prop_initializer.PropPlacer(
props=spheres[:1],
position=positions_dist,
settle_physics=True,
max_settle_physics_time=1e-6, # To ensure that settling FAILS.
max_settle_physics_attempts=max_settle_physics_attempts)
if max_settle_physics_attempts == 0:
with self.assertRaises(ValueError):
build_placer()
else:
prop_placer = build_placer()
prop_placer(physics, random_state=np.random.RandomState(0))
first_position, first_quaternion = spheres[0].get_pose(physics)
del first_quaternion # Unused.
# If we allowed the physics to settle then the first sphere should be
# resting on the ground, otherwise it should be at the target height.
expected_first_y_pos = max_settle_physics_attempts
self.assertAlmostEqual(first_position[1], expected_first_y_pos, places=3)
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/composer/initializers/prop_initializer_test.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""An initializer that places props at various poses."""
from absl import logging
from dm_control import composer
from dm_control import mjcf
from dm_control.composer import variation
from dm_control.composer.initializers import utils
from dm_control.composer.variation import rotations
from dm_control.rl import control
import numpy as np
# Absolute velocity threshold for a prop joint to be considered settled.
_SETTLE_QVEL_TOL = 1e-3
# Absolute acceleration threshold for a prop joint to be considered settled.
_SETTLE_QACC_TOL = 1e-2
_REJECTION_SAMPLING_FAILED = '\n'.join([
'Failed to find a non-colliding pose for prop {model_name!r} within ' # pylint: disable=implicit-str-concat
'{max_attempts} attempts.',
'You may be able to avoid this error by:',
'1. Sampling from a broader distribution over positions and/or quaternions',
'2. Increasing `max_attempts_per_prop`',
'3. Disabling collision detection by setting `ignore_collisions=False`'])
_SETTLING_PHYSICS_FAILED = '\n'.join([
'Failed to settle physics after {max_attempts} attempts of ' # pylint: disable=implicit-str-concat
'{max_time} seconds.',
'Last residual velocity={max_qvel} and acceleration={max_qacc}.',
'This suggests your dynamics are unstable. Consider:',
'\t1. Increasing `max_settle_physics_attempts`',
'\t2. Increasing `max_settle_physics_time`',
'\t3. Tuning your contact parameters or initial pose distributions.'])
class PropPlacer(composer.Initializer):
"""An initializer that places props at various positions and orientations."""
def __init__(self,
props,
position,
quaternion=rotations.IDENTITY_QUATERNION,
ignore_collisions=False,
max_qvel_tol=_SETTLE_QVEL_TOL,
max_qacc_tol=_SETTLE_QACC_TOL,
max_attempts_per_prop=20,
settle_physics=False,
min_settle_physics_time=0.,
max_settle_physics_time=2.,
max_settle_physics_attempts=1,
raise_exception_on_settle_failure=False):
"""Initializes this PropPlacer.
Args:
props: A sequence of `composer.Entity` instances representing props.
position: A single fixed Cartesian position, or a `composer.Variation`
object that generates Cartesian positions. If a fixed sequence of
positions for multiple props is desired, use
`variation.deterministic.Sequence`.
quaternion: (optional) A single fixed unit quaternion, or a
`Variation` object that generates unit quaternions. If a fixed
sequence of quaternions for multiple props is desired, use
`variation.deterministic.Sequence`.
ignore_collisions: (optional) If True, ignore collisions between props,
i.e. do not run rejection sampling.
max_qvel_tol: Maximum post-initialization joint velocity for props. If
`settle_physics=True`, the simulation will be run until all prop joint
velocities are less than this threshold.
max_qacc_tol: Maximum post-initialization joint acceleration for props. If
`settle_physics=True`, the simulation will be run until all prop joint
velocities are less than this threshold.
max_attempts_per_prop: The maximum number of rejection sampling attempts
per prop. If a non-colliding pose cannot be found before this limit is
reached, a `RuntimeError` will be raised.
settle_physics: (optional) If True, the physics simulation will be
advanced for a few steps to allow the prop positions to settle.
min_settle_physics_time: (optional) When `settle_physics` is True, lower
bound on time (in seconds) the physics simulation is advanced.
max_settle_physics_time: (optional) When `settle_physics` is True, upper
bound on time (in seconds) the physics simulation is advanced.
max_settle_physics_attempts: (optional) When `settle_physics` is True, the
number of attempts at sampling overall scene pose and settling.
raise_exception_on_settle_failure: If True, raises an exception if
settling physics is unsuccessful.
"""
super().__init__()
self._props = props
self._prop_joints = []
for prop in props:
freejoint = mjcf.get_frame_freejoint(prop.mjcf_model)
if freejoint is not None:
self._prop_joints.append(freejoint)
self._prop_joints.extend(prop.mjcf_model.find_all('joint'))
self._position = position
self._quaternion = quaternion
self._ignore_collisions = ignore_collisions
self._max_attempts_per_prop = max_attempts_per_prop
self._settle_physics = settle_physics
self._max_qvel_tol = max_qvel_tol
self._max_qacc_tol = max_qacc_tol
self._min_settle_physics_time = min_settle_physics_time
self._max_settle_physics_time = max_settle_physics_time
self._max_settle_physics_attempts = max_settle_physics_attempts
self._raise_exception_on_settle_failure = raise_exception_on_settle_failure
if max_settle_physics_attempts < 1:
raise ValueError('max_settle_physics_attempts should be greater than '
'zero to have any effect, but is '
f'{max_settle_physics_attempts}')
def _has_collisions_with_prop(self, physics, prop):
prop_geom_ids = physics.bind(prop.mjcf_model.find_all('geom')).element_id
contacts = physics.data.contact
for contact in contacts:
# Ignore contacts with positive distances (i.e. not actually touching).
if contact.dist <= 0 and (contact.geom1 in prop_geom_ids or
contact.geom2 in prop_geom_ids):
return True
def _disable_and_cache_contact_parameters(self, physics, props):
cached_contact_params = {}
for prop in props:
geoms = prop.mjcf_model.find_all('geom')
param_list = []
for geom in geoms:
bound_geom = physics.bind(geom)
param_list.append((bound_geom.contype, bound_geom.conaffinity))
bound_geom.contype = 0
bound_geom.conaffinity = 0
cached_contact_params[prop] = param_list
return cached_contact_params
def _restore_contact_parameters(self, physics, prop, cached_contact_params):
geoms = prop.mjcf_model.find_all('geom')
param_list = cached_contact_params[prop]
for i, geom in enumerate(geoms):
contype, conaffinity = param_list[i]
bound_geom = physics.bind(geom)
bound_geom.contype = contype
bound_geom.conaffinity = conaffinity
def __call__(self, physics, random_state, ignore_contacts_with_entities=None):
"""Sets initial prop poses.
Args:
physics: An `mjcf.Physics` instance.
random_state: a `np.random.RandomState` instance.
ignore_contacts_with_entities: a list of `composer.Entity` instances
to ignore when detecting collisions. This can be used to ignore props
that are not being placed by this initializer, but are known to be
colliding in the current state of the simulation (for example if they
are going to be placed by a different initializer that will be called
subsequently).
Raises:
RuntimeError: If `ignore_collisions == False` and a non-colliding prop
pose could not be found within `max_attempts_per_prop`.
"""
if ignore_contacts_with_entities is None:
ignore_contacts_with_entities = []
# Temporarily disable contacts for all geoms that belong to props which
# haven't yet been placed in order to free up space in the contact buffer.
cached_contact_params = self._disable_and_cache_contact_parameters(
physics, self._props + ignore_contacts_with_entities)
try:
physics.forward()
except control.PhysicsError as cause:
effect = control.PhysicsError(
'Despite disabling contact for all props in this initializer, '
'`physics.forward()` resulted in a `PhysicsError`')
raise effect from cause
def place_props():
for prop in self._props:
# Restore the original contact parameters for all geoms in the prop
# we're about to place, so that we can detect if the new pose results in
# collisions.
self._restore_contact_parameters(physics, prop, cached_contact_params)
success = False
initial_position, initial_quaternion = prop.get_pose(physics)
next_position, next_quaternion = initial_position, initial_quaternion
for _ in range(self._max_attempts_per_prop):
next_position = variation.evaluate(self._position,
initial_value=initial_position,
current_value=next_position,
random_state=random_state)
next_quaternion = variation.evaluate(self._quaternion,
initial_value=initial_quaternion,
current_value=next_quaternion,
random_state=random_state)
prop.set_pose(physics, next_position, next_quaternion)
try:
# If this pose results in collisions then there's a chance we'll
# encounter a PhysicsError error here due to a full contact buffer,
# in which case reject this pose and sample another.
physics.forward()
except control.PhysicsError:
continue
if (self._ignore_collisions
or not self._has_collisions_with_prop(physics, prop)):
success = True
break
if not success:
raise RuntimeError(_REJECTION_SAMPLING_FAILED.format(
model_name=prop.mjcf_model.model,
max_attempts=self._max_attempts_per_prop))
for prop in ignore_contacts_with_entities:
self._restore_contact_parameters(physics, prop, cached_contact_params)
# Place the props and settle the physics. If settling was requested and it
# it fails, re-place the props.
def place_and_settle():
for _ in range(self._max_settle_physics_attempts):
place_props()
# Step physics and check prop states.
original_time = physics.data.time
props_isolator = utils.JointStaticIsolator(physics, self._prop_joints)
prop_joints_mj = physics.bind(self._prop_joints)
while physics.data.time - original_time < self._max_settle_physics_time:
with props_isolator:
physics.step()
max_qvel = np.max(np.abs(prop_joints_mj.qvel))
max_qacc = np.max(np.abs(prop_joints_mj.qacc))
if (max_qvel < self._max_qvel_tol) and (
max_qacc < self._max_qacc_tol) and (
physics.data.time - original_time
) > self._min_settle_physics_time:
return True
physics.data.time = original_time
if self._raise_exception_on_settle_failure:
raise RuntimeError(
_SETTLING_PHYSICS_FAILED.format(
max_attempts=self._max_settle_physics_attempts,
max_time=self._max_settle_physics_time,
max_qvel=max_qvel,
max_qacc=max_qacc,
))
else:
log_str = _SETTLING_PHYSICS_FAILED.format(
max_attempts='%s',
max_time='%s',
max_qvel='%s',
max_qacc='%s',
)
logging.warning(log_str, self._max_settle_physics_attempts,
self._max_settle_physics_time, max_qvel, max_qacc)
return False
if self._settle_physics:
place_and_settle()
else:
place_props()
| dm_control-main | dm_control/composer/initializers/prop_initializer.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""An initializer that sets the pose of a hand's tool center point."""
from dm_control import composer
from dm_control import mjcf
from dm_control.composer import variation
from dm_control.entities.manipulators import base
_REJECTION_SAMPLING_FAILED = (
'Failed to find a valid initial configuration for the robot after '
'{max_rejection_samples} TCP poses sampled and up to {max_ik_attempts} '
'initial joint configurations per pose.')
class ToolCenterPointInitializer(composer.Initializer):
"""An initializer that sets the position of a hand's tool center point.
This initializer calls the RobotArm's internal method to try and set the
hand's TCP to a randomized Cartesian position within the specified bound.
By default the initializer performs rejection sampling in order to avoid
poses that result in "relevant collisions", which are defined as:
* Collisions between links of the robot arm
* Collisions between the arm and the hand
* Collisions between either the arm or hand and an external body without a
free joint
"""
def __init__(self,
hand,
arm,
position,
quaternion=base.DOWN_QUATERNION,
ignore_collisions=False,
max_ik_attempts=10,
max_rejection_samples=10):
"""Initializes this ToolCenterPointInitializer.
Args:
hand: Either a `base.RobotHand` instance or None, in which case
`arm.wrist_site` is used as the TCP site in place of
`hand.tool_center_point`.
arm: A `base.RobotArm` instance.
position: A single fixed Cartesian position, or a `Variation`
object that generates Cartesian positions. If a fixed sequence of
positions for multiple props is desired, use
`variation.deterministic.Sequence`.
quaternion: (optional) A single fixed unit quaternion, or a
`composer.Variation` object that generates unit quaternions. If a fixed
sequence of quaternions for ultiple props is desired, use
`variation.deterministic.Sequence`.
ignore_collisions: (optional) If True all collisions are ignored, i.e.
rejection sampling is disabled.
max_ik_attempts: (optional) Maximum number of attempts for the inverse
kinematics solver to find a solution satisfying `target_pos` and
`target_quat`. These are attempts per rejection sample. If more than
one attempt is performed, the joint configuration will be randomized
before the second trial. To avoid randomizing joint positions, set this
parameter to 1.
max_rejection_samples (optional): Maximum number of TCP target poses to
sample while attempting to find a non-colliding configuration. For each
sampled pose, up to `max_ik_attempts` may be performed in order to find
an IK solution satisfying this pose.
"""
super().__init__()
self._arm = arm
self._hand = hand
self._position = position
self._quaternion = quaternion
self._ignore_collisions = ignore_collisions
self._max_ik_attempts = max_ik_attempts
self._max_rejection_samples = max_rejection_samples
def _has_relevant_collisions(self, physics):
mjcf_root = self._arm.mjcf_model.root_model
all_geoms = mjcf_root.find_all('geom')
free_body_geoms = set()
for body in mjcf_root.worldbody.get_children('body'):
if mjcf.get_freejoint(body):
free_body_geoms.update(body.find_all('geom'))
arm_model = self._arm.mjcf_model
hand_model = None
if self._hand is not None:
hand_model = self._hand.mjcf_model
def is_robot(geom):
return geom.root is arm_model or geom.root is hand_model
def is_external_body_without_freejoint(geom):
return not (is_robot(geom) or geom in free_body_geoms)
for contact in physics.data.contact:
geom_1 = all_geoms[contact.geom1]
geom_2 = all_geoms[contact.geom2]
if contact.dist > 0:
# Ignore "contacts" with positive distance (i.e. not actually touching).
continue
if (
# Include arm-arm and arm-hand self-collisions (but not hand-hand).
(geom_1.root is arm_model and geom_2.root is arm_model) or
(geom_1.root is arm_model and geom_2.root is hand_model) or
(geom_1.root is hand_model and geom_2.root is arm_model) or
# Include collisions between the arm or hand and an external body
# provided that the external body does not have a freejoint.
(is_robot(geom_1) and is_external_body_without_freejoint(geom_2)) or
(is_external_body_without_freejoint(geom_1) and is_robot(geom_2))):
return True
return False
def __call__(self, physics, random_state):
"""Sets initial tool center point pose via inverse kinematics.
Args:
physics: An `mjcf.Physics` instance.
random_state: An `np.random.RandomState` instance.
Raises:
RuntimeError: If a collision-free pose could not be found within
`max_ik_attempts`.
"""
if self._hand is not None:
target_site = self._hand.tool_center_point
else:
target_site = self._arm.wrist_site
initial_qpos = physics.bind(self._arm.joints).qpos.copy()
for _ in range(self._max_rejection_samples):
target_pos = variation.evaluate(self._position,
random_state=random_state)
target_quat = variation.evaluate(self._quaternion,
random_state=random_state)
success = self._arm.set_site_to_xpos(
physics=physics, random_state=random_state, site=target_site,
target_pos=target_pos, target_quat=target_quat,
max_ik_attempts=self._max_ik_attempts)
if success:
physics.forward() # Recalculate contacts.
if (self._ignore_collisions
or not self._has_relevant_collisions(physics)):
return
# If IK failed to find a solution for this target pose, or if the solution
# resulted in contacts, then reset the arm joints to their original
# positions and try again with a new target.
physics.bind(self._arm.joints).qpos = initial_qpos
raise RuntimeError(_REJECTION_SAMPLING_FAILED.format(
max_rejection_samples=self._max_rejection_samples,
max_ik_attempts=self._max_ik_attempts))
| dm_control-main | dm_control/composer/initializers/tcp_initializer.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tools for initializing the states of Composer environments."""
from dm_control.composer.initializers.prop_initializer import PropPlacer
from dm_control.composer.initializers.tcp_initializer import ToolCenterPointInitializer
| dm_control-main | dm_control/composer/initializers/__init__.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for tcp_initializer."""
import functools
from absl.testing import absltest
from absl.testing import parameterized
from dm_control import composer
from dm_control import mjcf
from dm_control.composer.initializers import tcp_initializer
from dm_control.entities import props
from dm_control.entities.manipulators import kinova
from dm_control.mujoco.wrapper import mjbindings
import numpy as np
mjlib = mjbindings.mjlib
class TcpInitializerTest(parameterized.TestCase):
def make_model(self, with_hand=True):
arm = kinova.JacoArm()
arena = composer.Arena()
arena.attach(arm)
if with_hand:
hand = kinova.JacoHand()
arm.attach(hand)
else:
hand = None
return arena, arm, hand
def assertTargetPoseAchieved(self, frame_binding, target_pos, target_quat):
np.testing.assert_array_almost_equal(target_pos, frame_binding.xpos)
target_xmat = np.empty(9, np.double)
mjlib.mju_quat2Mat(target_xmat, target_quat / np.linalg.norm(target_quat))
np.testing.assert_array_almost_equal(target_xmat, frame_binding.xmat)
def assertEntitiesInContact(self, physics, first, second):
first_geom_ids = physics.bind(
first.mjcf_model.find_all('geom')).element_id
second_geom_ids = physics.bind(
second.mjcf_model.find_all('geom')).element_id
contact = physics.data.contact
first_to_second = (np.in1d(contact.geom1, first_geom_ids) &
np.in1d(contact.geom2, second_geom_ids))
second_to_first = (np.in1d(contact.geom1, second_geom_ids) &
np.in1d(contact.geom2, first_geom_ids))
touching = contact.dist <= 0
valid_contact = touching & (first_to_second | second_to_first)
self.assertTrue(np.any(valid_contact), msg='Entities are not in contact.')
@parameterized.parameters([
dict(target_pos=np.array([0.1, 0.2, 0.3]),
target_quat=np.array([0., 1., 1., 0.]),
with_hand=True),
dict(target_pos=np.array([0., -0.1, 0.5]),
target_quat=np.array([1., 1., 0., 0.]),
with_hand=False),
])
def test_initialize_to_fixed_pose(self, target_pos, target_quat, with_hand):
arena, arm, hand = self.make_model(with_hand=with_hand)
initializer = tcp_initializer.ToolCenterPointInitializer(
hand=hand, arm=arm, position=target_pos, quaternion=target_quat)
physics = mjcf.Physics.from_mjcf_model(arena.mjcf_model)
initializer(physics=physics, random_state=np.random.RandomState(0))
site = hand.tool_center_point if with_hand else arm.wrist_site
self.assertTargetPoseAchieved(physics.bind(site), target_pos, target_quat)
def test_exception_if_hand_colliding_with_fixed_body(self):
arena, arm, hand = self.make_model()
target_pos = np.array([0.1, 0.2, 0.3])
target_quat = np.array([0., 1., 1., 0.])
max_rejection_samples = 10
max_ik_attempts = 5
# Place a fixed obstacle at the target location so that the TCP can't reach
# the target without colliding with it.
obstacle = props.Primitive(geom_type='sphere', size=[0.3])
attachment_frame = arena.attach(obstacle)
attachment_frame.pos = target_pos
physics = mjcf.Physics.from_mjcf_model(arena.mjcf_model)
make_initializer = functools.partial(
tcp_initializer.ToolCenterPointInitializer,
hand=hand,
arm=arm,
position=target_pos,
quaternion=target_quat,
max_ik_attempts=max_ik_attempts,
max_rejection_samples=max_rejection_samples)
initializer = make_initializer()
with self.assertRaisesWithLiteralMatch(
RuntimeError,
tcp_initializer._REJECTION_SAMPLING_FAILED.format(
max_rejection_samples=max_rejection_samples,
max_ik_attempts=max_ik_attempts)):
initializer(physics=physics, random_state=np.random.RandomState(0))
# The initializer should succeed if we ignore collisions.
initializer_ignore_collisions = make_initializer(ignore_collisions=True)
initializer_ignore_collisions(physics=physics,
random_state=np.random.RandomState(0))
self.assertTargetPoseAchieved(
physics.bind(hand.tool_center_point), target_pos, target_quat)
# Confirm that the obstacle and the hand are in contact.
self.assertEntitiesInContact(physics, hand, obstacle)
@parameterized.named_parameters([
dict(testcase_name='between_arm_and_arm', with_hand=False),
dict(testcase_name='between_arm_and_hand', with_hand=True),
])
def test_exception_if_self_collision(self, with_hand):
arena, arm, hand = self.make_model(with_hand=with_hand)
# This pose places the wrist or hand partially inside the base of the arm.
target_pos = np.array([0., 0.1, 0.1])
target_quat = np.array([-1., 1., 0., 0.])
max_rejection_samples = 10
max_ik_attempts = 5
physics = mjcf.Physics.from_mjcf_model(arena.mjcf_model)
make_initializer = functools.partial(
tcp_initializer.ToolCenterPointInitializer,
hand=hand,
arm=arm,
position=target_pos,
quaternion=target_quat,
max_ik_attempts=max_ik_attempts,
max_rejection_samples=max_rejection_samples)
initializer = make_initializer()
with self.assertRaisesWithLiteralMatch(
RuntimeError,
tcp_initializer._REJECTION_SAMPLING_FAILED.format(
max_rejection_samples=max_rejection_samples,
max_ik_attempts=max_ik_attempts)):
initializer(physics=physics, random_state=np.random.RandomState(0))
# The initializer should succeed if we ignore collisions.
initializer_ignore_collisions = make_initializer(ignore_collisions=True)
initializer_ignore_collisions(physics=physics,
random_state=np.random.RandomState(0))
site = hand.tool_center_point if with_hand else arm.wrist_site
self.assertTargetPoseAchieved(
physics.bind(site), target_pos, target_quat)
# Confirm that there is self-collision.
self.assertEntitiesInContact(physics, arm, hand if with_hand else arm)
def test_ignore_robot_collision_with_free_body(self):
arena, arm, hand = self.make_model()
target_pos = np.array([0.1, 0.2, 0.3])
target_quat = np.array([0., 1., 1., 0.])
# The obstacle is still placed at the target location, but this time it has
# a freejoint and is held in place by a weld constraint.
obstacle = props.Primitive(geom_type='sphere', size=[0.3], pos=target_pos)
attachment_frame = arena.add_free_entity(obstacle)
attachment_frame.pos = target_pos
arena.mjcf_model.equality.add(
'weld', body1=attachment_frame,
relpose=np.hstack([target_pos, [1., 0., 0., 0.]]))
physics = mjcf.Physics.from_mjcf_model(arena.mjcf_model)
initializer = tcp_initializer.ToolCenterPointInitializer(
hand=hand,
arm=arm,
position=target_pos,
quaternion=target_quat)
# Check that the initializer succeeds.
initializer(physics=physics, random_state=np.random.RandomState(0))
self.assertTargetPoseAchieved(
physics.bind(hand.tool_center_point), target_pos, target_quat)
# Confirm that the obstacle and the hand are in contact.
self.assertEntitiesInContact(physics, hand, obstacle)
def test_ignore_collision_not_involving_robot(self):
arena, arm, hand = self.make_model()
target_pos = np.array([0.1, 0.2, 0.3])
target_quat = np.array([0., 1., 1., 0.])
# Add two boxes that are always in contact with each other, but never with
# the arm or hand (since they are not within reach).
side_length = 0.1
x_offset = 10.
bottom_box = props.Primitive(
geom_type='box', size=[side_length]*3, pos=[x_offset, 0, 0])
top_box = props.Primitive(
geom_type='box', size=[side_length]*3, pos=[x_offset, 0, 2*side_length])
arena.attach(bottom_box)
arena.add_free_entity(top_box)
initializer = tcp_initializer.ToolCenterPointInitializer(
hand=hand,
arm=arm,
position=target_pos,
quaternion=target_quat)
physics = mjcf.Physics.from_mjcf_model(arena.mjcf_model)
# Confirm that there are actually contacts between the two boxes.
self.assertEntitiesInContact(physics, bottom_box, top_box)
# Check that the initializer still succeeds.
initializer(physics=physics, random_state=np.random.RandomState(0))
self.assertTargetPoseAchieved(
physics.bind(hand.tool_center_point), target_pos, target_quat)
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/composer/initializers/tcp_initializer_test.py |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Utilities that are helpful for implementing initializers."""
import collections
def _get_root_model(mjcf_elements):
root_model = mjcf_elements[0].root.root_model
for element in mjcf_elements:
if element.root.root_model != root_model:
raise ValueError('entities do not all belong to the same root model')
return root_model
class JointStaticIsolator:
"""Helper class that isolates a collection of MuJoCo joints from others.
An instance of this class is a context manager that caches the positions and
velocities of all non-isolated joints *upon construction*, and resets them to
their original state when the context exits.
"""
def __init__(self, physics, joints):
"""Initializes the joint isolator.
Args:
physics: An instance of `mjcf.Physics`.
joints: An iterable of `mjcf.Element` representing joints that may be
modified inside the context managed by this isolator.
"""
if not isinstance(joints, collections.abc.Iterable):
joints = [joints]
root_model = _get_root_model(joints)
other_joints = [joint for joint in root_model.find_all('joint')
if joint not in joints]
if other_joints:
self._other_joints_mj = physics.bind(other_joints)
self._initial_qpos = self._other_joints_mj.qpos.copy()
self._initial_qvel = self._other_joints_mj.qvel.copy()
else:
self._other_joints_mj = None
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
del exc_type, exc_value, traceback # unused
if self._other_joints_mj:
self._other_joints_mj.qpos = self._initial_qpos
self._other_joints_mj.qvel = self._initial_qvel
| dm_control-main | dm_control/composer/initializers/utils.py |
# Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for index."""
import collections
from absl.testing import absltest
from absl.testing import parameterized
from dm_control.mujoco import index
from dm_control.mujoco import wrapper
from dm_control.mujoco.testing import assets
from dm_control.mujoco.wrapper.mjbindings import sizes
import mujoco
import numpy as np
MODEL = assets.get_contents('cartpole.xml')
MODEL_NO_NAMES = assets.get_contents('cartpole_no_names.xml')
MODEL_3RD_ORDER_ACTUATORS = assets.get_contents(
'model_with_third_order_actuators.xml')
FIELD_REPR = {
'act': ('FieldIndexer(act):\n'
'(empty)'),
'qM': ('FieldIndexer(qM):\n'
'0 [ 0 ]\n'
'1 [ 1 ]\n'
'2 [ 2 ]'),
'sensordata': ('FieldIndexer(sensordata):\n'
'0 accelerometer [ 0 ]\n'
'1 accelerometer [ 1 ]\n'
'2 accelerometer [ 2 ]\n'
'3 collision [ 3 ]'),
'xpos': ('FieldIndexer(xpos):\n'
' x y z \n'
'0 world [ 0 1 2 ]\n'
'1 cart [ 3 4 5 ]\n'
'2 pole [ 6 7 8 ]\n'
'3 mocap1 [ 9 10 11 ]\n'
'4 mocap2 [ 12 13 14 ]'),
}
class MujocoIndexTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self._model = wrapper.MjModel.from_xml_string(MODEL)
self._data = wrapper.MjData(self._model)
mujoco.mj_forward(self._model.ptr, self._data.ptr)
self._size_to_axis_indexer = index.make_axis_indexers(self._model)
self._model_indexers = index.struct_indexer(self._model, 'mjmodel',
self._size_to_axis_indexer)
self._data_indexers = index.struct_indexer(self._data, 'mjdata',
self._size_to_axis_indexer)
def assertIndexExpressionEqual(self, expected, actual):
try:
if isinstance(expected, tuple):
self.assertLen(actual, len(expected))
for expected_item, actual_item in zip(expected, actual):
self.assertIndexExpressionEqual(expected_item, actual_item)
elif isinstance(expected, (list, np.ndarray)):
np.testing.assert_array_equal(expected, actual)
else:
self.assertEqual(expected, actual)
except AssertionError:
self.fail('Indexing expressions are not equal.\n'
'expected: {!r}\nactual: {!r}'.format(expected, actual))
@parameterized.parameters(
# (field name, named index key, expected integer index key)
('actuator_gear', 'slide', 0),
('geom_rgba', ('mocap_sphere', 'g'), (6, 1)),
('dof_armature', 'slider', slice(0, 1, None)),
('dof_armature', ['slider', 'hinge'], [0, 1]),
('numeric_data', 'three_numbers', slice(1, 4, None)),
('numeric_data', ['three_numbers', 'control_timestep'], [1, 2, 3, 0]))
def testModelNamedIndexing(self, field_name, key, numeric_key):
indexer = getattr(self._model_indexers, field_name)
field = getattr(self._model, field_name)
converted_key = indexer._convert_key(key)
# Explicit check that the converted key matches the numeric key.
converted_key = indexer._convert_key(key)
self.assertIndexExpressionEqual(numeric_key, converted_key)
# This writes unique values to the underlying buffer to prevent false
# negatives.
field.flat[:] = np.arange(field.size)
# Check that the result of named indexing matches the result of numeric
# indexing.
np.testing.assert_array_equal(field[numeric_key], indexer[key])
@parameterized.parameters(
# (field name, named index key, expected integer index key)
('xpos', 'pole', 2),
('xpos', ['pole', 'cart'], [2, 1]),
('sensordata', 'accelerometer', slice(0, 3, None)),
('sensordata', 'collision', slice(3, 4, None)),
('sensordata', ['accelerometer', 'collision'], [0, 1, 2, 3]),
# Slices.
('xpos', (slice(None), 0), (slice(None), 0)),
# Custom fixed-size columns.
('xpos', ('pole', 'y'), (2, 1)),
('xmat', ('cart', ['yy', 'zz']), (1, [4, 8])),
# Custom indexers for mocap bodies.
('mocap_quat', 'mocap1', 0),
('mocap_pos', (['mocap2', 'mocap1'], 'z'), ([1, 0], 2)),
# Two-dimensional named indexing.
('xpos', (['pole', 'cart'], ['x', 'z']), ([2, 1], [0, 2])),
('xpos', ([['pole'], ['cart']], ['x', 'z']), ([[2], [1]], [0, 2])))
def testDataNamedIndexing(self, field_name, key, numeric_key):
indexer = getattr(self._data_indexers, field_name)
field = getattr(self._data, field_name)
# Explicit check that the converted key matches the numeric key.
converted_key = indexer._convert_key(key)
self.assertIndexExpressionEqual(numeric_key, converted_key)
# This writes unique values to the underlying buffer to prevent false
# negatives.
field.flat[:] = np.arange(field.size)
# Check that the result of named indexing matches the result of numeric
# indexing.
np.testing.assert_array_equal(field[numeric_key], indexer[key])
@parameterized.parameters(
# (field name, named index key, expected integer index key)
('act', 'cylinder', 0),
('act_dot', 'general', 1),
('act', ['general', 'cylinder', 'general'], [1, 0, 1]))
def testIndexThirdOrderActuators(self, field_name, key, numeric_key):
model = wrapper.MjModel.from_xml_string(MODEL_3RD_ORDER_ACTUATORS)
data = wrapper.MjData(model)
size_to_axis_indexer = index.make_axis_indexers(model)
data_indexers = index.struct_indexer(data, 'mjdata', size_to_axis_indexer)
indexer = getattr(data_indexers, field_name)
field = getattr(data, field_name)
# Explicit check that the converted key matches the numeric key.
converted_key = indexer._convert_key(key)
self.assertIndexExpressionEqual(numeric_key, converted_key)
# This writes unique values to the underlying buffer to prevent false
# negatives.
field.flat[:] = np.arange(field.size)
# Check that the result of named indexing matches the result of numeric
# indexing.
np.testing.assert_array_equal(field[numeric_key], indexer[key])
@parameterized.parameters(
# (field name, named index key)
('xpos', 'pole'),
('xpos', ['pole', 'cart']),
('xpos', (['pole', 'cart'], 'y')),
('xpos', (['pole', 'cart'], ['x', 'z'])),
('qpos', 'slider'),
('qvel', ['slider', 'hinge']),)
def testDataAssignment(self, field_name, key):
indexer = getattr(self._data_indexers, field_name)
field = getattr(self._data, field_name)
# The result of the indexing expression is either an array or a scalar.
index_result = indexer[key]
try:
# Write a sequence of unique values to prevent false negatives.
new_values = np.arange(index_result.size).reshape(index_result.shape)
except AttributeError:
new_values = 99
indexer[key] = new_values
# Check that the new value(s) can be read back from the underlying buffer.
converted_key = indexer._convert_key(key)
np.testing.assert_array_equal(new_values, field[converted_key])
@parameterized.parameters(
# (field name, first index key, second index key)
('sensordata', 'accelerometer', 0),
('sensordata', 'accelerometer', [0, 2]),
('sensordata', 'accelerometer', slice(None)),)
def testChainedAssignment(self, field_name, first_key, second_key):
indexer = getattr(self._data_indexers, field_name)
field = getattr(self._data, field_name)
# The result of the indexing expression is either an array or a scalar.
index_result = indexer[first_key][second_key]
try:
# Write a sequence of unique values to prevent false negatives.
new_values = np.arange(index_result.size).reshape(index_result.shape)
except AttributeError:
new_values = 99
indexer[first_key][second_key] = new_values
# Check that the new value(s) can be read back from the underlying buffer.
converted_key = indexer._convert_key(first_key)
np.testing.assert_array_equal(new_values, field[converted_key][second_key])
def testNamedColumnFieldNames(self):
all_fields = set()
for struct in sizes.array_sizes.values():
all_fields.update(struct.keys())
named_col_fields = set()
for field_set in index._COLUMN_ID_TO_FIELDS.values():
named_col_fields.update(field_set)
# Check that all of the "named column" fields specified in index are
# also found in mjbindings.sizes.
self.assertContainsSubset(named_col_fields, all_fields)
@parameterized.parameters('xpos', 'xmat') # field name
def testTooManyIndices(self, field_name):
indexer = getattr(self._data_indexers, field_name)
with self.assertRaisesRegex(IndexError, 'Index tuple'):
_ = indexer[:, :, :, 'too', 'many', 'elements']
@parameterized.parameters(
# bad item, exception regexp
(Ellipsis, 'Ellipsis'),
(None, 'None'),
(np.newaxis, 'None'),
(b'', 'Empty string'),
(u'', 'Empty string'))
def testBadIndexItems(self, bad_index_item, exception_regexp):
indexer = getattr(self._data_indexers, 'xpos')
expressions = [
bad_index_item,
(0, bad_index_item),
[bad_index_item],
[[bad_index_item]],
(0, [bad_index_item]),
(0, [[bad_index_item]]),
np.array([bad_index_item]),
(0, np.array([bad_index_item])),
(0, np.array([[bad_index_item]]))
]
for expression in expressions:
with self.assertRaisesRegex(IndexError, exception_regexp):
_ = indexer[expression]
@parameterized.parameters('act', 'qM', 'sensordata', 'xpos') # field name
def testFieldIndexerRepr(self, field_name):
indexer = getattr(self._data_indexers, field_name)
field = getattr(self._data, field_name)
# Write a sequence of unique values to prevent false negatives.
field.flat[:] = np.arange(field.size)
# Check that the string representation is as expected.
self.assertEqual(FIELD_REPR[field_name], repr(indexer))
@parameterized.parameters(MODEL, MODEL_NO_NAMES)
def testBuildIndexersForEdgeCases(self, xml_string):
model = wrapper.MjModel.from_xml_string(xml_string)
data = wrapper.MjData(model)
size_to_axis_indexer = index.make_axis_indexers(model)
index.struct_indexer(model, 'mjmodel', size_to_axis_indexer)
index.struct_indexer(data, 'mjdata', size_to_axis_indexer)
# pylint: disable=undefined-variable
@parameterized.named_parameters([
(name, name) for name in dir(np.ndarray)
if not name.startswith('_') # Exclude 'private' attributes
and name not in ('ctypes', 'flat') # Can't compare via identity/equality
])
# pylint: enable=undefined-variable
def testFieldIndexerDelegatesNDArrayAttributes(self, name):
field = self._data.xpos
field_indexer = self._data_indexers.xpos
actual = getattr(field_indexer, name)
expected = getattr(field, name)
if isinstance(expected, np.ndarray):
np.testing.assert_array_equal(actual, expected)
else:
self.assertEqual(actual, expected)
# FieldIndexer attributes should be read-only
with self.assertRaisesRegex(AttributeError, name):
setattr(field_indexer, name, expected)
def testFieldIndexerDir(self):
expected_subset = dir(self._data.xpos)
actual_set = dir(self._data_indexers.xpos)
self.assertContainsSubset(expected_subset, actual_set)
def _iter_indexers(model, data):
mujoco.mj_forward(model.ptr, data.ptr)
size_to_axis_indexer = index.make_axis_indexers(model)
all_fields = collections.OrderedDict()
for struct, struct_name in ((model, 'mjmodel'), (data, 'mjdata')):
indexer = index.struct_indexer(struct, struct_name, size_to_axis_indexer)
for field_name, field_indexer in indexer._asdict().items():
if field_name not in all_fields:
all_fields[field_name] = field_indexer
for field_name, field_indexer in all_fields.items():
yield field_name, field_indexer
class AllFieldsTest(parameterized.TestCase):
"""Generic tests covering each FieldIndexer in model and data."""
# NB: the class must hold references to the model and data instances or they
# may be garbage-collected before any indexing is attempted.
model = wrapper.MjModel.from_xml_string(MODEL)
data = wrapper.MjData(model)
# Iterates over ('field_name', FieldIndexer) pairs
@parameterized.named_parameters(_iter_indexers(model, data))
def testReadWrite_(self, field):
# Read the contents of the FieldIndexer as a numpy array.
old_contents = field[:]
# Write unique values to the FieldIndexer and read them back again.
# Don't write to non-float fields since these might contain pointers.
if np.issubdtype(old_contents.dtype, np.floating):
new_contents = np.arange(old_contents.size, dtype=old_contents.dtype)
new_contents.shape = old_contents.shape
field[:] = new_contents
np.testing.assert_array_equal(new_contents, field[:])
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/mujoco/index_test.py |
# Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests to check whether methods of `mujoco.Physics` are threadsafe."""
import platform
from absl.testing import absltest
from dm_control import _render
from dm_control.mujoco import engine
from dm_control.mujoco.testing import assets
from dm_control.mujoco.testing import decorators
MODEL = assets.get_contents('cartpole.xml')
NUM_STEPS = 10
# Context creation with GLFW is not threadsafe.
if _render.BACKEND == 'glfw':
# On Linux we are able to create a GLFW window in a single thread that is not
# the main thread.
# On Mac we are only allowed to create windows on the main thread, so we
# disable the `run_threaded` wrapper entirely.
NUM_THREADS = None if platform.system() == 'Darwin' else 1
else:
NUM_THREADS = 4
class ThreadSafetyTest(absltest.TestCase):
@decorators.run_threaded(num_threads=NUM_THREADS)
def test_load_physics_from_string(self):
engine.Physics.from_xml_string(MODEL)
@decorators.run_threaded(num_threads=NUM_THREADS)
def test_load_and_reload_physics_from_string(self):
physics = engine.Physics.from_xml_string(MODEL)
physics.reload_from_xml_string(MODEL)
@decorators.run_threaded(num_threads=NUM_THREADS)
def test_load_and_step_physics(self):
physics = engine.Physics.from_xml_string(MODEL)
for _ in range(NUM_STEPS):
physics.step()
@decorators.run_threaded(num_threads=NUM_THREADS)
def test_load_and_step_multiple_physics_parallel(self):
physics1 = engine.Physics.from_xml_string(MODEL)
physics2 = engine.Physics.from_xml_string(MODEL)
for _ in range(NUM_STEPS):
physics1.step()
physics2.step()
@decorators.run_threaded(num_threads=NUM_THREADS)
def test_load_and_step_multiple_physics_sequential(self):
physics1 = engine.Physics.from_xml_string(MODEL)
for _ in range(NUM_STEPS):
physics1.step()
del physics1
physics2 = engine.Physics.from_xml_string(MODEL)
for _ in range(NUM_STEPS):
physics2.step()
@decorators.run_threaded(num_threads=NUM_THREADS, calls_per_thread=5)
def test_load_physics_and_render(self):
physics = engine.Physics.from_xml_string(MODEL)
# Check that frames aren't repeated - make the cartpole move.
physics.set_control([1.0])
unique_frames = set()
for _ in range(NUM_STEPS):
physics.step()
frame = physics.render(width=320, height=240, camera_id=0)
unique_frames.add(frame.tobytes())
self.assertLen(unique_frames, NUM_STEPS)
@decorators.run_threaded(num_threads=NUM_THREADS, calls_per_thread=5)
def test_render_multiple_physics_instances_per_thread_parallel(self):
physics1 = engine.Physics.from_xml_string(MODEL)
physics2 = engine.Physics.from_xml_string(MODEL)
for _ in range(NUM_STEPS):
physics1.step()
physics1.render(width=320, height=240, camera_id=0)
physics2.step()
physics2.render(width=320, height=240, camera_id=0)
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/mujoco/thread_safety_test.py |
# Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Mujoco functions to support named indexing.
The Mujoco name structure works as follows:
In mjxmacro.h, each "X" entry denotes a type (a), a field name (b) and a list
of dimension size metadata (c) which may contain both numbers and names, for
example
X(int, name_bodyadr, nbody, 1) // or
X(mjtNum, body_pos, nbody, 3)
a b c ----->
The second declaration states that the field `body_pos` has type `mjtNum` and
dimension sizes `(nbody, 3)`, i.e. the first axis is indexed by body number.
These and other named dimensions are sized based on the loaded model. This
information is parsed and stored in `mjbindings.sizes`.
In mjmodel.h, the struct mjModel contains an array of element name addresses
for each size name.
int* name_bodyadr; // body name pointers (nbody x 1)
By iterating over each of these element name address arrays, we first obtain a
mapping from size names to a list of element names.
{'nbody': ['cart', 'pole'], 'njnt': ['free', 'ball', 'hinge'], ...}
In addition to the element names that are derived from the mjModel struct at
runtime, we also assign hard-coded names to certain dimensions where there is an
established naming convention (e.g. 'x', 'y', 'z' for dimensions that correspond
to Cartesian positions).
For some dimensions, a single element name maps to multiple indices within the
underlying field. For example, a single joint name corresponds to a variable
number of indices within `qpos` that depends on the number of degrees of freedom
associated with that joint type. These are referred to as "ragged" dimensions.
In such cases we determine the size of each named element by examining the
address arrays (e.g. `jnt_qposadr`), and construct a mapping from size name to
element sizes:
{'nq': [7, 3, 1], 'nv': [6, 3, 1], ...}
Given these two dictionaries, we then create an `Axis` instance for each size
name. These objects have a `convert_key_item` method that handles the conversion
from indexing expressions containing element names to valid numpy indices.
Different implementations of `Axis` are used to handle "ragged" and "non-ragged"
dimensions.
{'nbody': RegularNamedAxis(names=['cart', 'pole']),
'nq': RaggedNamedAxis(names=['free', 'ball', 'hinge'], sizes=[7, 4, 1])}
We construct this dictionary once using `make_axis_indexers`.
Finally, for each field we construct a `FieldIndexer` class. A `FieldIndexer`
instance encapsulates a field together with a list of `Axis` instances (one per
dimension), and implements the named indexing logic by calling their respective
`convert_key_item` methods.
Summary of terminology:
* _size name_ or _size_ A dimension size name, e.g. `nbody` or `ngeom`.
* _element name_ or _name_ A named element in a Mujoco model, e.g. 'cart' or
'pole'.
* _element index_ or _index_ The index of an element name, for a specific size
name.
"""
import abc
import collections
import weakref
from dm_control.mujoco.wrapper import util
from dm_control.mujoco.wrapper.mjbindings import sizes
import numpy as np
# Mapping from {size_name: address_field_name} for ragged dimensions.
_RAGGED_ADDRS = {
'nq': 'jnt_qposadr',
'nv': 'jnt_dofadr',
'na': 'actuator_actadr',
'nsensordata': 'sensor_adr',
'nnumericdata': 'numeric_adr',
}
# Names of columns.
_COLUMN_NAMES = {
'xyz': ['x', 'y', 'z'],
'quat': ['qw', 'qx', 'qy', 'qz'],
'mat': ['xx', 'xy', 'xz',
'yx', 'yy', 'yz',
'zx', 'zy', 'zz'],
'rgba': ['r', 'g', 'b', 'a'],
}
# Mapping from keys of _COLUMN_NAMES to sets of field names whose columns are
# addressable using those names.
_COLUMN_ID_TO_FIELDS = {
'xyz': set([
'body_pos',
'body_ipos',
'body_inertia',
'jnt_pos',
'jnt_axis',
'geom_size',
'geom_pos',
'site_size',
'site_pos',
'cam_pos',
'cam_poscom0',
'cam_pos0',
'light_pos',
'light_dir',
'light_poscom0',
'light_pos0',
'light_dir0',
'mesh_vert',
'mesh_normal',
'mocap_pos',
'xpos',
'xipos',
'xanchor',
'xaxis',
'geom_xpos',
'site_xpos',
'cam_xpos',
'light_xpos',
'light_xdir',
'subtree_com',
'wrap_xpos',
'subtree_linvel',
'subtree_angmom',
]),
'quat': set([
'body_quat',
'body_iquat',
'geom_quat',
'site_quat',
'cam_quat',
'mocap_quat',
'xquat',
]),
'mat': set([
'cam_mat0',
'xmat',
'ximat',
'geom_xmat',
'site_xmat',
'cam_xmat',
]),
'rgba': set([
'geom_rgba',
'site_rgba',
'skin_rgba',
'mat_rgba',
'tendon_rgba',
])
}
def _get_size_name_to_element_names(model):
"""Returns a dict that maps size names to element names.
Args:
model: An instance of `mjbindings.mjModelWrapper`.
Returns:
A `dict` mapping from a size name (e.g. `'nbody'`) to a list of element
names.
"""
names = model.names
size_name_to_element_names = {}
for field_name in dir(model.ptr):
if not _is_name_pointer(field_name):
continue
# Get addresses of element names in `model.names` array, e.g.
# field name: `name_nbodyadr` and name_addresses: `[86, 92, 101]`, and skip
# when there are no elements for this type in the model.
name_addresses = getattr(model, field_name).ravel()
if not name_addresses.size:
continue
# Get the element names.
element_names = []
for start_index in name_addresses:
end_index = names.find(b'\0', start_index)
name = names[start_index:end_index]
element_names.append(str(name, 'utf-8'))
# String identifier for the size of the first dimension, e.g. 'nbody'.
size_name = _get_size_name(field_name)
size_name_to_element_names[size_name] = element_names
# Add custom element names for certain columns.
for size_name, element_names in _COLUMN_NAMES.items():
size_name_to_element_names[size_name] = element_names
# "Ragged" axes inherit their element names from other "non-ragged" axes.
# For example, the element names for "nv" axis come from "njnt".
for size_name, address_field_name in _RAGGED_ADDRS.items():
donor = 'n' + address_field_name.split('_')[0]
if donor == 'nactuator':
donor = 'nu'
if donor in size_name_to_element_names:
size_name_to_element_names[size_name] = size_name_to_element_names[donor]
# Mocap bodies are a special subset of bodies.
mocap_body_names = [None] * model.nmocap
for body_id, body_name in enumerate(size_name_to_element_names['nbody']):
body_mocapid = model.body_mocapid[body_id]
if body_mocapid != -1:
mocap_body_names[body_mocapid] = body_name
assert None not in mocap_body_names
size_name_to_element_names['nmocap'] = mocap_body_names
return size_name_to_element_names
def _get_size_name_to_element_sizes(model):
"""Returns a dict that maps size names to element sizes for ragged axes.
Args:
model: An instance of `mjbindings.mjModelWrapper`.
Returns:
A `dict` mapping from a size name (e.g. `'nv'`) to a numpy array of element
sizes. Size names corresponding to non-ragged axes are omitted.
"""
size_name_to_element_sizes = {}
for size_name, address_field_name in _RAGGED_ADDRS.items():
addresses = getattr(model, address_field_name).ravel()
if size_name == 'na':
element_sizes = np.where(addresses == -1, 0, 1)
else:
total_length = getattr(model, size_name)
element_sizes = np.diff(np.r_[addresses, total_length])
size_name_to_element_sizes[size_name] = element_sizes
return size_name_to_element_sizes
def make_axis_indexers(model):
"""Returns a dict that maps size names to `Axis` indexers.
Args:
model: An instance of `mjbindings.MjModelWrapper`.
Returns:
A `dict` mapping from a size name (e.g. `'nbody'`) to an `Axis` instance.
"""
size_name_to_element_names = _get_size_name_to_element_names(model)
size_name_to_element_sizes = _get_size_name_to_element_sizes(model)
# Unrecognized size names are treated as unnamed axes.
axis_indexers = collections.defaultdict(UnnamedAxis)
for size_name in size_name_to_element_names:
element_names = size_name_to_element_names[size_name]
if size_name in _RAGGED_ADDRS:
element_sizes = size_name_to_element_sizes[size_name]
singleton = (size_name == 'na')
indexer = RaggedNamedAxis(element_names, element_sizes,
singleton=singleton)
else:
indexer = RegularNamedAxis(element_names)
axis_indexers[size_name] = indexer
return axis_indexers
def _is_name_pointer(field_name):
"""Returns True for name pointer field names such as `name_bodyadr`."""
# Denotes name pointer fields in mjModel.
prefix, suffix = 'name_', 'adr'
return field_name.startswith(prefix) and field_name.endswith(suffix)
def _get_size_name(field_name, struct_name='mjmodel'):
# Look up size name in metadata.
return sizes.array_sizes[struct_name][field_name][0]
def _validate_key_item(key_item):
if isinstance(key_item, (list, np.ndarray)):
for sub in key_item:
_validate_key_item(sub) # Recurse into nested arrays and lists.
elif key_item is Ellipsis:
raise IndexError('Ellipsis indexing not supported.')
elif key_item is None:
raise IndexError('None indexing not supported.')
elif key_item in (b'', u''):
raise IndexError('Empty strings are not allowed.')
class Axis(metaclass=abc.ABCMeta):
"""Handles the conversion of named indexing expressions into numpy indices."""
@abc.abstractmethod
def convert_key_item(self, key_item):
"""Converts a (possibly named) indexing expression to a numpy index."""
class UnnamedAxis(Axis):
"""An object representing an axis where the elements are not named."""
def convert_key_item(self, key_item):
"""Validate the indexing expression and return it unmodified."""
_validate_key_item(key_item)
return key_item
class RegularNamedAxis(Axis):
"""Represents an axis where each named element has a fixed size of 1."""
def __init__(self, names):
"""Initializes a new `RegularNamedAxis` instance.
Args:
names: A list or array of element names.
"""
self._names = names
self._names_to_offsets = {name: offset
for offset, name in enumerate(names) if name}
def convert_key_item(self, key_item):
"""Converts a named indexing expression to a numpy-friendly index."""
_validate_key_item(key_item)
if isinstance(key_item, str):
key_item = self._names_to_offsets[util.to_native_string(key_item)]
elif isinstance(key_item, (list, np.ndarray)):
# Cast lists to numpy arrays.
key_item = np.array(key_item, copy=False)
original_shape = key_item.shape
# We assume that either all or none of the items in the array are strings
# representing names. If there is a mix, we will let NumPy throw an error
# when trying to index with the returned item.
if isinstance(key_item.flat[0], str):
key_item = np.array([self._names_to_offsets[util.to_native_string(k)]
for k in key_item.flat])
# Ensure the output shape is the same as that of the input.
key_item.shape = original_shape
return key_item
@property
def names(self):
"""Returns a list of element names."""
return self._names
class RaggedNamedAxis(Axis):
"""Represents an axis where the named elements may vary in size."""
def __init__(self, element_names, element_sizes, singleton=False):
"""Initializes a new `RaggedNamedAxis` instance.
Args:
element_names: A list or array containing the element names.
element_sizes: A list or array containing the size of each element.
singleton: Whether to reduce singleton slices to scalars.
"""
names_to_slices = {}
names_to_indices = {}
offset = 0
for name, size in zip(element_names, element_sizes):
# Don't add unnamed elements to the dicts.
if name:
if size == 1 and singleton:
names_to_slices[name] = offset
else:
names_to_slices[name] = slice(offset, offset + size)
names_to_indices[name] = range(offset, offset + size)
offset += size
self._names = element_names
self._sizes = element_sizes
self._names_to_slices = names_to_slices
self._names_to_indices = names_to_indices
def convert_key_item(self, key_item):
"""Converts a named indexing expression to a numpy-friendly index."""
_validate_key_item(key_item)
if isinstance(key_item, str):
key_item = self._names_to_slices[util.to_native_string(key_item)]
elif isinstance(key_item, (list, np.ndarray)):
# We assume that either all or none of the items in the sequence are
# strings representing names. If there is a mix, we will let NumPy throw
# an error when trying to index with the returned key.
if isinstance(key_item[0], str):
new_key = []
for k in key_item:
idx = self._names_to_indices[util.to_native_string(k)]
if isinstance(idx, int):
new_key.append(idx)
else:
new_key.extend(idx)
key_item = new_key
return key_item
@property
def names(self):
"""Returns a list of element names."""
return self._names
Axes = collections.namedtuple('Axes', ['row', 'col'])
Axes.__new__.__defaults__ = (None,) # Default value for optional 'col' field
class FieldIndexer:
"""An array-like object providing named access to a field in a MuJoCo struct.
FieldIndexers expose the same attributes and methods as an `np.ndarray`.
They may be indexed with strings or lists of strings corresponding to element
names. They also support standard numpy indexing expressions, with the
exception of indices containing `Ellipsis` or `None`.
"""
__slots__ = ('_field_name', '_field', '_axes')
def __init__(self,
parent_struct,
field_name,
axis_indexers):
"""Initializes a new `FieldIndexer`.
Args:
parent_struct: Wrapped ctypes structure, as generated by `mjbindings`.
field_name: String containing field name in `parent_struct`.
axis_indexers: A list of `Axis` instances, one per dimension.
"""
self._field_name = field_name
self._field = weakref.proxy(getattr(parent_struct, field_name))
self._axes = Axes(*axis_indexers)
def __dir__(self):
# Enables IPython tab completion
return sorted(set(dir(type(self)) + dir(self._field)))
def __getattr__(self, name):
return getattr(self._field, name)
def _convert_key(self, key):
"""Convert a (possibly named) indexing expression to a valid numpy index."""
return_tuple = isinstance(key, tuple)
if not return_tuple:
key = (key,)
if len(key) > self._field.ndim:
raise IndexError('Index tuple has {} elements, but array has only {} '
'dimensions.'.format(len(key), self._field.ndim))
new_key = tuple(axis.convert_key_item(key_item)
for axis, key_item in zip(self._axes, key))
if not return_tuple:
new_key = new_key[0]
return new_key
def __getitem__(self, key):
"""Converts the key to a numeric index and returns the indexed array.
Args:
key: Indexing expression.
Raises:
IndexError: If an indexing tuple has too many elements, or if it contains
`Ellipsis`, `None`, or an empty string.
Returns:
The indexed array.
"""
return self._field[self._convert_key(key)]
def __setitem__(self, key, value):
"""Converts the key and assigns to the indexed array.
Args:
key: Indexing expression.
value: Value to assign.
Raises:
IndexError: If an indexing tuple has too many elements, or if it contains
`Ellipsis`, `None`, or an empty string.
"""
self._field[self._convert_key(key)] = value
@property
def axes(self):
"""A namedtuple containing the row and column indexers for this field."""
return self._axes
def __repr__(self):
"""Returns a pretty string representation of the `FieldIndexer`."""
def get_name_arr_and_len(dim_idx):
"""Returns a string array of element names and the max name length."""
axis = self._axes[dim_idx]
size = self._field.shape[dim_idx]
try:
name_len = max(len(name) for name in axis.names)
name_arr = np.zeros(size, dtype='S{}'.format(name_len))
for name in axis.names:
if name:
# Use the `Axis` object to convert the name into a numpy index, then
# use this index to write into name_arr.
name_arr[axis.convert_key_item(name)] = name
except AttributeError:
name_arr = np.zeros(size, dtype='S0') # An array of zero-length strings
name_len = 0
return name_arr, name_len
row_name_arr, row_name_len = get_name_arr_and_len(0)
if self._field.ndim > 1:
col_name_arr, col_name_len = get_name_arr_and_len(1)
else:
col_name_arr, col_name_len = np.zeros(1, dtype='S0'), 0
idx_len = int(np.log10(max(self._field.shape[0], 1))) + 1
cls_template = '{class_name:}({field_name:}):'
col_template = '{padding:}{col_names:}'
row_template = '{idx:{idx_len:}} {row_name:>{row_name_len:}} {row_vals:}'
lines = []
# Write the class name and field name.
lines.append(cls_template.format(class_name=self.__class__.__name__,
field_name=self._field_name))
# Write a header line containing the column names (if there are any).
if col_name_len:
col_width = max(col_name_len, 9) + 1
extra_indent = 4
padding = ' ' * (idx_len + row_name_len + extra_indent)
col_names = ''.join(
'{name:<{width:}}'
.format(name=util.to_native_string(name), width=col_width)
for name in col_name_arr)
lines.append(col_template.format(padding=padding, col_names=col_names))
# Write the row names (if there are any) and the formatted array values.
if not self._field.shape[0]:
lines.append('(empty)')
else:
for idx, row in enumerate(self._field):
row_vals = np.array2string(
np.atleast_1d(row),
suppress_small=True,
formatter={'float_kind': '{: < 9.3g}'.format})
lines.append(row_template.format(
idx=idx,
idx_len=idx_len,
row_name=util.to_native_string(row_name_arr[idx]),
row_name_len=row_name_len,
row_vals=row_vals))
return '\n'.join(lines)
def struct_indexer(struct, struct_name, size_to_axis_indexer):
"""Returns an object with a `FieldIndexer` attribute for each dynamic field.
Usage example
```python
named_data = struct_indexer(mjdata, 'mjdata', size_to_axis_indexer)
fingertip_xpos = named_data.xpos['fingertip']
elbow_qvel = named_data.qvel['elbow']
```
Args:
struct: Wrapped ctypes structure as generated by `mjbindings`.
struct_name: String containing corresponding Mujoco name of struct.
size_to_axis_indexer: dict that maps size names to `Axis` instances.
Returns:
An object with a field for every dynamically sized array field, mapping to a
`FieldIndexer`. The returned object is immutable and has an `_asdict`
method.
Raises:
ValueError: If `struct_name` is not recognized.
"""
struct_name = struct_name.lower()
if struct_name not in sizes.array_sizes:
raise ValueError('Unrecognized struct name ' + struct_name)
array_sizes = sizes.array_sizes[struct_name]
# Used to create the namedtuple.
field_names = []
field_indexers = {}
for field_name in array_sizes:
# Skip over structured arrays and fields that have sizes but aren't numpy
# arrays, such as text fields and contacts (b/34805932).
attr = getattr(struct, field_name)
if not isinstance(attr, np.ndarray) or attr.dtype.fields:
continue
size_names = sizes.array_sizes[struct_name][field_name]
# Here we override the size name in order to enable named column indexing
# for certain fields, e.g. 3 becomes "xyz" for field name "xpos".
for new_col_size, field_set in _COLUMN_ID_TO_FIELDS.items():
if field_name in field_set:
size_names = (size_names[0], new_col_size)
break
axis_indexers = []
for size_name in size_names:
axis_indexers.append(size_to_axis_indexer[size_name])
field_indexers[field_name] = FieldIndexer(
parent_struct=struct,
field_name=field_name,
axis_indexers=axis_indexers)
field_names.append(field_name)
return make_struct_indexer(field_indexers)
def make_struct_indexer(field_indexers):
"""Returns an immutable container exposing named indexers as attributes."""
class StructIndexer:
__slots__ = ()
def _asdict(self):
return field_indexers.copy()
for name, indexer in field_indexers.items():
setattr(StructIndexer, name, indexer)
return StructIndexer()
| dm_control-main | dm_control/mujoco/index.py |
# Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for `engine`."""
import copy
import pickle
from absl.testing import absltest
from absl.testing import parameterized
from dm_control.mujoco import engine
from dm_control.mujoco import wrapper
from dm_control.mujoco.testing import assets
from dm_control.mujoco.wrapper.mjbindings import enums
from dm_control.rl import control
import mock
import mujoco
import numpy as np
MODEL_PATH = assets.get_path('cartpole.xml')
MODEL_WITH_ASSETS = assets.get_contents('model_with_assets.xml')
ASSETS = {
'texture.png': assets.get_contents('deepmind.png'),
'mesh.stl': assets.get_contents('cube.stl'),
'included.xml': assets.get_contents('sphere.xml')
}
class MujocoEngineTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self._physics = engine.Physics.from_xml_path(MODEL_PATH)
def _assert_attributes_equal(self, actual_obj, expected_obj, attr_to_compare):
for name in attr_to_compare:
actual_value = getattr(actual_obj, name)
expected_value = getattr(expected_obj, name)
try:
if isinstance(expected_value, np.ndarray):
np.testing.assert_array_equal(actual_value, expected_value)
else:
self.assertEqual(actual_value, expected_value)
except AssertionError as e:
raise AssertionError(
f"Attribute '{name}' differs from expected value.") from e
@parameterized.parameters(0, 'cart', u'cart')
def testCameraIndexing(self, camera_id):
height, width = 480, 640
_ = engine.Camera(
self._physics, height, width, camera_id=camera_id)
def testDepthRender(self):
plane_and_box = """
<mujoco>
<worldbody>
<geom type="plane" pos="0 0 0" size="2 2 .1"/>
<geom type="box" size=".1 .1 .1" pos="0 0 .1"/>
<camera name="top" pos="0 0 3"/>
</worldbody>
</mujoco>
"""
physics = engine.Physics.from_xml_string(plane_and_box)
pixels = physics.render(height=200, width=200, camera_id='top', depth=True)
# Nearest pixels should be 2.8m away
np.testing.assert_approx_equal(pixels.min(), 2.8, 3)
# Furthest pixels should be 3m away (depth is orthographic)
np.testing.assert_approx_equal(pixels.max(), 3.0, 3)
@parameterized.parameters([True, False])
def testSegmentationRender(self, enable_geom_frame_rendering):
box_four_corners = """
<mujoco>
<visual>
<scale framelength="2"/>
</visual>
<worldbody>
<geom name="box0" type="box" size=".2 .2 .2" pos="-1 1 .1"/>
<geom name="box1" type="box" size=".2 .2 .2" pos="1 1 .1"/>
<site name="box2" type="box" size=".2 .2 .2" pos="1 -1 .1"/>
<site name="box3" type="box" size=".2 .2 .2" pos="-1 -1 .1"/>
<camera name="top" pos="0 0 3"/>
</worldbody>
</mujoco>
"""
physics = engine.Physics.from_xml_string(box_four_corners)
obj_type_geom = enums.mjtObj.mjOBJ_GEOM # Geom object type
obj_type_site = enums.mjtObj.mjOBJ_SITE # Site object type
obj_type_decor = enums.mjtObj.mjOBJ_UNKNOWN # Decor object type
scene_options = wrapper.MjvOption()
if enable_geom_frame_rendering:
scene_options.frame = mujoco.mjtFrame.mjFRAME_GEOM
pixels = physics.render(height=200, width=200, camera_id='top',
segmentation=True, scene_option=scene_options)
# The pixel indices below were chosen so that toggling the frame decors do
# not affect the segmentation results.
with self.subTest('Center pixels should have background label'):
np.testing.assert_equal(pixels[95:105, 95:105, 0], -1)
np.testing.assert_equal(pixels[95:105, 95:105, 1], -1)
with self.subTest('Geoms have correct object type'):
np.testing.assert_equal(pixels[15:25, 0:10, 1], obj_type_geom)
np.testing.assert_equal(pixels[15:25, 190:200, 1], obj_type_geom)
with self.subTest('Sites have correct object type'):
np.testing.assert_equal(pixels[190:200, 190:200, 1], obj_type_site)
np.testing.assert_equal(pixels[190:200, 0:10, 1], obj_type_site)
with self.subTest('Geoms have correct object IDs'):
np.testing.assert_equal(pixels[15:25, 0:10, 0],
physics.model.name2id('box0', obj_type_geom))
np.testing.assert_equal(pixels[15:25, 190:200, 0],
physics.model.name2id('box1', obj_type_geom))
with self.subTest('Sites have correct object IDs'):
np.testing.assert_equal(pixels[190:200, 190:200, 0],
physics.model.name2id('box2', obj_type_site))
np.testing.assert_equal(pixels[190:200, 0:10, 0],
physics.model.name2id('box3', obj_type_site))
with self.subTest('Decor elements present if and only if geom frames are '
'enabled'):
contains_decor = np.any(pixels[:, :, 1] == obj_type_decor)
self.assertEqual(contains_decor, enable_geom_frame_rendering)
def testSceneCallback(self):
empty_world = """
<mujoco>
<worldbody>
<camera name="cam" pos="0 0 3"/>
</worldbody>
</mujoco>
"""
def callback(_, scn: mujoco.MjvScene):
# Add a red box to the scene
scn.ngeom += 1
mujoco.mjv_initGeom(
scn.geoms[scn.ngeom - 1],
mujoco.mjtGeom.mjGEOM_BOX.value,
size=np.array([0.2, 0.2, 0.2]),
pos=np.zeros(3),
mat=np.eye(3).flatten(),
rgba=np.array([1, 0, 0, 1], dtype=np.float32))
physics = engine.Physics.from_xml_string(empty_world)
# Without the callback, render should return a black image.
empty_image = physics.render(
height=8, width=8, camera_id='cam', scene_callback=None)
np.testing.assert_array_equal(
np.zeros((8, 8, 3), dtype=np.uint8), empty_image)
# With the callback, there should be a red box.
pixels = physics.render(
height=8, width=8, camera_id='cam', scene_callback=callback)
# Are there any pixels where red component is bigger than green and blue?
any_red_pixels = np.any(pixels[:, :, 0] > np.max(pixels[:, :, 1:3], axis=2))
self.assertTrue(any_red_pixels, 'Expecting some red pixels.')
def testTextOverlay(self):
height, width = 480, 640
overlay = engine.TextOverlay(title='Title', body='Body', style='big',
position='bottom right')
no_overlay = self._physics.render(height, width, camera_id=0)
with_overlay = self._physics.render(height, width, camera_id=0,
overlays=[overlay])
self.assertFalse(np.all(no_overlay == with_overlay),
msg='Images are identical with and without text overlay.')
def testSceneOption(self):
height, width = 480, 640
scene_option = wrapper.MjvOption()
# Render geoms as semi-transparent.
scene_option.flags[enums.mjtVisFlag.mjVIS_TRANSPARENT] = 1
no_scene_option = self._physics.render(height, width, camera_id=0)
with_scene_option = self._physics.render(height, width, camera_id=0,
scene_option=scene_option)
self.assertFalse(np.all(no_scene_option == with_scene_option),
msg='Images are identical with and without scene option.')
def testRenderFlags(self):
height, width = 480, 640
cam = engine.Camera(self._physics, height, width, camera_id=0)
cam.scene.flags[enums.mjtRndFlag.mjRND_WIREFRAME] = 1 # Enable wireframe
enabled = cam.render().copy()
cam.scene.flags[enums.mjtRndFlag.mjRND_WIREFRAME] = 0 # Disable wireframe
disabled = cam.render().copy()
self.assertFalse(
np.all(disabled == enabled),
msg='Images are identical regardless of whether wireframe is enabled.')
@parameterized.parameters(((0.5, 0.5), (1, 3)), # pole
((0.5, 0.1), (0, 0)), # ground
((0.9, 0.9), (None, None)), # sky
)
def testCameraSelection(self, coordinates, expected_selection):
height, width = 480, 640
camera = engine.Camera(self._physics, height, width, camera_id=0)
# Test for b/63380170: Enabling visualization of body frames adds
# "non-model" geoms to the scene. This means that the indices of geoms
# within `camera._scene.geoms` don't match the rows of `model.geom_bodyid`.
camera.option.frame = enums.mjtFrame.mjFRAME_BODY
selected = camera.select(coordinates)
self.assertEqual(expected_selection, selected[:2])
@parameterized.parameters(
dict(camera_id='cam0', height=200, width=300),
dict(camera_id=1, height=300, width=200),
dict(camera_id=-1, height=400, width=400),
)
def testCameraMatrix(self, camera_id, height, width):
"""Tests the camera_matrix() method.
Creates a model with two cameras and two small geoms. We render the scene
with one of the cameras and check that the geom locations, projected into
pixel space, are correct, using segmenation rendering.
xyz2pixels() shows how the transformation is used. For a description
of the camera matrix see https://en.wikipedia.org/wiki/Camera_matrix.
Args:
camera_id: One of the two cameras. Can be either integer or String.
height: The height of the image (pixels).
width: The width of the image (pixels).
"""
def xyz2pixels(x, y, z, camera_matrix):
"""Transforms from world coordinates to pixel coordinates."""
xs, ys, s = camera_matrix.dot(np.array([x, y, z, 1.0]))
return xs/s, ys/s
two_geoms_and_two_cameras = """
<mujoco>
<visual>
<global fovy="55"/>
</visual>
<worldbody>
<light name="top" pos="0 0 1"/>
<geom name="red" pos=".2 0 0" size=".005" rgba="1 0 0 1"/>
<geom name="green" pos=".2 .2 .1" size=".005" rgba="0 1 0 1"/>
<camera name="cam0" pos="1 .5 1" zaxis="1 .5 1" fovy="20"/>
<camera name="cam1" pos=".1 .1 1" xyaxes="1 1 0 -1 0 0"/>
</worldbody>
</mujoco>
"""
physics = engine.Physics.from_xml_string(two_geoms_and_two_cameras)
camera = engine.Camera(physics, width=width, height=height,
camera_id=camera_id)
camera_matrix = camera.matrix # Get camera matrix.
pixels = camera.render(segmentation=True) # Render a segmentation frame.
for geom_id in [0, 1]:
# Compute the location of the geom in pixel space using the camera matrix.
x, y = xyz2pixels(*physics.data.geom_xpos[geom_id], camera_matrix)
row = int(round(y))
column = int(round(x))
# Compare segmentation values of nearest pixel to corresponding geom.
[obj_id, obj_type] = pixels[row, column, :]
self.assertEqual(obj_type, enums.mjtObj.mjOBJ_GEOM)
self.assertEqual(obj_id, geom_id)
def testMovableCameraSetGetPose(self):
height, width = 240, 320
camera = engine.MovableCamera(self._physics, height, width)
image = camera.render().copy()
pose = camera.get_pose()
lookat_offset = np.array([0.01, 0.02, -0.03])
# Would normally pass the new values directly to camera.set_pose instead of
# using the namedtuple _replace method, but this makes the asserts at the
# end of the test a little cleaner.
new_pose = pose._replace(distance=pose.distance * 1.5,
lookat=pose.lookat + lookat_offset,
azimuth=pose.azimuth + -15,
elevation=pose.elevation - 10)
camera.set_pose(*new_pose)
self.assertEqual(new_pose.distance, camera.get_pose().distance)
self.assertEqual(new_pose.azimuth, camera.get_pose().azimuth)
self.assertEqual(new_pose.elevation, camera.get_pose().elevation)
np.testing.assert_allclose(new_pose.lookat, camera.get_pose().lookat)
self.assertFalse(np.all(image == camera.render()))
def testRenderExceptions(self):
max_width = self._physics.model.vis.global_.offwidth
max_height = self._physics.model.vis.global_.offheight
max_camid = self._physics.model.ncam - 1
with self.assertRaisesRegex(ValueError, 'width'):
self._physics.render(max_height, max_width + 1, camera_id=max_camid)
with self.assertRaisesRegex(ValueError, 'height'):
self._physics.render(max_height + 1, max_width, camera_id=max_camid)
with self.assertRaisesRegex(ValueError, 'camera_id'):
self._physics.render(max_height, max_width, camera_id=max_camid + 1)
with self.assertRaisesRegex(ValueError, 'camera_id'):
self._physics.render(max_height, max_width, camera_id=-2)
def testPhysicsRenderMethod(self):
height, width = 240, 320
image = self._physics.render(height=height, width=width)
self.assertEqual(image.shape, (height, width, 3))
depth = self._physics.render(height=height, width=width, depth=True)
self.assertEqual(depth.shape, (height, width))
segmentation = self._physics.render(height=height, width=width,
segmentation=True)
self.assertEqual(segmentation.shape, (height, width, 2))
def testExceptionIfBothDepthAndSegmentation(self):
with self.assertRaisesWithLiteralMatch(
ValueError, engine._BOTH_SEGMENTATION_AND_DEPTH_ENABLED):
self._physics.render(depth=True, segmentation=True)
def testRenderFlagOverridesAreNotPersistent(self):
camera = engine.Camera(self._physics)
first_rgb = camera.render().copy()
camera.render(segmentation=True)
second_rgb = camera.render().copy()
np.testing.assert_array_equal(first_rgb, second_rgb)
def testCustomRenderFlags(self):
default = self._physics.render()
wireframe_string_key = self._physics.render(
render_flag_overrides=dict(wireframe=True))
self.assertFalse((default == wireframe_string_key).all())
wireframe_enum_key = self._physics.render(
render_flag_overrides={enums.mjtRndFlag.mjRND_WIREFRAME: True})
np.testing.assert_array_equal(wireframe_string_key, wireframe_enum_key)
@parameterized.parameters(dict(depth=True), dict(segmentation=True))
def testExceptionIfRenderFlagOverridesAndDepthOrSegmentation(self, **kwargs):
with self.assertRaisesWithLiteralMatch(
ValueError,
engine._RENDER_FLAG_OVERRIDES_NOT_SUPPORTED_FOR_DEPTH_OR_SEGMENTATION):
self._physics.render(render_flag_overrides=dict(wireframe=True), **kwargs)
def testExceptionIfOverlaysAndDepthOrSegmentation(self):
overlay = engine.TextOverlay()
with self.assertRaisesWithLiteralMatch(
ValueError, engine._OVERLAYS_NOT_SUPPORTED_FOR_DEPTH_OR_SEGMENTATION):
self._physics.render(depth=True, overlays=[overlay])
with self.assertRaisesWithLiteralMatch(
ValueError, engine._OVERLAYS_NOT_SUPPORTED_FOR_DEPTH_OR_SEGMENTATION):
self._physics.render(segmentation=True, overlays=[overlay])
def testNamedViews(self):
self.assertEqual((1,), self._physics.control().shape)
self.assertEqual((2,), self._physics.position().shape)
self.assertEqual((2,), self._physics.velocity().shape)
self.assertEqual((0,), self._physics.activation().shape)
self.assertEqual((4,), self._physics.state().shape)
self.assertEqual(0., self._physics.time())
self.assertEqual(0.01, self._physics.timestep())
def testSetGetPhysicsState(self):
physics_state = self._physics.get_state()
# qpos, qvel, act
self.assertLen(self._physics._physics_state_items(), 3)
self._physics.set_state(physics_state)
new_physics_state = np.random.random_sample(physics_state.shape)
self._physics.set_state(new_physics_state)
np.testing.assert_allclose(new_physics_state,
self._physics.get_state())
def testSetGetPhysicsStateWithPlugin(self):
# Model copied from mujoco/test/plugin/elasticity/elasticity_test.cc
model_with_cable_plugin = """
<mujoco>
<option gravity="0 0 0"/>
<extension>
<plugin plugin="mujoco.elasticity.cable"/>
</extension>
<worldbody>
<geom type="plane" size="0 0 1" quat="1 0 0 0"/>
<site name="reference" pos="0 0 0"/>
<composite type="cable" curve="s" count="41 1 1" size="1" offset="0 0 1" initial="none">
<plugin plugin="mujoco.elasticity.cable">
<config key="twist" value="1e6"/>
<config key="bend" value="1e9"/>
</plugin>
<joint kind="main" damping="2"/>
<geom type="capsule" size=".005" density="1"/>
</composite>
</worldbody>
<contact>
<exclude body1="B_first" body2="B_last"/>
</contact>
<sensor>
<framepos objtype="site" objname="S_last"/>
</sensor>
<actuator>
<motor site="S_last" gear="0 0 0 0 1 0" ctrllimited="true" ctrlrange="0 4"/>
</actuator>
</mujoco>
"""
physics = engine.Physics.from_xml_string(model_with_cable_plugin)
physics_state = physics.get_state()
# qpos, qvel, act, plugin_state
self.assertLen(physics._physics_state_items(), 4)
physics.set_state(physics_state)
new_physics_state = np.random.random_sample(physics_state.shape)
physics.set_state(new_physics_state)
np.testing.assert_allclose(new_physics_state, physics.get_state())
def testSetInvalidPhysicsState(self):
badly_shaped_state = np.repeat(self._physics.get_state(), repeats=2)
with self.assertRaises(ValueError):
self._physics.set_state(badly_shaped_state)
def testNamedIndexing(self):
self.assertEqual((3,), self._physics.named.data.xpos['cart'].shape)
self.assertEqual((2, 3),
self._physics.named.data.xpos[['cart', 'pole']].shape)
def testReload(self):
self._physics.reload_from_xml_path(MODEL_PATH)
def testReset(self):
self._physics.reset()
self.assertEqual(self._physics.data.qpos[1], 0)
keyframe_id = 0
self._physics.reset(keyframe_id=keyframe_id)
self.assertEqual(self._physics.data.qpos[1],
self._physics.model.key_qpos[keyframe_id, 1])
out_of_range = [-1, 3]
max_valid = self._physics.model.nkey - 1
for actual in out_of_range:
with self.assertRaisesWithLiteralMatch(
ValueError,
engine._KEYFRAME_ID_OUT_OF_RANGE.format(
max_valid=max_valid, actual=actual)):
self._physics.reset(keyframe_id=actual)
def testLoadAndReloadFromStringWithAssets(self):
physics = engine.Physics.from_xml_string(
MODEL_WITH_ASSETS, assets=ASSETS)
physics.reload_from_xml_string(MODEL_WITH_ASSETS, assets=ASSETS)
@parameterized.parameters(*enums.mjtWarning._fields[:-1])
def testDivergenceException(self, warning_name):
warning_enum = getattr(enums.mjtWarning, warning_name)
with self.assertRaisesWithLiteralMatch(
control.PhysicsError,
engine._INVALID_PHYSICS_STATE.format(warning_names=warning_name)):
with self._physics.check_invalid_state():
self._physics.data.warning[warning_enum].number = 1
# Existing warnings should not raise an exception.
with self._physics.check_invalid_state():
pass
self._physics.reset()
with self._physics.check_invalid_state():
pass
@parameterized.parameters(float('inf'), float('nan'), 1e15)
def testBadQpos(self, bad_value):
with self._physics.reset_context():
self._physics.data.qpos[0] = bad_value
with self.assertRaises(control.PhysicsError):
with self._physics.check_invalid_state():
mujoco.mj_checkPos(self._physics.model.ptr, self._physics.data.ptr)
self._physics.reset()
with self._physics.check_invalid_state():
mujoco.mj_checkPos(self._physics.model.ptr, self._physics.data.ptr)
def testNanControl(self):
with self._physics.reset_context():
pass
# Apply the controls.
with self.assertRaisesWithLiteralMatch(
control.PhysicsError,
engine._INVALID_PHYSICS_STATE.format(warning_names='mjWARN_BADCTRL')):
with self._physics.check_invalid_state():
self._physics.data.ctrl[0] = float('nan')
self._physics.step()
def testSuppressPhysicsError(self):
bad_value = float('nan')
message = engine._INVALID_PHYSICS_STATE.format(
warning_names='mjWARN_BADCTRL')
def assert_physics_error():
self._physics.data.ctrl[0] = bad_value
with self.assertRaisesWithLiteralMatch(control.PhysicsError, message):
self._physics.forward()
def assert_warning():
self._physics.data.ctrl[0] = bad_value
with mock.patch.object(engine.logging, 'warn') as mock_warn:
self._physics.forward()
mock_warn.assert_called_once_with(message)
assert_physics_error()
with self._physics.suppress_physics_errors():
assert_warning()
with self._physics.suppress_physics_errors():
assert_warning()
assert_warning()
assert_physics_error()
@parameterized.named_parameters(
('_copy', lambda x: x.copy()),
('_deepcopy', copy.deepcopy),
('_pickle_and_unpickle', lambda x: pickle.loads(pickle.dumps(x))),
)
def testCopyOrPicklePhysics(self, func):
for _ in range(10):
self._physics.step()
physics2 = func(self._physics)
self.assertNotEqual(physics2.model.ptr, self._physics.model.ptr)
self.assertNotEqual(physics2.data.ptr, self._physics.data.ptr)
model_attr_to_compare = ('nnames', 'njmax', 'body_pos', 'geom_quat')
self._assert_attributes_equal(
physics2.model, self._physics.model, model_attr_to_compare)
data_attr_to_compare = ('time', 'energy', 'qpos', 'xpos')
self._assert_attributes_equal(
physics2.data, self._physics.data, data_attr_to_compare)
for _ in range(10):
self._physics.step()
physics2.step()
self._assert_attributes_equal(
physics2.model, self._physics.model, model_attr_to_compare)
self._assert_attributes_equal(
physics2.data, self._physics.data, data_attr_to_compare)
@parameterized.named_parameters(
('_copy', lambda x: x.copy()),
('_pickle_and_unpickle', lambda x: pickle.loads(pickle.dumps(x))),
)
def testSuppressErrorsAfterCopyOrPicklePhysics(self, func):
# Regression test for a problem that used to exist where
# suppress_physics_errors couldn't be used on Physics objects that were
# unpickled.
physics2 = func(self._physics)
with physics2.suppress_physics_errors():
pass
def testCopyDataOnly(self):
physics2 = self._physics.copy(share_model=True)
self.assertEqual(physics2.model.ptr, self._physics.model.ptr)
self.assertNotEqual(physics2.data.ptr, self._physics.data.ptr)
def testForwardDynamicsUpdatedAfterReset(self):
gravity = -9.81
self._physics.model.opt.gravity[2] = gravity
with self._physics.reset_context():
pass
self.assertAlmostEqual(
self._physics.named.data.sensordata['accelerometer'][2], -gravity)
def testActuationNotAppliedInAfterReset(self):
self._physics.data.ctrl[0] = 1.
self._physics.after_reset() # Calls `forward()` with actuation disabled.
self.assertEqual(self._physics.data.actuator_force[0], 0.)
self._physics.forward() # Call `forward` directly with actuation enabled.
self.assertEqual(self._physics.data.actuator_force[0], 1.)
def testActionSpec(self):
xml = """
<mujoco>
<worldbody>
<body>
<geom type="sphere" size="0.1"/>
<joint type="hinge" name="hinge"/>
</body>
</worldbody>
<actuator>
<motor joint="hinge" ctrllimited="false"/>
<motor joint="hinge" ctrllimited="true" ctrlrange="-1 2"/>
</actuator>
</mujoco>
"""
physics = engine.Physics.from_xml_string(xml)
spec = engine.action_spec(physics)
self.assertEqual(float, spec.dtype)
np.testing.assert_array_equal(spec.minimum, [-mujoco.mjMAXVAL, -1.0])
np.testing.assert_array_equal(spec.maximum, [mujoco.mjMAXVAL, 2.0])
def testNstep(self):
# Make initial state.
with self._physics.reset_context():
self._physics.data.qvel[0] = 1
self._physics.data.qvel[1] = 1
initial_state = self._physics.get_state()
# step() 4 times.
for _ in range(4):
self._physics.step()
for_loop_state = self._physics.get_state()
# Reset state, call step(4).
with self._physics.reset_context():
self._physics.set_state(initial_state)
self._physics.step(4)
nstep_state = self._physics.get_state()
np.testing.assert_array_equal(for_loop_state, nstep_state)
# Repeat test with with RK4 integrator:
self._physics.model.opt.integrator = enums.mjtIntegrator.mjINT_RK4
# step() 4 times.
with self._physics.reset_context():
self._physics.set_state(initial_state)
for _ in range(4):
self._physics.step()
for_loop_state_rk4 = self._physics.get_state()
# Reset state, call step(4).
with self._physics.reset_context():
self._physics.set_state(initial_state)
self._physics.step(4)
nstep_state_rk4 = self._physics.get_state()
np.testing.assert_array_equal(for_loop_state_rk4, nstep_state_rk4)
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/mujoco/engine_test.py |
# Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Mujoco implementations of base classes."""
from dm_control.mujoco.engine import action_spec
from dm_control.mujoco.engine import Camera
from dm_control.mujoco.engine import MovableCamera
from dm_control.mujoco.engine import Physics
from dm_control.mujoco.engine import TextOverlay
from mujoco import *
| dm_control-main | dm_control/mujoco/__init__.py |
# Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Mujoco `Physics` implementation and helper classes.
The `Physics` class provides the main Python interface to MuJoCo.
MuJoCo models are defined using the MJCF XML format. The `Physics` class
can load a model from a path to an XML file, an XML string, or from a serialized
MJB binary format. See the named constructors for each of these cases.
Each `Physics` instance defines a simulated world. To step forward the
simulation, use the `step` method. To set a control or actuation signal, use the
`set_control` method, which will apply the provided signal to the actuators in
subsequent calls to `step`.
Use the `Camera` class to create RGB or depth images. A `Camera` can render its
viewport to an array using the `render` method, and can query for objects
visible at specific positions using the `select` method. The `Physics` class
also provides a `render` method that returns a pixel array directly.
"""
import collections
import contextlib
import threading
from typing import Callable, NamedTuple, Optional, Union
from absl import logging
from dm_control import _render
from dm_control.mujoco import index
from dm_control.mujoco import wrapper
from dm_control.mujoco.wrapper import util
from dm_control.rl import control as _control
from dm_env import specs
import mujoco
import numpy as np
_FONT_STYLES = {
'normal': mujoco.mjtFont.mjFONT_NORMAL,
'shadow': mujoco.mjtFont.mjFONT_SHADOW,
'big': mujoco.mjtFont.mjFONT_BIG,
}
_GRID_POSITIONS = {
'top left': mujoco.mjtGridPos.mjGRID_TOPLEFT,
'top right': mujoco.mjtGridPos.mjGRID_TOPRIGHT,
'bottom left': mujoco.mjtGridPos.mjGRID_BOTTOMLEFT,
'bottom right': mujoco.mjtGridPos.mjGRID_BOTTOMRIGHT,
}
Contexts = collections.namedtuple('Contexts', ['gl', 'mujoco'])
Selected = collections.namedtuple(
'Selected', ['body', 'geom', 'skin', 'world_position'])
NamedIndexStructs = collections.namedtuple(
'NamedIndexStructs', ['model', 'data'])
Pose = collections.namedtuple(
'Pose', ['lookat', 'distance', 'azimuth', 'elevation'])
_BOTH_SEGMENTATION_AND_DEPTH_ENABLED = (
'`segmentation` and `depth` cannot both be `True`.')
_INVALID_PHYSICS_STATE = (
'Physics state is invalid. Warning(s) raised: {warning_names}')
_OVERLAYS_NOT_SUPPORTED_FOR_DEPTH_OR_SEGMENTATION = (
'Overlays are not supported with depth or segmentation rendering.')
_RENDER_FLAG_OVERRIDES_NOT_SUPPORTED_FOR_DEPTH_OR_SEGMENTATION = (
'`render_flag_overrides` are not supported for depth or segmentation '
'rendering.')
_KEYFRAME_ID_OUT_OF_RANGE = (
'`keyframe_id` must be between 0 and {max_valid} inclusive, got: {actual}.')
class Physics(_control.Physics):
"""Encapsulates a MuJoCo model.
A MuJoCo model is typically defined by an MJCF XML file [0]
```python
physics = Physics.from_xml_path('/path/to/model.xml')
with physics.reset_context():
physics.named.data.qpos['hinge'] = np.random.rand()
# Apply controls and advance the simulation state.
physics.set_control(np.random.random_sample(size=N_ACTUATORS))
physics.step()
# Render a camera defined in the XML file to a NumPy array.
rgb = physics.render(height=240, width=320, id=0)
```
[0] http://www.mujoco.org/book/modeling.html
"""
_contexts = None
def __new__(cls, *args, **kwargs):
# TODO(b/174603485): Re-enable once lint stops spuriously firing here.
obj = super(Physics, cls).__new__(cls) # pylint: disable=no-value-for-parameter
# The lock is created in `__new__` rather than `__init__` because there are
# a number of existing subclasses that override `__init__` without calling
# the `__init__` method of the superclass.
obj._contexts_lock = threading.Lock() # pylint: disable=protected-access
return obj
def __init__(self, data):
"""Initializes a new `Physics` instance.
Args:
data: Instance of `wrapper.MjData`.
"""
self._warnings_cause_exception = True
self._reload_from_data(data)
@contextlib.contextmanager
def suppress_physics_errors(self):
"""Physics warnings will be logged rather than raise exceptions."""
prev_state = self._warnings_cause_exception
self._warnings_cause_exception = False
try:
yield
finally:
self._warnings_cause_exception = prev_state
def enable_profiling(self):
"""Enables Mujoco timing profiling."""
wrapper.enable_timer(True)
def set_control(self, control):
"""Sets the control signal for the actuators.
Args:
control: NumPy array or array-like actuation values.
"""
np.copyto(self.data.ctrl, control)
def _step_with_up_to_date_position_velocity(self, nstep: int = 1) -> None:
"""Physics step with up-to-date position and velocity dependent fields."""
# In the case of Euler integration we assume mj_step1 has already been
# called for this state, finish the step with mj_step2 and then update all
# position and velocity related fields with mj_step1. This ensures that
# (most of) mjData is in sync with qpos and qvel. In the case of non-Euler
# integrators (e.g. RK4) an additional mj_step1 must be called after the
# last mj_step to ensure mjData syncing.
if self.model.opt.integrator != mujoco.mjtIntegrator.mjINT_RK4.value:
mujoco.mj_step2(self.model.ptr, self.data.ptr)
if nstep > 1:
mujoco.mj_step(self.model.ptr, self.data.ptr, nstep-1)
else:
mujoco.mj_step(self.model.ptr, self.data.ptr, nstep)
mujoco.mj_step1(self.model.ptr, self.data.ptr)
def step(self, nstep: int = 1) -> None:
"""Advances the physics state by `nstep`s.
Args:
nstep: Optional integer, number of steps to take.
The actuation can be updated by calling the `set_control` function first.
"""
with self.check_invalid_state():
if self.legacy_step:
self._step_with_up_to_date_position_velocity(nstep)
else:
mujoco.mj_step(self.model.ptr, self.data.ptr, nstep)
def render(
self,
height=240,
width=320,
camera_id=-1,
overlays=(),
depth=False,
segmentation=False,
scene_option=None,
render_flag_overrides=None,
scene_callback: Optional[Callable[['Physics', mujoco.MjvScene],
None]] = None,
):
"""Returns a camera view as a NumPy array of pixel values.
Args:
height: Viewport height (number of pixels). Optional, defaults to 240.
width: Viewport width (number of pixels). Optional, defaults to 320.
camera_id: Optional camera name or index. Defaults to -1, the free
camera, which is always defined. A nonnegative integer or string
corresponds to a fixed camera, which must be defined in the model XML.
If `camera_id` is a string then the camera must also be named.
overlays: An optional sequence of `TextOverlay` instances to draw. Only
supported if `depth` is False.
depth: If `True`, this method returns a NumPy float array of depth values
(in meters). Defaults to `False`, which results in an RGB image.
segmentation: If `True`, this method returns a 2-channel NumPy int32 array
of label values where the pixels of each object are labeled with the
pair (mjModel ID, mjtObj enum object type). Background pixels are
labeled (-1, -1). Defaults to `False`, which returns an RGB image.
scene_option: An optional `wrapper.MjvOption` instance that can be used to
render the scene with custom visualization options. If None then the
default options will be used.
render_flag_overrides: Optional mapping specifying rendering flags to
override. The keys can be either lowercase strings or `mjtRndFlag` enum
values, and the values are the overridden flag values, e.g.
`{'wireframe': True}` or `{mujoco.mjtRndFlag.mjRND_WIREFRAME: True}`.
See `mujoco.mjtRndFlag` for the set of valid flags. Must be None if
either `depth` or `segmentation` is True.
scene_callback: Called after the scene has been created and before
it is rendered. Can be used to add more geoms to the scene.
Returns:
The rendered RGB, depth or segmentation image.
"""
camera = Camera(
physics=self,
height=height,
width=width,
camera_id=camera_id,
scene_callback=scene_callback)
image = camera.render(
overlays=overlays, depth=depth, segmentation=segmentation,
scene_option=scene_option, render_flag_overrides=render_flag_overrides)
camera._scene.free() # pylint: disable=protected-access
return image
def get_state(self):
"""Returns the physics state.
Returns:
NumPy array containing full physics simulation state.
"""
return np.concatenate(self._physics_state_items())
def set_state(self, physics_state):
"""Sets the physics state.
Args:
physics_state: NumPy array containing the full physics simulation state.
Raises:
ValueError: If `physics_state` has invalid size.
"""
state_items = self._physics_state_items()
expected_shape = (sum(item.size for item in state_items),)
if expected_shape != physics_state.shape:
raise ValueError('Input physics state has shape {}. Expected {}.'.format(
physics_state.shape, expected_shape))
start = 0
for state_item in state_items:
size = state_item.size
np.copyto(state_item, physics_state[start:start + size])
start += size
def copy(self, share_model=False):
"""Creates a copy of this `Physics` instance.
Args:
share_model: If True, the copy and the original will share a common
MjModel instance. By default, both model and data will both be copied.
Returns:
A `Physics` instance.
"""
new_data = self.data._make_copy(share_model=share_model) # pylint: disable=protected-access
cls = self.__class__
new_obj = cls.__new__(cls)
# pylint: disable=protected-access
new_obj._warnings_cause_exception = True
new_obj._reload_from_data(new_data)
# pylint: enable=protected-access
return new_obj
def reset(self, keyframe_id=None):
"""Resets internal variables of the simulation, possibly to a keyframe.
Args:
keyframe_id: Optional integer specifying the index of a keyframe defined
in the model XML to which the simulation state should be initialized.
Must be between 0 and `self.model.nkey - 1` (inclusive).
Raises:
ValueError: If `keyframe_id` is out of range.
"""
if keyframe_id is None:
mujoco.mj_resetData(self.model.ptr, self.data.ptr)
else:
if not 0 <= keyframe_id < self.model.nkey:
raise ValueError(_KEYFRAME_ID_OUT_OF_RANGE.format(
max_valid=self.model.nkey-1, actual=keyframe_id))
mujoco.mj_resetDataKeyframe(self.model.ptr, self.data.ptr, keyframe_id)
# Disable actuation since we don't yet have meaningful control inputs.
with self.model.disable('actuation'):
self.forward()
def after_reset(self):
"""Runs after resetting internal variables of the physics simulation."""
# Disable actuation since we don't yet have meaningful control inputs.
with self.model.disable('actuation'):
self.forward()
def forward(self):
"""Recomputes the forward dynamics without advancing the simulation."""
# Note: `mj_forward` differs from `mj_step1` in that it also recomputes
# quantities that depend on acceleration (and therefore on the state of the
# controls). For example `mj_forward` updates accelerometer and gyro
# readings, whereas `mj_step1` does not.
# http://www.mujoco.org/book/programming.html#siForward
with self.check_invalid_state():
mujoco.mj_forward(self.model.ptr, self.data.ptr)
@contextlib.contextmanager
def check_invalid_state(self):
"""Checks whether the physics state is invalid at exit.
Yields:
None
Raises:
PhysicsError: if the simulation state is invalid at exit, unless this
context is nested inside a `suppress_physics_errors` context, in which
case a warning will be logged instead.
"""
np.copyto(self._warnings_before, self._warnings)
yield
np.greater(self._warnings, self._warnings_before, out=self._new_warnings)
if any(self._new_warnings):
warning_names = np.compress(self._new_warnings,
list(mujoco.mjtWarning.__members__))
message = _INVALID_PHYSICS_STATE.format(
warning_names=', '.join(warning_names))
if self._warnings_cause_exception:
raise _control.PhysicsError(message)
else:
logging.warn(message)
def __getstate__(self):
return self.data # All state is assumed to reside within `self.data`.
def __setstate__(self, data):
# Note: `_contexts_lock` is normally created in `__new__`, but `__new__` is
# not invoked during unpickling.
self._contexts_lock = threading.Lock()
self._warnings_cause_exception = True
self._reload_from_data(data)
def _reload_from_model(self, model):
"""Initializes a new or existing `Physics` from a `wrapper.MjModel`.
Creates a new `wrapper.MjData` instance, then delegates to
`_reload_from_data`.
Args:
model: Instance of `wrapper.MjModel`.
"""
data = wrapper.MjData(model)
self._reload_from_data(data)
def _reload_from_data(self, data):
"""Initializes a new or existing `Physics` instance from a `wrapper.MjData`.
Assigns all attributes, sets up named indexing, and creates rendering
contexts if rendering is enabled.
The default constructor as well as the other `reload_from` methods should
delegate to this method.
Args:
data: Instance of `wrapper.MjData`.
"""
if not isinstance(data, wrapper.MjData):
raise TypeError(f'Expected wrapper.MjData. Got: {type(data)}.')
self._data = data
# Performance optimization: pre-allocate numpy arrays used when checking for
# MuJoCo warnings on each step.
self._warnings = self.data.warning.number
self._warnings_before = np.empty_like(self._warnings)
self._new_warnings = np.empty(dtype=bool, shape=(len(self._warnings),))
# Forcibly free any previous GL context in order to avoid problems with GL
# implementations that do not support multiple contexts on a given device.
with self._contexts_lock:
if self._contexts:
self._free_rendering_contexts()
# Call kinematics update to enable rendering.
try:
self.after_reset()
except _control.PhysicsError as e:
logging.warning(e)
# Set up named indexing.
axis_indexers = index.make_axis_indexers(self.model)
self._named = NamedIndexStructs(
model=index.struct_indexer(self.model, 'mjmodel', axis_indexers),
data=index.struct_indexer(self.data, 'mjdata', axis_indexers),)
def free(self):
"""Frees the native MuJoCo data structures held by this `Physics` instance.
This is an advanced feature for use when manual memory management is
necessary. This `Physics` object MUST NOT be used after this function has
been called.
"""
with self._contexts_lock:
if self._contexts:
self._free_rendering_contexts()
del self._data
@classmethod
def from_model(cls, model):
"""A named constructor from a `wrapper.MjModel` instance."""
data = wrapper.MjData(model)
return cls(data)
@classmethod
def from_xml_string(cls, xml_string, assets=None):
"""A named constructor from a string containing an MJCF XML file.
Args:
xml_string: XML string containing an MJCF model description.
assets: Optional dict containing external assets referenced by the model
(such as additional XML files, textures, meshes etc.), in the form of
`{filename: contents_string}` pairs. The keys should correspond to the
filenames specified in the model XML.
Returns:
A new `Physics` instance.
"""
model = wrapper.MjModel.from_xml_string(xml_string, assets=assets)
return cls.from_model(model)
@classmethod
def from_byte_string(cls, byte_string):
"""A named constructor from a model binary as a byte string."""
model = wrapper.MjModel.from_byte_string(byte_string)
return cls.from_model(model)
@classmethod
def from_xml_path(cls, file_path):
"""A named constructor from a path to an MJCF XML file.
Args:
file_path: String containing path to model definition file.
Returns:
A new `Physics` instance.
"""
model = wrapper.MjModel.from_xml_path(file_path)
return cls.from_model(model)
@classmethod
def from_binary_path(cls, file_path):
"""A named constructor from a path to an MJB model binary file.
Args:
file_path: String containing path to model definition file.
Returns:
A new `Physics` instance.
"""
model = wrapper.MjModel.from_binary_path(file_path)
return cls.from_model(model)
def reload_from_xml_string(self, xml_string, assets=None):
"""Reloads the `Physics` instance from a string containing an MJCF XML file.
After calling this method, the state of the `Physics` instance is the same
as a new `Physics` instance created with the `from_xml_string` named
constructor.
Args:
xml_string: XML string containing an MJCF model description.
assets: Optional dict containing external assets referenced by the model
(such as additional XML files, textures, meshes etc.), in the form of
`{filename: contents_string}` pairs. The keys should correspond to the
filenames specified in the model XML.
"""
new_model = wrapper.MjModel.from_xml_string(xml_string, assets=assets)
self._reload_from_model(new_model)
def reload_from_xml_path(self, file_path):
"""Reloads the `Physics` instance from a path to an MJCF XML file.
After calling this method, the state of the `Physics` instance is the same
as a new `Physics` instance created with the `from_xml_path`
named constructor.
Args:
file_path: String containing path to model definition file.
"""
self._reload_from_model(wrapper.MjModel.from_xml_path(file_path))
@property
def named(self):
return self._named
def _make_rendering_contexts(self):
"""Creates the OpenGL and MuJoCo rendering contexts."""
# Get the offscreen framebuffer size, as specified in the model XML.
max_width = self.model.vis.global_.offwidth
max_height = self.model.vis.global_.offheight
# Create the OpenGL context.
render_context = _render.Renderer(
max_width=max_width, max_height=max_height)
# Create the MuJoCo context.
mujoco_context = wrapper.MjrContext(self.model, render_context)
self._contexts = Contexts(gl=render_context, mujoco=mujoco_context)
def _free_rendering_contexts(self):
"""Frees existing OpenGL and MuJoCo rendering contexts."""
self._contexts.mujoco.free()
self._contexts.gl.free()
self._contexts = None
@property
def contexts(self):
"""Returns a `Contexts` namedtuple, used in `Camera`s and rendering code."""
with self._contexts_lock:
if not self._contexts:
self._make_rendering_contexts()
return self._contexts
@property
def model(self):
return self._data.model
@property
def data(self):
return self._data
def _physics_state_items(self):
"""Returns list of arrays making up internal physics simulation state.
The physics state consists of the state variables, their derivatives and
actuation activations. If the model contains plugins, then the state will
also contain any plugin state.
Returns:
List of NumPy arrays containing full physics simulation state.
"""
if self.model.nplugin > 0:
return [
self.data.qpos,
self.data.qvel,
self.data.act,
self.data.plugin_state,
]
else:
return [self.data.qpos, self.data.qvel, self.data.act]
# Named views of simulation data.
def control(self):
"""Returns a copy of the control signals for the actuators."""
return self.data.ctrl.copy()
def activation(self):
"""Returns a copy of the internal states of actuators.
For details, please refer to
http://www.mujoco.org/book/computation.html#geActuation
Returns:
Activations in a numpy array.
"""
return self.data.act.copy()
def state(self):
"""Returns the full physics state. Alias for `get_physics_state`."""
return np.concatenate(self._physics_state_items())
def position(self):
"""Returns a copy of the generalized positions (system configuration)."""
return self.data.qpos.copy()
def velocity(self):
"""Returns a copy of the generalized velocities."""
return self.data.qvel.copy()
def timestep(self):
"""Returns the simulation timestep."""
return self.model.opt.timestep
def time(self):
"""Returns episode time in seconds."""
return self.data.time
class CameraMatrices(NamedTuple):
"""Component matrices used to construct the camera matrix.
The matrix product over these components yields the camera matrix.
Attributes:
image: (3, 3) image matrix.
focal: (3, 4) focal matrix.
rotation: (4, 4) rotation matrix.
translation: (4, 4) translation matrix.
"""
image: np.ndarray
focal: np.ndarray
rotation: np.ndarray
translation: np.ndarray
class Camera:
"""Mujoco scene camera.
Holds rendering properties such as the width and height of the viewport. The
camera position and rotation is defined by the Mujoco camera corresponding to
the `camera_id`. Multiple `Camera` instances may exist for a single
`camera_id`, for example to render the same view at different resolutions.
"""
def __init__(
self,
physics: Physics,
height: int = 240,
width: int = 320,
camera_id: Union[int, str] = -1,
max_geom: Optional[int] = None,
scene_callback: Optional[Callable[[Physics, mujoco.MjvScene],
None]] = None,
):
"""Initializes a new `Camera`.
Args:
physics: Instance of `Physics`.
height: Optional image height. Defaults to 240.
width: Optional image width. Defaults to 320.
camera_id: Optional camera name or index. Defaults to -1, the free
camera, which is always defined. A nonnegative integer or string
corresponds to a fixed camera, which must be defined in the model XML.
If `camera_id` is a string then the camera must also be named.
max_geom: Optional integer specifying the maximum number of geoms that can
be rendered in the same scene. If None this will be chosen automatically
based on the estimated maximum number of renderable geoms in the model.
scene_callback: Called after the scene has been created and before
it is rendered. Can be used to add more geoms to the scene.
Raises:
ValueError: If `camera_id` is outside the valid range, or if `width` or
`height` exceed the dimensions of MuJoCo's offscreen framebuffer.
"""
buffer_width = physics.model.vis.global_.offwidth
buffer_height = physics.model.vis.global_.offheight
if width > buffer_width:
raise ValueError('Image width {} > framebuffer width {}. Either reduce '
'the image width or specify a larger offscreen '
'framebuffer in the model XML using the clause\n'
'<visual>\n'
' <global offwidth="my_width"/>\n'
'</visual>'.format(width, buffer_width))
if height > buffer_height:
raise ValueError('Image height {} > framebuffer height {}. Either reduce '
'the image height or specify a larger offscreen '
'framebuffer in the model XML using the clause\n'
'<visual>\n'
' <global offheight="my_height"/>\n'
'</visual>'.format(height, buffer_height))
if isinstance(camera_id, str):
camera_id = physics.model.name2id(camera_id, 'camera')
if camera_id < -1:
raise ValueError('camera_id cannot be smaller than -1.')
if camera_id >= physics.model.ncam:
raise ValueError('model has {} fixed cameras. camera_id={} is invalid.'.
format(physics.model.ncam, camera_id))
self._width = width
self._height = height
self._physics = physics
self._scene_callback = scene_callback
# Variables corresponding to structs needed by Mujoco's rendering functions.
self._scene = wrapper.MjvScene(model=physics.model, max_geom=max_geom)
self._scene_option = wrapper.MjvOption()
self._perturb = wrapper.MjvPerturb()
self._perturb.active = 0
self._perturb.select = 0
self._rect = mujoco.MjrRect(0, 0, self._width, self._height)
self._render_camera = wrapper.MjvCamera()
self._render_camera.fixedcamid = camera_id
if camera_id == -1:
self._render_camera.type = mujoco.mjtCamera.mjCAMERA_FREE
mujoco.mjv_defaultFreeCamera(physics.model._model, self._render_camera)
else:
# As defined in the Mujoco documentation, mjCAMERA_FIXED refers to a
# camera explicitly defined in the model.
self._render_camera.type = mujoco.mjtCamera.mjCAMERA_FIXED
# Internal buffers.
self._rgb_buffer = np.empty((self._height, self._width, 3), dtype=np.uint8)
self._depth_buffer = np.empty((self._height, self._width), dtype=np.float32)
if self._physics.contexts.mujoco is not None:
with self._physics.contexts.gl.make_current() as ctx:
ctx.call(mujoco.mjr_setBuffer, mujoco.mjtFramebuffer.mjFB_OFFSCREEN,
self._physics.contexts.mujoco.ptr)
@property
def width(self):
"""Returns the image width (number of pixels)."""
return self._width
@property
def height(self):
"""Returns the image height (number of pixels)."""
return self._height
@property
def option(self):
"""Returns the camera's visualization options."""
return self._scene_option
@property
def scene(self):
"""Returns the `mujoco.MjvScene` instance used by the camera."""
return self._scene
def matrices(self) -> CameraMatrices:
"""Computes the component matrices used to compute the camera matrix.
Returns:
An instance of `CameraMatrices` containing the image, focal, rotation, and
translation matrices of the camera.
"""
camera_id = self._render_camera.fixedcamid
if camera_id == -1:
# If the camera is a 'free' camera, we get its position and orientation
# from the scene data structure. It is a stereo camera, so we average over
# the left and right channels. Note: we call `self.update()` in order to
# ensure that the contents of `scene.camera` are correct.
self.update()
pos = np.mean([camera.pos for camera in self.scene.camera], axis=0)
z = -np.mean([camera.forward for camera in self.scene.camera], axis=0)
y = np.mean([camera.up for camera in self.scene.camera], axis=0)
rot = np.vstack((np.cross(y, z), y, z))
fov = self._physics.model.vis.global_.fovy
else:
pos = self._physics.data.cam_xpos[camera_id]
rot = self._physics.data.cam_xmat[camera_id].reshape(3, 3).T
fov = self._physics.model.cam_fovy[camera_id]
# Translation matrix (4x4).
translation = np.eye(4)
translation[0:3, 3] = -pos
# Rotation matrix (4x4).
rotation = np.eye(4)
rotation[0:3, 0:3] = rot
# Focal transformation matrix (3x4).
focal_scaling = (1./np.tan(np.deg2rad(fov)/2)) * self.height / 2.0
focal = np.diag([-focal_scaling, focal_scaling, 1.0, 0])[0:3, :]
# Image matrix (3x3).
image = np.eye(3)
image[0, 2] = (self.width - 1) / 2.0
image[1, 2] = (self.height - 1) / 2.0
return CameraMatrices(
image=image, focal=focal, rotation=rotation, translation=translation)
@property
def matrix(self):
"""Returns the 3x4 camera matrix.
For a description of the camera matrix see, e.g.,
https://en.wikipedia.org/wiki/Camera_matrix.
For a usage example, see the associated test.
"""
image, focal, rotation, translation = self.matrices()
return image @ focal @ rotation @ translation
def update(self, scene_option=None):
"""Updates geometry used for rendering.
Args:
scene_option: A custom `wrapper.MjvOption` instance to use to render
the scene instead of the default. If None, will use the default.
"""
scene_option = scene_option or self._scene_option
mujoco.mjv_updateScene(self._physics.model.ptr, self._physics.data.ptr,
scene_option.ptr, self._perturb.ptr,
self._render_camera.ptr, mujoco.mjtCatBit.mjCAT_ALL,
self._scene.ptr)
def _render_on_gl_thread(self, depth, overlays):
"""Performs only those rendering calls that require an OpenGL context."""
# Render the scene.
mujoco.mjr_render(self._rect, self._scene.ptr,
self._physics.contexts.mujoco.ptr)
if not depth:
# If rendering RGB, draw any text overlays on top of the image.
for overlay in overlays:
overlay.draw(self._physics.contexts.mujoco.ptr, self._rect)
# Read the contents of either the RGB or depth buffer.
mujoco.mjr_readPixels(self._rgb_buffer if not depth else None,
self._depth_buffer if depth else None, self._rect,
self._physics.contexts.mujoco.ptr)
def render(
self,
overlays=(),
depth=False,
segmentation=False,
scene_option=None,
render_flag_overrides=None,
):
"""Renders the camera view as a numpy array of pixel values.
Args:
overlays: An optional sequence of `TextOverlay` instances to draw. Only
supported if `depth` and `segmentation` are both False.
depth: An optional boolean. If True, makes the camera return depth
measurements. Cannot be enabled if `segmentation` is True.
segmentation: An optional boolean. If True, make the camera return a
pixel-wise segmentation of the scene. Cannot be enabled if `depth` is
True.
scene_option: A custom `wrapper.MjvOption` instance to use to render
the scene instead of the default. If None, will use the default.
render_flag_overrides: Optional mapping containing rendering flags to
override. The keys can be either lowercase strings or `mjtRndFlag` enum
values, and the values are the overridden flag values, e.g.
`{'wireframe': True}` or `{mujoco.mjtRndFlag.mjRND_WIREFRAME: True}`.
See `mujoco.mjtRndFlag` for the set of valid flags. Must be empty if
either `depth` or `segmentation` is True.
Returns:
The rendered scene.
* If `depth` and `segmentation` are both False (default), this is a
(height, width, 3) uint8 numpy array containing RGB values.
* If `depth` is True, this is a (height, width) float32 numpy array
containing depth values (in meters).
* If `segmentation` is True, this is a (height, width, 2) int32 numpy
array where the first channel contains the integer ID of the object at
each pixel, and the second channel contains the corresponding object
type (a value in the `mjtObj` enum). Background pixels are labeled
(-1, -1).
Raises:
ValueError: If either `overlays` or `render_flag_overrides` is requested
when `depth` or `segmentation` rendering is enabled.
ValueError: If both depth and segmentation flags are set together.
"""
if overlays and (depth or segmentation):
raise ValueError(_OVERLAYS_NOT_SUPPORTED_FOR_DEPTH_OR_SEGMENTATION)
if render_flag_overrides and (depth or segmentation):
raise ValueError(
_RENDER_FLAG_OVERRIDES_NOT_SUPPORTED_FOR_DEPTH_OR_SEGMENTATION)
if depth and segmentation:
raise ValueError(_BOTH_SEGMENTATION_AND_DEPTH_ENABLED)
if render_flag_overrides is None:
render_flag_overrides = {}
# Update scene geometry.
self.update(scene_option=scene_option)
if self._scene_callback:
self._scene_callback(self._physics, self._scene)
# Enable flags to compute segmentation labels
if segmentation:
render_flag_overrides.update({
mujoco.mjtRndFlag.mjRND_SEGMENT: True,
mujoco.mjtRndFlag.mjRND_IDCOLOR: True,
})
# Render scene and text overlays, read contents of RGB or depth buffer.
with self.scene.override_flags(render_flag_overrides):
with self._physics.contexts.gl.make_current() as ctx:
ctx.call(self._render_on_gl_thread, depth=depth, overlays=overlays)
if depth:
# Get the distances to the near and far clipping planes.
extent = self._physics.model.stat.extent
near = self._physics.model.vis.map.znear * extent
far = self._physics.model.vis.map.zfar * extent
# Convert from [0 1] to depth in meters, see links below:
# http://stackoverflow.com/a/6657284/1461210
# https://www.khronos.org/opengl/wiki/Depth_Buffer_Precision
image = near / (1 - self._depth_buffer * (1 - near / far))
elif segmentation:
# Convert 3-channel uint8 to 1-channel uint32.
image3 = self._rgb_buffer.astype(np.uint32)
segimage = (image3[:, :, 0] +
image3[:, :, 1] * (2**8) +
image3[:, :, 2] * (2**16))
# Remap segid to 2-channel (object ID, object type) pair.
# Seg ID 0 is background -- will be remapped to (-1, -1).
segid2output = np.full((self._scene.ngeom + 1, 2), fill_value=-1,
dtype=np.int32) # Seg id cannot be > ngeom + 1.
visible_geoms = [g for g in self._scene.geoms if g.segid != -1]
visible_segids = np.array([g.segid + 1 for g in visible_geoms], np.int32)
visible_objid = np.array([g.objid for g in visible_geoms], np.int32)
visible_objtype = np.array([g.objtype for g in visible_geoms], np.int32)
segid2output[visible_segids, 0] = visible_objid
segid2output[visible_segids, 1] = visible_objtype
image = segid2output[segimage]
else:
image = self._rgb_buffer
# The first row in the buffer is the bottom row of pixels in the image.
return np.flipud(image)
def select(self, cursor_position):
"""Returns bodies and geoms visible at given coordinates in the frame.
Args:
cursor_position: A `tuple` containing x and y coordinates, normalized to
between 0 and 1, and where (0, 0) is bottom-left.
Returns:
A `Selected` namedtuple. Fields are None if nothing is selected.
"""
self.update()
aspect_ratio = self._width / self._height
cursor_x, cursor_y = cursor_position
pos = np.empty(3, np.double)
geom_id_arr = np.intc([-1])
skin_id_arr = np.intc([-1])
body_id = mujoco.mjv_select(self._physics.model.ptr, self._physics.data.ptr,
self._scene_option.ptr, aspect_ratio, cursor_x,
cursor_y, self._scene.ptr, pos, geom_id_arr,
skin_id_arr)
[geom_id] = geom_id_arr
[skin_id] = skin_id_arr
# Validate IDs
if body_id != -1:
assert 0 <= body_id < self._physics.model.nbody
else:
body_id = None
if geom_id != -1:
assert 0 <= geom_id < self._physics.model.ngeom
else:
geom_id = None
if skin_id != -1:
assert 0 <= skin_id < self._physics.model.nskin
else:
skin_id = None
if all(id_ is None for id_ in (body_id, geom_id, skin_id)):
pos = None
return Selected(
body=body_id, geom=geom_id, skin=skin_id, world_position=pos)
class MovableCamera(Camera):
"""Subclass of `Camera` that can be moved by changing its pose.
A `MovableCamera` always corresponds to a MuJoCo free camera with id -1.
"""
def __init__(
self,
physics: Physics,
height: int = 240,
width: int = 320,
max_geom: Optional[int] = None,
scene_callback: Optional[Callable[[Physics, mujoco.MjvScene],
None]] = None,
):
"""Initializes a new `MovableCamera`.
Args:
physics: Instance of `Physics`.
height: Optional image height. Defaults to 240.
width: Optional image width. Defaults to 320.
max_geom: Optional integer specifying the maximum number of geoms that can
be rendered in the same scene. If None this will be chosen automatically
based on the estimated maximum number of renderable geoms in the model.
scene_callback: Called after the scene has been created and before
it is rendered. Can be used to add more geoms to the scene.
"""
super().__init__(physics=physics, height=height, width=width, camera_id=-1,
max_geom=max_geom, scene_callback=scene_callback)
def get_pose(self):
"""Returns the pose of the camera.
Returns:
A `Pose` named tuple with fields:
lookat: NumPy array specifying lookat point.
distance: Float specifying distance to `lookat`.
azimuth: Azimuth in degrees.
elevation: Elevation in degrees.
"""
return Pose(self._render_camera.lookat, self._render_camera.distance,
self._render_camera.azimuth, self._render_camera.elevation)
def set_pose(self, lookat, distance, azimuth, elevation):
"""Sets the pose of the camera.
Args:
lookat: NumPy array or list specifying lookat point.
distance: Float specifying distance to `lookat`.
azimuth: Azimuth in degrees.
elevation: Elevation in degrees.
"""
np.copyto(self._render_camera.lookat, lookat)
self._render_camera.distance = distance
self._render_camera.azimuth = azimuth
self._render_camera.elevation = elevation
class TextOverlay:
"""A text overlay that can be drawn on top of a camera view."""
__slots__ = ('title', 'body', 'style', 'position')
def __init__(self, title='', body='', style='normal', position='top left'):
"""Initializes a new TextOverlay instance.
Args:
title: Title text.
body: Body text.
style: The font style. Can be either "normal", "shadow", or "big".
position: The grid position of the overlay. Can be either "top left",
"top right", "bottom left", or "bottom right".
"""
self.title = title
self.body = body
self.style = _FONT_STYLES[style]
self.position = _GRID_POSITIONS[position]
def draw(self, context, rect):
"""Draws the overlay.
Args:
context: A `mujoco.MjrContext` pointer.
rect: A `mujoco.MjrRect`.
"""
mujoco.mjr_overlay(self.style, self.position, rect,
util.to_binary_string(self.title),
util.to_binary_string(self.body), context)
def action_spec(physics):
"""Returns a `BoundedArraySpec` matching the `physics` actuators."""
num_actions = physics.model.nu
is_limited = physics.model.actuator_ctrllimited.ravel().astype(bool)
control_range = physics.model.actuator_ctrlrange
minima = np.full(num_actions, fill_value=-mujoco.mjMAXVAL, dtype=float)
maxima = np.full(num_actions, fill_value=mujoco.mjMAXVAL, dtype=float)
minima[is_limited], maxima[is_limited] = control_range[is_limited].T
return specs.BoundedArray(
shape=(num_actions,), dtype=float, minimum=minima, maximum=maxima)
| dm_control-main | dm_control/mujoco/engine.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Utility functions."""
from dm_control.mujoco.wrapper.mjbindings import mjlib
import numpy as np
def euler2quat(ax, ay, az):
"""Converts euler angles to a quaternion.
Note: rotation order is zyx
Args:
ax: Roll angle (deg)
ay: Pitch angle (deg).
az: Yaw angle (deg).
Returns:
A numpy array representing the rotation as a quaternion.
"""
r1 = az
r2 = ay
r3 = ax
c1 = np.cos(np.deg2rad(r1 / 2))
s1 = np.sin(np.deg2rad(r1 / 2))
c2 = np.cos(np.deg2rad(r2 / 2))
s2 = np.sin(np.deg2rad(r2 / 2))
c3 = np.cos(np.deg2rad(r3 / 2))
s3 = np.sin(np.deg2rad(r3 / 2))
q0 = c1 * c2 * c3 + s1 * s2 * s3
q1 = c1 * c2 * s3 - s1 * s2 * c3
q2 = c1 * s2 * c3 + s1 * c2 * s3
q3 = s1 * c2 * c3 - c1 * s2 * s3
return np.array([q0, q1, q2, q3])
def mj_quatprod(q, r):
quaternion = np.zeros(4)
mjlib.mju_mulQuat(quaternion, np.ascontiguousarray(q),
np.ascontiguousarray(r))
return quaternion
def mj_quat2vel(q, dt):
vel = np.zeros(3)
mjlib.mju_quat2Vel(vel, np.ascontiguousarray(q), dt)
return vel
def mj_quatneg(q):
quaternion = np.zeros(4)
mjlib.mju_negQuat(quaternion, np.ascontiguousarray(q))
return quaternion
def mj_quatdiff(source, target):
return mj_quatprod(mj_quatneg(source), np.ascontiguousarray(target))
| dm_control-main | dm_control/mujoco/math.py |
# Copyright 2017-2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Integration tests for rendering."""
import os
import platform
from absl.testing import absltest
from absl.testing import parameterized
from dm_control import _render
from dm_control import mujoco
from dm_control.mujoco.testing import decorators
from dm_control.mujoco.testing import image_utils
DEBUG_IMAGE_DIR = os.environ.get('TEST_UNDECLARED_OUTPUTS_DIR',
absltest.get_default_test_tmpdir())
# Context creation with GLFW is not threadsafe.
if _render.BACKEND == 'glfw':
# On Linux we are able to create a GLFW window in a single thread that is not
# the main thread.
# On Mac we are only allowed to create windows on the main thread, so we
# disable the `run_threaded` wrapper entirely.
NUM_THREADS = None if platform.system() == 'Darwin' else 1
else:
NUM_THREADS = 4
CALLS_PER_THREAD = 1
class RenderTest(parameterized.TestCase):
@parameterized.named_parameters(image_utils.SEQUENCES.items())
@image_utils.save_images_on_failure(output_dir=DEBUG_IMAGE_DIR)
@decorators.run_threaded(num_threads=NUM_THREADS,
calls_per_thread=CALLS_PER_THREAD)
def test_render(self, sequence):
for expected, actual in zip(sequence.iter_load(), sequence.iter_render()):
image_utils.assert_images_close(expected, actual)
@decorators.run_threaded(num_threads=NUM_THREADS,
calls_per_thread=CALLS_PER_THREAD)
@image_utils.save_images_on_failure(output_dir=DEBUG_IMAGE_DIR)
def test_render_multiple_physics_per_thread(self):
cartpole = image_utils.cartpole
humanoid = image_utils.humanoid
cartpole_frames = []
humanoid_frames = []
for cartpole_frame, humanoid_frame in zip(cartpole.iter_render(),
humanoid.iter_render()):
cartpole_frames.append(cartpole_frame)
humanoid_frames.append(humanoid_frame)
for expected, actual in zip(cartpole.iter_load(), cartpole_frames):
image_utils.assert_images_close(expected, actual)
for expected, actual in zip(humanoid.iter_load(), humanoid_frames):
image_utils.assert_images_close(expected, actual)
@decorators.run_threaded(num_threads=NUM_THREADS, calls_per_thread=1)
def test_repeatedly_create_and_destroy_rendering_contexts(self):
# Tests for errors that may occur due to per-thread GL resource leakage.
physics = mujoco.Physics.from_xml_string('<mujoco/>')
for _ in range(500):
physics._make_rendering_contexts()
physics._free_rendering_contexts()
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/mujoco/render_test.py |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for index."""
import math
from absl.testing import absltest
from absl.testing import parameterized
from dm_control.mujoco import math as mjmath
import numpy as np
class MathTest(parameterized.TestCase):
def testQuatProd(self):
np.testing.assert_allclose(
mjmath.mj_quatprod([0., 1., 0., 0.], [0., 0., 1., 0.]),
[0., 0., 0., 1.])
np.testing.assert_allclose(
mjmath.mj_quatprod([0., 0., 1., 0.], [0., 0., 0., 1.]),
[0., 1., 0., 0.])
np.testing.assert_allclose(
mjmath.mj_quatprod([0., 0., 0., 1.], [0., 1., 0., 0.]),
[0., 0., 1., 0.])
def testQuat2Vel(self):
np.testing.assert_allclose(
mjmath.mj_quat2vel([0., 1., 0., 0.], 0.1), [math.pi / 0.1, 0., 0.])
def testQuatNeg(self):
np.testing.assert_allclose(
mjmath.mj_quatneg([math.sqrt(0.5), math.sqrt(0.5), 0., 0.]),
[math.sqrt(0.5), -math.sqrt(0.5), 0., 0.])
def testQuatDiff(self):
np.testing.assert_allclose(
mjmath.mj_quatdiff([0., 1., 0., 0.], [0., 0., 1., 0.]),
[0., 0., 0., -1.])
def testEuler2Quat(self):
np.testing.assert_allclose(
mjmath.euler2quat(0., 0., 0.), [1., 0., 0., 0.])
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/mujoco/math_test.py |
# Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for mjbindings."""
from absl.testing import absltest
from absl.testing import parameterized
from dm_control.mujoco.wrapper.mjbindings import constants
from dm_control.mujoco.wrapper.mjbindings import sizes
class MjbindingsTest(parameterized.TestCase):
@parameterized.parameters(
('mjdata', 'xpos', ('nbody', 3)),
('mjmodel', 'geom_type', ('ngeom',)),
# Fields with identifiers in mjxmacro that are resolved at compile-time.
('mjmodel', 'actuator_dynprm', ('nu', constants.mjNDYN)),
# Fields with multiple named indices.
('mjmodel', 'key_qpos', ('nkey', 'nq')),
)
def testIndexDict(self, struct_name, field_name, expected_metadata):
self.assertEqual(expected_metadata,
sizes.array_sizes[struct_name][field_name])
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/mujoco/wrapper/mjbindings_test.py |
# Copyright 2017-2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Various helper functions and classes."""
import functools
import sys
import mujoco
import numpy as np
# Environment variable that can be used to override the default path to the
# MuJoCo shared library.
ENV_MJLIB_PATH = "MJLIB_PATH"
DEFAULT_ENCODING = sys.getdefaultencoding()
def to_binary_string(s):
"""Convert text string to binary."""
if isinstance(s, bytes):
return s
return s.encode(DEFAULT_ENCODING)
def to_native_string(s):
"""Convert a text or binary string to the native string format."""
if isinstance(s, bytes):
return s.decode(DEFAULT_ENCODING)
else:
return s
def get_mjlib():
return mujoco
@functools.wraps(np.ctypeslib.ndpointer)
def ndptr(*args, **kwargs):
"""Wraps `np.ctypeslib.ndpointer` to allow passing None for NULL pointers."""
base = np.ctypeslib.ndpointer(*args, **kwargs)
def from_param(_, obj):
if obj is None:
return obj
else:
return base.from_param(obj)
return type(base.__name__, (base,), {"from_param": classmethod(from_param)})
| dm_control-main | dm_control/mujoco/wrapper/util.py |
# Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Python bindings and wrapper classes for MuJoCo."""
from dm_control.mujoco.wrapper import mjbindings
from dm_control.mujoco.wrapper.core import callback_context
from dm_control.mujoco.wrapper.core import enable_timer
from dm_control.mujoco.wrapper.core import Error
from dm_control.mujoco.wrapper.core import get_schema
from dm_control.mujoco.wrapper.core import MjData
from dm_control.mujoco.wrapper.core import MjModel
from dm_control.mujoco.wrapper.core import MjrContext
from dm_control.mujoco.wrapper.core import MjvCamera
from dm_control.mujoco.wrapper.core import MjvFigure
from dm_control.mujoco.wrapper.core import MjvOption
from dm_control.mujoco.wrapper.core import MjvPerturb
from dm_control.mujoco.wrapper.core import MjvScene
from dm_control.mujoco.wrapper.core import save_last_parsed_model_to_xml
from dm_control.mujoco.wrapper.core import set_callback
| dm_control-main | dm_control/mujoco/wrapper/__init__.py |
# Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Main user-facing classes and utility functions for loading MuJoCo models."""
import contextlib
import copy
import ctypes
import weakref
from absl import logging
from dm_control.mujoco.wrapper import util
# Some clients explicitly import core.mjlib.
from dm_control.mujoco.wrapper.mjbindings import mjlib # pylint: disable=unused-import
import mujoco
import numpy as np
# Unused internal import: resources.
_FAKE_BINARY_FILENAME = "model.mjb"
_CONTACT_ID_OUT_OF_RANGE = (
"`contact_id` must be between 0 and {max_valid} (inclusive), got: {actual}."
)
class Error(Exception):
"""Base class for MuJoCo exceptions."""
pass
if mujoco.mjVERSION_HEADER != mujoco.mj_version():
raise Error("MuJoCo library version ({0}) does not match header version "
"({1})".format(mujoco.mjVERSION_HEADER, mujoco.mj_version()))
# This is used to keep track of the `MJMODEL` pointer that was most recently
# loaded by `_get_model_ptr_from_xml`. Only this model can be saved to XML.
_LAST_PARSED_MODEL_PTR = None
_NOT_LAST_PARSED_ERROR = (
"Only the model that was most recently loaded from an XML file or string "
"can be saved to an XML file.")
import time
# NB: Python functions that are called from C are defined at module-level to
# ensure they won't be garbage-collected before they are called.
@ctypes.CFUNCTYPE(None, ctypes.c_char_p)
def _warning_callback(message):
logging.warning(util.to_native_string(message))
@ctypes.CFUNCTYPE(None, ctypes.c_char_p)
def _error_callback(message):
logging.fatal(util.to_native_string(message))
# Override MuJoCo's callbacks for handling warnings
mujoco.set_mju_user_warning(_warning_callback)
def enable_timer(enabled=True):
if enabled:
set_callback("mjcb_time", time.time)
else:
set_callback("mjcb_time", None)
def _str2type(type_str):
type_id = mujoco.mju_str2Type(util.to_binary_string(type_str))
if not type_id:
raise Error("{!r} is not a valid object type name.".format(type_str))
return type_id
def _type2str(type_id):
type_str_ptr = mujoco.mju_type2Str(type_id)
if not type_str_ptr:
raise Error("{!r} is not a valid object type ID.".format(type_id))
return type_str_ptr
def set_callback(name, new_callback=None):
"""Sets a user-defined callback function to modify MuJoCo's behavior.
Callback functions should have the following signature:
func(const_mjmodel_ptr, mjdata_ptr) -> None
Args:
name: Name of the callback to set. Must be a field in
`functions.function_pointers`.
new_callback: The new callback. This can be one of the following:
* A Python callable
* A C function exposed by a `ctypes.CDLL` object
* An integer specifying the address of a callback function
* None, in which case any existing callback of that name is removed
"""
getattr(mujoco, "set_" + name)(new_callback)
@contextlib.contextmanager
def callback_context(name, new_callback=None):
"""Context manager that temporarily overrides a MuJoCo callback function.
On exit, the callback will be restored to its original value (None if the
callback was not already overridden when the context was entered).
Args:
name: Name of the callback to set. Must be a field in
`mjbindings.function_pointers`.
new_callback: The new callback. This can be one of the following:
* A Python callable
* A C function exposed by a `ctypes.CDLL` object
* An integer specifying the address of a callback function
* None, in which case any existing callback of that name is removed
Yields:
None
"""
old_callback = getattr(mujoco, "get_" + name)()
set_callback(name, new_callback)
try:
yield
finally:
# Ensure that the callback is reset on exit, even if an exception is raised.
set_callback(name, old_callback)
def get_schema():
"""Returns a string containing the schema used by the MuJoCo XML parser."""
buf = ctypes.create_string_buffer(100000)
mujoco.mj_printSchema(None, buf, len(buf), 0, 0)
return buf.value
def _get_model_ptr_from_xml(xml_path=None, xml_string=None, assets=None):
"""Parses a model XML file, compiles it, and returns a pointer to an mjModel.
Args:
xml_path: None or a path to a model XML file in MJCF or URDF format.
xml_string: None or an XML string containing an MJCF or URDF model
description.
assets: None or a dict containing external assets referenced by the model
(such as additional XML files, textures, meshes etc.), in the form of
`{filename: contents_string}` pairs. The keys should correspond to the
filenames specified in the model XML. Ignored if `xml_string` is None.
One of `xml_path` or `xml_string` must be specified.
Returns:
A `ctypes.POINTER` to a new `mjbindings.types.MJMODEL` instance.
Raises:
TypeError: If both or neither of `xml_path` and `xml_string` are specified.
Error: If the model is not created successfully.
"""
if xml_path is None and xml_string is None:
raise TypeError(
"At least one of `xml_path` or `xml_string` must be specified.")
elif xml_path is not None and xml_string is not None:
raise TypeError(
"Only one of `xml_path` or `xml_string` may be specified.")
if xml_string is not None:
ptr = mujoco.MjModel.from_xml_string(xml_string, assets or {})
else:
ptr = mujoco.MjModel.from_xml_path(xml_path, assets or {})
global _LAST_PARSED_MODEL_PTR
_LAST_PARSED_MODEL_PTR = ptr
return ptr
def save_last_parsed_model_to_xml(xml_path, check_model=None):
"""Writes a description of the most recently loaded model to an MJCF XML file.
Args:
xml_path: Path to the output XML file.
check_model: Optional `MjModel` instance. If specified, this model will be
checked to see if it is the most recently parsed one, and a ValueError
will be raised otherwise.
Raises:
Error: If MuJoCo encounters an error while writing the XML file.
ValueError: If `check_model` was passed, and this model is not the most
recently parsed one.
"""
if check_model and check_model.ptr is not _LAST_PARSED_MODEL_PTR:
raise ValueError(_NOT_LAST_PARSED_ERROR)
mujoco.mj_saveLastXML(xml_path, _LAST_PARSED_MODEL_PTR)
def _get_model_ptr_from_binary(binary_path=None, byte_string=None):
"""Returns a pointer to an mjModel from the contents of a MuJoCo model binary.
Args:
binary_path: Path to an MJB file (as produced by MjModel.save_binary).
byte_string: String of bytes (as returned by MjModel.to_bytes).
One of `binary_path` or `byte_string` must be specified.
Returns:
A `ctypes.POINTER` to a new `mjbindings.types.MJMODEL` instance.
Raises:
TypeError: If both or neither of `byte_string` and `binary_path`
are specified.
"""
if binary_path is None and byte_string is None:
raise TypeError(
"At least one of `byte_string` or `binary_path` must be specified.")
elif binary_path is not None and byte_string is not None:
raise TypeError(
"Only one of `byte_string` or `binary_path` may be specified.")
if byte_string is not None:
assets = {_FAKE_BINARY_FILENAME: byte_string}
return mujoco.MjModel.from_binary_path(_FAKE_BINARY_FILENAME, assets)
return mujoco.MjModel.from_binary_path(binary_path, {})
class _MjModelMeta(type):
"""Metaclass which allows MjModel below to delegate to mujoco.MjModel."""
def __new__(cls, name, bases, dct):
for attr in dir(mujoco.MjModel):
if not attr.startswith("_"):
if attr not in dct:
# pylint: disable=protected-access
fget = lambda self, attr=attr: getattr(self._model, attr)
fset = (
lambda self, value, attr=attr: setattr(self._model, attr, value))
# pylint: enable=protected-access
dct[attr] = property(fget, fset)
return super().__new__(cls, name, bases, dct)
class MjModel(metaclass=_MjModelMeta):
"""Wrapper class for a MuJoCo 'mjModel' instance.
MjModel encapsulates features of the model that are expected to remain
constant. It also contains simulation and visualization options which may be
changed occasionally, although this is done explicitly by the user.
"""
_HAS_DYNAMIC_ATTRIBUTES = True
def __init__(self, model_ptr):
"""Creates a new MjModel instance from a mujoco.MjModel."""
self._model = model_ptr
@property
def ptr(self):
"""The lower level MjModel instance."""
return self._model
def __getstate__(self):
return self._model
def __setstate__(self, state):
self._model = state
def __copy__(self):
new_model_ptr = copy.copy(self._model)
return self.__class__(new_model_ptr)
@classmethod
def from_xml_string(cls, xml_string, assets=None):
"""Creates an `MjModel` instance from a model description XML string.
Args:
xml_string: String containing an MJCF or URDF model description.
assets: Optional dict containing external assets referenced by the model
(such as additional XML files, textures, meshes etc.), in the form of
`{filename: contents_string}` pairs. The keys should correspond to the
filenames specified in the model XML.
Returns:
An `MjModel` instance.
"""
model_ptr = _get_model_ptr_from_xml(xml_string=xml_string, assets=assets)
return cls(model_ptr)
@classmethod
def from_byte_string(cls, byte_string):
"""Creates an MjModel instance from a model binary as a string of bytes."""
model_ptr = _get_model_ptr_from_binary(byte_string=byte_string)
return cls(model_ptr)
@classmethod
def from_xml_path(cls, xml_path):
"""Creates an MjModel instance from a path to a model XML file."""
model_ptr = _get_model_ptr_from_xml(xml_path=xml_path)
return cls(model_ptr)
@classmethod
def from_binary_path(cls, binary_path):
"""Creates an MjModel instance from a path to a compiled model binary."""
model_ptr = _get_model_ptr_from_binary(binary_path=binary_path)
return cls(model_ptr)
def save_binary(self, binary_path):
"""Saves the MjModel instance to a binary file."""
mujoco.mj_saveModel(self.ptr, binary_path, None)
def to_bytes(self):
"""Serialize the model to a string of bytes."""
bufsize = mujoco.mj_sizeModel(self.ptr)
buf = np.zeros(shape=(bufsize,), dtype=np.uint8)
mujoco.mj_saveModel(self.ptr, None, buf)
return buf.tobytes()
def copy(self):
"""Returns a copy of this MjModel instance."""
return self.__copy__()
def free(self):
"""Frees the native resources held by this MjModel.
This is an advanced feature for use when manual memory management is
necessary. This MjModel object MUST NOT be used after this function has
been called.
"""
del self._ptr
def name2id(self, name, object_type):
"""Returns the integer ID of a specified MuJoCo object.
Args:
name: String specifying the name of the object to query.
object_type: The type of the object. Can be either a lowercase string
(e.g. 'body', 'geom') or an `mjtObj` enum value.
Returns:
An integer object ID.
Raises:
Error: If `object_type` is not a valid MuJoCo object type, or if no object
with the corresponding name and type was found.
"""
if isinstance(object_type, str):
object_type = _str2type(object_type)
obj_id = mujoco.mj_name2id(self.ptr, object_type, name)
if obj_id == -1:
raise Error("Object of type {!r} with name {!r} does not exist.".format(
_type2str(object_type), name))
return obj_id
def id2name(self, object_id, object_type):
"""Returns the name associated with a MuJoCo object ID, if there is one.
Args:
object_id: Integer ID.
object_type: The type of the object. Can be either a lowercase string
(e.g. 'body', 'geom') or an `mjtObj` enum value.
Returns:
A string containing the object name, or an empty string if the object ID
either doesn't exist or has no name.
Raises:
Error: If `object_type` is not a valid MuJoCo object type.
"""
if isinstance(object_type, str):
object_type = _str2type(object_type)
return mujoco.mj_id2name(self.ptr, object_type, object_id) or ""
@contextlib.contextmanager
def disable(self, *flags):
"""Context manager for temporarily disabling MuJoCo flags.
Args:
*flags: Positional arguments specifying flags to disable. Can be either
lowercase strings (e.g. 'gravity', 'contact') or `mjtDisableBit` enum
values.
Yields:
None
Raises:
ValueError: If any item in `flags` is neither a valid name nor a value
from `mujoco.mjtDisableBit`.
"""
old_bitmask = self.opt.disableflags
new_bitmask = old_bitmask
for flag in flags:
if isinstance(flag, str):
try:
field_name = "mjDSBL_" + flag.upper()
flag = getattr(mujoco.mjtDisableBit, field_name)
except AttributeError:
valid_names = [
field_name.split("_")[1].lower()
for field_name in list(mujoco.mjtDisableBit.__members__)[:-1]
]
raise ValueError("'{}' is not a valid flag name. Valid names: {}"
.format(flag, ", ".join(valid_names))) from None
elif isinstance(flag, int):
flag = mujoco.mjtDisableBit(flag)
new_bitmask |= flag.value
self.opt.disableflags = new_bitmask
try:
yield
finally:
self.opt.disableflags = old_bitmask
@property
def name(self):
"""Returns the name of the model."""
# The model's name is the first null terminated string in _model.names
return str(self._model.names[:self._model.names.find(b"\0")], "ascii")
class _MjDataMeta(type):
"""Metaclass which allows MjData below to delegate to mujoco.MjData."""
def __new__(cls, name, bases, dct):
for attr in dir(mujoco.MjData):
if not attr.startswith("_"):
if attr not in dct:
# pylint: disable=protected-access
fget = lambda self, attr=attr: getattr(self._data, attr)
fset = lambda self, value, attr=attr: setattr(self._data, attr, value)
# pylint: enable=protected-access
dct[attr] = property(fget, fset)
return super().__new__(cls, name, bases, dct)
class MjData(metaclass=_MjDataMeta):
"""Wrapper class for a MuJoCo 'mjData' instance.
MjData contains all of the dynamic variables and intermediate results produced
by the simulation. These are expected to change on each simulation timestep.
"""
_HAS_DYNAMIC_ATTRIBUTES = True
def __init__(self, model):
"""Construct a new MjData instance.
Args:
model: An MjModel instance.
"""
self._model = model
self._data = mujoco.MjData(model._model)
def __getstate__(self):
return (self._model, self._data)
def __setstate__(self, state):
self._model, self._data = state
def __copy__(self):
# This makes a shallow copy that shares the same parent MjModel instance.
return self._make_copy(share_model=True)
def _make_copy(self, share_model):
# TODO(nimrod): Avoid allocating a new MjData just to replace it.
new_obj = self.__class__(
self._model if share_model else copy.copy(self._model))
super(self.__class__, new_obj).__setattr__("_data", copy.copy(self._data))
return new_obj
def copy(self):
"""Returns a copy of this MjData instance with the same parent MjModel."""
return self.__copy__()
def object_velocity(self, object_id, object_type, local_frame=False):
"""Returns the 6D velocity (linear, angular) of a MuJoCo object.
Args:
object_id: Object identifier. Can be either integer ID or String name.
object_type: The type of the object. Can be either a lowercase string
(e.g. 'body', 'geom') or an `mjtObj` enum value.
local_frame: Boolean specifiying whether the velocity is given in the
global (worldbody), or local (object) frame.
Returns:
2x3 array with stacked (linear_velocity, angular_velocity)
Raises:
Error: If `object_type` is not a valid MuJoCo object type, or if no object
with the corresponding name and type was found.
"""
if not isinstance(object_type, int):
object_type = _str2type(object_type)
velocity = np.empty(6, dtype=np.float64)
if not isinstance(object_id, int):
object_id = self.model.name2id(object_id, object_type)
mujoco.mj_objectVelocity(self._model.ptr, self._data, object_type,
object_id, velocity, local_frame)
# MuJoCo returns velocities in (angular, linear) order, which we flip here.
return velocity.reshape(2, 3)[::-1]
def contact_force(self, contact_id):
"""Returns the wrench of a contact as a 2 x 3 array of (forces, torques).
Args:
contact_id: Integer, the index of the contact within the contact buffer
(`self.contact`).
Returns:
2x3 array with stacked (force, torque). Note that the order of dimensions
is (normal, tangent, tangent), in the contact's frame.
Raises:
ValueError: If `contact_id` is negative or bigger than ncon-1.
"""
if not 0 <= contact_id < self.ncon:
raise ValueError(_CONTACT_ID_OUT_OF_RANGE
.format(max_valid=self.ncon-1, actual=contact_id))
# Run the portion of `mj_step2` that are needed for correct contact forces.
mujoco.mj_fwdActuation(self._model.ptr, self._data)
mujoco.mj_fwdAcceleration(self._model.ptr, self._data)
mujoco.mj_fwdConstraint(self._model.ptr, self._data)
wrench = np.empty(6, dtype=np.float64)
mujoco.mj_contactForce(self._model.ptr, self._data, contact_id, wrench)
return wrench.reshape(2, 3)
@property
def ptr(self):
"""The lower level MjData instance."""
return self._data
@property
def model(self):
"""The parent MjModel for this MjData instance."""
return self._model
@property
def contact(self):
"""Variable-length recarray containing all current contacts."""
return self._data.contact[:self.ncon]
# Docstrings for these subclasses are inherited from their parent class.
class MjvCamera(mujoco.MjvCamera): # pylint: disable=missing-docstring
# Provide this alias for the "type" property for backwards compatibility.
@property
def type_(self):
return self.type
@type_.setter
def type_(self, t):
self.type = t
@property
def ptr(self):
return self
class MjvOption(mujoco.MjvOption): # pylint: disable=missing-docstring
def __init__(self):
super().__init__()
self.flags[mujoco.mjtVisFlag.mjVIS_RANGEFINDER] = False
# Provided for backwards compatibility
@property
def ptr(self):
return self
class MjrContext:
"""Wrapper for mujoco.MjrContext."""
def __init__(self,
model,
gl_context,
font_scale=mujoco.mjtFontScale.mjFONTSCALE_150):
"""Initializes this MjrContext instance.
Args:
model: An `MjModel` instance.
gl_context: A `render.ContextBase` instance.
font_scale: Integer controlling the font size for text. Must be a value
in `mujoco.mjtFontScale`.
Raises:
ValueError: If `font_scale` is invalid.
"""
if not isinstance(font_scale, mujoco.mjtFontScale):
font_scale = mujoco.mjtFontScale(font_scale)
self._gl_context = gl_context
with gl_context.make_current() as ctx:
ptr = ctx.call(mujoco.MjrContext, model.ptr, font_scale)
ctx.call(mujoco.mjr_setBuffer, mujoco.mjtFramebuffer.mjFB_OFFSCREEN, ptr)
gl_context.keep_alive(ptr)
gl_context.increment_refcount()
self._ptr = weakref.ref(ptr)
@property
def ptr(self):
return self._ptr()
def free(self):
"""Frees the native resources held by this MjrContext.
This is an advanced feature for use when manual memory management is
necessary. This MjrContext object MUST NOT be used after this function has
been called.
"""
if self._gl_context and not self._gl_context.terminated:
ptr = self.ptr
if ptr:
self._gl_context.dont_keep_alive(ptr)
with self._gl_context.make_current() as ctx:
ctx.call(ptr.free)
if self._gl_context:
self._gl_context.decrement_refcount()
self._gl_context.free()
self._gl_context = None
def __del__(self):
self.free()
# A mapping from human-readable short names to mjtRndFlag enum values, i.e.
# {'shadow': mjtRndFlag.mjRND_SHADOW, 'fog': mjtRndFlag.mjRND_FOG, ...}
_NAME_TO_RENDER_FLAG_ENUM_VALUE = {
name[len("mjRND_"):].lower(): getattr(mujoco.mjtRndFlag, name).value
for name in mujoco.mjtRndFlag.__members__
if name != "mjRND_NUMRNDFLAG"
}
def _estimate_max_renderable_geoms(model):
"""Estimates the maximum number of renderable geoms for a given model."""
# Only one type of object frame can be rendered at once.
max_nframes = max(
[model.nbody, model.ngeom, model.nsite, model.ncam, model.nlight])
# This is probably an underestimate, but it is unlikely that all possible
# rendering options will be enabled simultaneously, or that all renderable
# geoms will be present within the viewing frustum at the same time.
return (
3 * max_nframes + # 1 geom per axis for each frame.
4 * model.ngeom + # geom itself + contacts + 2 * split contact forces.
3 * model.nbody + # COM + inertia box + perturbation force.
model.nsite +
model.ntendon +
model.njnt +
model.nu +
model.nskin +
model.ncam +
model.nlight)
class MjvScene(mujoco.MjvScene): # pylint: disable=missing-docstring
def __init__(self, model=None, max_geom=None):
"""Initializes a new `MjvScene` instance.
Args:
model: (optional) An `MjModel` instance.
max_geom: (optional) An integer specifying the maximum number of geoms
that can be represented in the scene. If None, this will be chosen
automatically based on `model`.
"""
if model is None:
super().__init__()
else:
if max_geom is None:
if model is None:
max_renderable_geoms = 0
else:
max_renderable_geoms = _estimate_max_renderable_geoms(model)
max_geom = max(1000, max_renderable_geoms)
super().__init__(model.ptr, max_geom)
@property
def ptr(self):
return self
@contextlib.contextmanager
def override_flags(self, overrides):
"""Context manager for temporarily overriding rendering flags.
Args:
overrides: A mapping specifying rendering flags to override. The keys can
be either lowercase strings or `mjtRndFlag` enum values, and the values
are the overridden flag values, e.g. `{'wireframe': True}` or
`{mujoco.mjtRndFlag.mjRND_WIREFRAME: True}`. See `mujoco.mjtRndFlag` for
the set of valid flags.
Yields:
None
"""
if not overrides:
yield
else:
original_flags = self.flags.copy()
for key, value in overrides.items():
index = _NAME_TO_RENDER_FLAG_ENUM_VALUE.get(key, key)
self.flags[index] = value
try:
yield
finally:
np.copyto(self.flags, original_flags)
def free(self):
"""Frees the native resources held by this MjvScene.
This is an advanced feature for use when manual memory management is
necessary. This MjvScene object MUST NOT be used after this function has
been called.
"""
pass
@property
def geoms(self):
"""Variable-length recarray containing all geoms currently in the buffer."""
return super().geoms[:super().ngeom]
class MjvPerturb(mujoco.MjvPerturb): # pylint: disable=missing-docstring
@property
def ptr(self):
return self
class MjvFigure(mujoco.MjvFigure): # pylint: disable=missing-docstring
@property
def ptr(self):
return self
@property
def range_(self):
return self.range
@range_.setter
def range_(self, value):
self.range = value
| dm_control-main | dm_control/mujoco/wrapper/core.py |
# Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for core.py."""
import gc
import os
import pickle
from absl.testing import absltest
from absl.testing import parameterized
from dm_control import _render
from dm_control.mujoco.testing import assets
from dm_control.mujoco.wrapper import core
import mujoco
import numpy as np
HUMANOID_XML_PATH = assets.get_path("humanoid.xml")
MODEL_WITH_ASSETS = assets.get_contents("model_with_assets.xml")
ASSETS = {
"texture.png": assets.get_contents("deepmind.png"),
"mesh.stl": assets.get_contents("cube.stl"),
"included.xml": assets.get_contents("sphere.xml")
}
SCALAR_TYPES = (int, float)
ARRAY_TYPES = (np.ndarray,)
OUT_DIR = absltest.get_default_test_tmpdir()
if not os.path.exists(OUT_DIR):
os.makedirs(OUT_DIR) # Ensure that the output directory exists.
class CoreTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.model = core.MjModel.from_xml_path(HUMANOID_XML_PATH)
self.data = core.MjData(self.model)
def _assert_attributes_equal(self, actual_obj, expected_obj, attr_to_compare):
for name in attr_to_compare:
actual_value = getattr(actual_obj, name)
expected_value = getattr(expected_obj, name)
try:
if isinstance(expected_value, np.ndarray):
np.testing.assert_array_equal(actual_value, expected_value)
else:
self.assertEqual(actual_value, expected_value)
except AssertionError as e:
self.fail("Attribute '{}' differs from expected value: {}"
.format(name, str(e)))
def testLoadXML(self):
with open(HUMANOID_XML_PATH, "r") as f:
xml_string = f.read()
model = core.MjModel.from_xml_string(xml_string)
core.MjData(model)
with self.assertRaises(TypeError):
core.MjModel()
with self.assertRaises(ValueError):
core.MjModel.from_xml_path("/path/to/nonexistent/model/file.xml")
xml_with_warning = """
<mujoco>
<size njmax='2'/>
<worldbody>
<body pos='0 0 0'>
<geom type='box' size='.1 .1 .1'/>
</body>
<body pos='0 0 0'>
<joint type='slide' axis='1 0 0'/>
<geom type='box' size='.1 .1 .1'/>
</body>
</worldbody>
</mujoco>"""
# This model should compile successfully, but raise a warning on the first
# simulation step.
model = core.MjModel.from_xml_string(xml_with_warning)
data = core.MjData(model)
mujoco.mj_step(model.ptr, data.ptr)
def testLoadXMLWithAssetsFromString(self):
core.MjModel.from_xml_string(MODEL_WITH_ASSETS, assets=ASSETS)
with self.assertRaises(ValueError):
# Should fail to load without the assets
core.MjModel.from_xml_string(MODEL_WITH_ASSETS)
def testSaveLastParsedModelToXML(self):
save_xml_path = os.path.join(OUT_DIR, "tmp_humanoid.xml")
not_last_parsed = core.MjModel.from_xml_path(HUMANOID_XML_PATH)
last_parsed = core.MjModel.from_xml_path(HUMANOID_XML_PATH)
# Modify the model before saving it in order to confirm that the changes are
# written to the XML.
last_parsed.geom_pos.flat[:] = np.arange(last_parsed.geom_pos.size)
core.save_last_parsed_model_to_xml(save_xml_path, check_model=last_parsed)
loaded = core.MjModel.from_xml_path(save_xml_path)
self._assert_attributes_equal(last_parsed, loaded, ["geom_pos"])
core.MjData(loaded)
# Test that `check_model` results in a ValueError if it is not the most
# recently parsed model.
with self.assertRaisesWithLiteralMatch(
ValueError, core._NOT_LAST_PARSED_ERROR):
core.save_last_parsed_model_to_xml(save_xml_path,
check_model=not_last_parsed)
def testBinaryIO(self):
bin_path = os.path.join(OUT_DIR, "tmp_humanoid.mjb")
self.model.save_binary(bin_path)
core.MjModel.from_binary_path(bin_path)
byte_string = self.model.to_bytes()
core.MjModel.from_byte_string(byte_string)
def testDimensions(self):
self.assertEqual(self.data.qpos.shape[0], self.model.nq)
self.assertEqual(self.data.qvel.shape[0], self.model.nv)
self.assertEqual(self.model.body_pos.shape, (self.model.nbody, 3))
def testStep(self):
t0 = self.data.time
mujoco.mj_step(self.model.ptr, self.data.ptr)
self.assertEqual(self.data.time, t0 + self.model.opt.timestep)
self.assertTrue(np.all(np.isfinite(self.data.qpos[:])))
self.assertTrue(np.all(np.isfinite(self.data.qvel[:])))
def testMultipleData(self):
data2 = core.MjData(self.model)
self.assertNotEqual(self.data.ptr, data2.ptr)
t0 = self.data.time
mujoco.mj_step(self.model.ptr, self.data.ptr)
self.assertEqual(self.data.time, t0 + self.model.opt.timestep)
self.assertEqual(data2.time, 0)
def testMultipleModel(self):
model2 = core.MjModel.from_xml_path(HUMANOID_XML_PATH)
self.assertNotEqual(self.model.ptr, model2.ptr)
self.model.opt.timestep += 0.001
self.assertEqual(self.model.opt.timestep, model2.opt.timestep + 0.001)
def testModelName(self):
self.assertEqual(self.model.name, "humanoid")
@parameterized.named_parameters(
("_copy", lambda x: x.copy()),
("_pickle_unpickle", lambda x: pickle.loads(pickle.dumps(x))),)
def testCopyOrPickleModel(self, func):
timestep = 0.12345
self.model.opt.timestep = timestep
body_pos = self.model.body_pos + 1
self.model.body_pos[:] = body_pos
model2 = func(self.model)
self.assertNotEqual(model2.ptr, self.model.ptr)
self.assertEqual(model2.opt.timestep, timestep)
np.testing.assert_array_equal(model2.body_pos, body_pos)
@parameterized.named_parameters(
("_copy", lambda x: x.copy()),
("_pickle_unpickle", lambda x: pickle.loads(pickle.dumps(x))),)
def testCopyOrPickleData(self, func):
for _ in range(10):
mujoco.mj_step(self.model.ptr, self.data.ptr)
data2 = func(self.data)
attr_to_compare = ("time", "energy", "qpos", "xpos")
self.assertNotEqual(data2.ptr, self.data.ptr)
self._assert_attributes_equal(data2, self.data, attr_to_compare)
for _ in range(10):
mujoco.mj_step(self.model.ptr, self.data.ptr)
mujoco.mj_step(data2.model.ptr, data2.ptr)
self._assert_attributes_equal(data2, self.data, attr_to_compare)
@parameterized.named_parameters(
("_copy", lambda x: x.copy()),
("_pickle_unpickle", lambda x: pickle.loads(pickle.dumps(x))),)
def testCopyOrPickleStructs(self, func):
for _ in range(10):
mujoco.mj_step(self.model.ptr, self.data.ptr)
data2 = func(self.data)
self.assertNotEqual(data2.ptr, self.data.ptr)
attr_to_compare = ("warning", "timer", "solver")
self._assert_attributes_equal(self.data, data2, attr_to_compare)
for _ in range(10):
mujoco.mj_step(self.model.ptr, self.data.ptr)
mujoco.mj_step(data2.model.ptr, data2.ptr)
self._assert_attributes_equal(self.data, data2, attr_to_compare)
@parameterized.parameters(
("right_foot", "body", 6),
("right_foot", mujoco.mjtObj.mjOBJ_BODY, 6),
("left_knee", "joint", 11),
("left_knee", mujoco.mjtObj.mjOBJ_JOINT, 11),
)
def testNamesIds(self, name, object_type, object_id):
output_id = self.model.name2id(name, object_type)
self.assertEqual(object_id, output_id)
output_name = self.model.id2name(object_id, object_type)
self.assertEqual(name, output_name)
def testNamesIdsExceptions(self):
with self.assertRaisesRegex(core.Error, "does not exist"):
self.model.name2id("nonexistent_body_name", "body")
with self.assertRaisesRegex(core.Error, "is not a valid object type"):
self.model.name2id("right_foot", "nonexistent_type_name")
def testNamelessObject(self):
# The model in humanoid.xml contains a single nameless camera.
name = self.model.id2name(0, "camera")
self.assertEqual("", name)
def testSingleCallbackContext(self):
callback_was_called = [False]
def callback(unused_model, unused_data):
callback_was_called[0] = True
mujoco.mj_step(self.model.ptr, self.data.ptr)
self.assertFalse(callback_was_called[0])
class DummyError(RuntimeError):
pass
try:
with core.callback_context("mjcb_passive", callback):
# Stepping invokes the `mjcb_passive` callback.
mujoco.mj_step(self.model.ptr, self.data.ptr)
self.assertTrue(callback_was_called[0])
# Exceptions should not prevent `mjcb_passive` from being reset.
raise DummyError("Simulated exception.")
except DummyError:
pass
# `mjcb_passive` should have been reset to None.
callback_was_called[0] = False
mujoco.mj_step(self.model.ptr, self.data.ptr)
self.assertFalse(callback_was_called[0])
def testNestedCallbackContexts(self):
last_called = [None]
outer_called = "outer called"
inner_called = "inner called"
def outer(unused_model, unused_data):
last_called[0] = outer_called
def inner(unused_model, unused_data):
last_called[0] = inner_called
with core.callback_context("mjcb_passive", outer):
# This should execute `outer` a few times.
mujoco.mj_step(self.model.ptr, self.data.ptr)
self.assertEqual(last_called[0], outer_called)
with core.callback_context("mjcb_passive", inner):
# This should execute `inner` a few times.
mujoco.mj_step(self.model.ptr, self.data.ptr)
self.assertEqual(last_called[0], inner_called)
# When we exit the inner context, the `mjcb_passive` callback should be
# reset to `outer`.
mujoco.mj_step(self.model.ptr, self.data.ptr)
self.assertEqual(last_called[0], outer_called)
# When we exit the outer context, the `mjcb_passive` callback should be
# reset to None, and stepping should not affect `last_called`.
last_called[0] = None
mujoco.mj_step(self.model.ptr, self.data.ptr)
self.assertIsNone(last_called[0])
def testDisableFlags(self):
xml_string = """
<mujoco>
<option gravity="0 0 -9.81"/>
<worldbody>
<geom name="floor" type="plane" pos="0 0 0" size="10 10 0.1"/>
<body name="cube" pos="0 0 0.1">
<geom type="box" size="0.1 0.1 0.1" mass="1"/>
<site name="cube_site" type="box" size="0.1 0.1 0.1"/>
<joint type="slide"/>
</body>
</worldbody>
<sensor>
<touch name="touch_sensor" site="cube_site"/>
</sensor>
</mujoco>
"""
model = core.MjModel.from_xml_string(xml_string)
data = core.MjData(model)
for _ in range(100): # Let the simulation settle for a while.
mujoco.mj_step(model.ptr, data.ptr)
# With gravity and contact enabled, the cube should be stationary and the
# touch sensor should give a reading of ~9.81 N.
self.assertAlmostEqual(data.qvel[0], 0, places=4)
self.assertAlmostEqual(data.sensordata[0], 9.81, places=2)
# If we disable both contacts and gravity then the cube should remain
# stationary and the touch sensor should read zero.
with model.disable("contact", "gravity"):
mujoco.mj_step(model.ptr, data.ptr)
self.assertAlmostEqual(data.qvel[0], 0, places=4)
self.assertEqual(data.sensordata[0], 0)
# If we disable contacts but not gravity then the cube should fall through
# the floor.
with model.disable(mujoco.mjtDisableBit.mjDSBL_CONTACT):
for _ in range(10):
mujoco.mj_step(model.ptr, data.ptr)
self.assertLess(data.qvel[0], -0.1)
def testDisableFlagsExceptions(self):
with self.assertRaises(ValueError):
with self.model.disable("invalid_flag_name"):
pass
with self.assertRaises(ValueError):
with self.model.disable(-99):
pass
@parameterized.parameters(
# The tip is .5 meters from the cart so we expect its horizontal velocity
# to be 1m/s + .5m*1rad/s = 1.5m/s.
dict(
qpos=[0., 0.], # Pole pointing upwards.
qvel=[1., 1.],
expected_linvel=[1.5, 0., 0.],
expected_angvel=[0., 1., 0.],
),
# For the same velocities but with the pole pointing down, we expect the
# velocities to cancel, making the global tip velocity now equal to
# 1m/s - 0.5m*1rad/s = 0.5m/s.
dict(
qpos=[0., np.pi], # Pole pointing downwards.
qvel=[1., 1.],
expected_linvel=[0.5, 0., 0.],
expected_angvel=[0., 1., 0.],
),
# In the site's local frame, which is now flipped w.r.t the world, the
# velocity is in the negative x direction.
dict(
qpos=[0., np.pi], # Pole pointing downwards.
qvel=[1., 1.],
expected_linvel=[-0.5, 0., 0.],
expected_angvel=[0., 1., 0.],
local=True,
),
)
def testObjectVelocity(
self, qpos, qvel, expected_linvel, expected_angvel, local=False):
cartpole = """
<mujoco>
<worldbody>
<body name='cart'>
<joint type='slide' axis='1 0 0'/>
<geom name='cart' type='box' size='0.2 0.2 0.2'/>
<body name='pole'>
<joint name='hinge' type='hinge' axis='0 1 0'/>
<geom name='mass' pos='0 0 .5' size='0.04'/>
</body>
</body>
</worldbody>
</mujoco>
"""
model = core.MjModel.from_xml_string(cartpole)
data = core.MjData(model)
data.qpos[:] = qpos
data.qvel[:] = qvel
mujoco.mj_step1(model.ptr, data.ptr)
linvel, angvel = data.object_velocity("mass", "geom", local_frame=local)
np.testing.assert_array_almost_equal(linvel, expected_linvel)
np.testing.assert_array_almost_equal(angvel, expected_angvel)
def testContactForce(self):
box_on_floor = """
<mujoco>
<worldbody>
<geom name='floor' type='plane' size='1 1 1'/>
<body name='box' pos='0 0 .1'>
<freejoint/>
<geom name='box' type='box' size='.1 .1 .1'/>
</body>
</worldbody>
</mujoco>
"""
model = core.MjModel.from_xml_string(box_on_floor)
data = core.MjData(model)
# Settle for 500 timesteps (1 second):
for _ in range(500):
mujoco.mj_step(model.ptr, data.ptr)
normal_force = 0.
for contact_id in range(data.ncon):
force = data.contact_force(contact_id)
normal_force += force[0, 0]
box_id = 1
box_weight = -model.opt.gravity[2]*model.body_mass[box_id]
self.assertAlmostEqual(normal_force, box_weight)
# Test raising of out-of-range errors:
bad_ids = [-1, data.ncon]
for bad_id in bad_ids:
with self.assertRaisesWithLiteralMatch(
ValueError,
core._CONTACT_ID_OUT_OF_RANGE.format(
max_valid=data.ncon - 1, actual=bad_id)):
data.contact_force(bad_id)
@parameterized.parameters(
dict(
condim=3, # Only sliding friction.
expected_torques=[False, False, False], # No torques.
),
dict(
condim=4, # Sliding and torsional friction.
expected_torques=[True, False, False], # Only torsional torque.
),
dict(
condim=6, # Sliding, torsional and rolling.
expected_torques=[True, True, True], # All torques are nonzero.
),
)
def testContactTorque(self, condim, expected_torques):
ball_on_floor = """
<mujoco>
<worldbody>
<geom name='floor' type='plane' size='1 1 1'/>
<body name='ball' pos='0 0 .1'>
<freejoint/>
<geom name='ball' size='.1' friction='1 .1 .1'/>
</body>
</worldbody>
</mujoco>
"""
model = core.MjModel.from_xml_string(ball_on_floor)
data = core.MjData(model)
model.geom_condim[:] = condim
data.qvel[3:] = np.array((1., 1., 1.))
# Settle for 10 timesteps (20 milliseconds):
for _ in range(10):
mujoco.mj_step(model.ptr, data.ptr)
contact_id = 0 # This model has only one contact.
_, torque = data.contact_force(contact_id)
nonzero_torques = torque != 0
np.testing.assert_array_equal(nonzero_torques, np.array((expected_torques)))
def testFreeMjrContext(self):
for _ in range(5):
renderer = _render.Renderer(640, 480)
mjr_context = core.MjrContext(self.model, renderer)
# Explicit freeing should not break any automatic GC triggered later.
del mjr_context
renderer.free()
del renderer
gc.collect()
def testSceneGeomsAttribute(self):
scene = core.MjvScene(model=self.model)
self.assertEqual(scene.ngeom, 0)
self.assertEmpty(scene.geoms)
geom_types = (
mujoco.mjtObj.mjOBJ_BODY,
mujoco.mjtObj.mjOBJ_GEOM,
mujoco.mjtObj.mjOBJ_SITE,
)
for geom_type in geom_types:
scene.ngeom += 1
scene.geoms[scene.ngeom - 1].objtype = geom_type
self.assertLen(scene.geoms, len(geom_types))
self.assertEqual(tuple(g.objtype for g in scene.geoms), geom_types)
def testInvalidFontScale(self):
invalid_font_scale = 99
with self.assertRaises(ValueError):
core.MjrContext(model=self.model,
gl_context=None, # Don't need a context for this test.
font_scale=invalid_font_scale)
def _get_attributes_test_params():
model = core.MjModel.from_xml_path(HUMANOID_XML_PATH)
data = core.MjData(model)
# Get the names of the non-private attributes of model and data through
# introspection. These are passed as parameters to each of the test methods
# in AttributesTest.
array_args = []
scalar_args = []
skipped_args = []
for parent_name, parent_obj in zip(("model", "data"),
(model._model, data._data)):
for attr_name in dir(parent_obj):
if not attr_name.startswith("_"): # Skip 'private' attributes
args = (parent_name, attr_name)
attr = getattr(parent_obj, attr_name)
if isinstance(attr, ARRAY_TYPES):
array_args.append(args)
elif isinstance(attr, SCALAR_TYPES):
scalar_args.append(args)
elif callable(attr):
# Methods etc. should be covered specifically in CoreTest.
continue
else:
skipped_args.append(args)
return array_args, scalar_args, skipped_args
_array_args, _scalar_args, _skipped_args = _get_attributes_test_params()
class AttributesTest(parameterized.TestCase):
"""Generic tests covering attributes of MjModel and MjData."""
# Iterates over ('parent_name', 'attr_name') tuples
@parameterized.parameters(*_array_args)
def testReadWriteArray(self, parent_name, attr_name):
attr = getattr(getattr(self, parent_name), attr_name)
if not isinstance(attr, ARRAY_TYPES):
raise TypeError("{}.{} has incorrect type {!r} - must be one of {!r}."
.format(parent_name, attr_name, type(attr), ARRAY_TYPES))
# Check that we can read the contents of the array
_ = attr[:]
# Write unique values into the array and read them back.
self._write_unique_values(attr_name, attr)
self._take_steps() # Take a few steps, check that we don't get segfaults.
def _write_unique_values(self, attr_name, target_array):
# If the target array is structured, recursively write unique values into
# each subfield.
if target_array.dtype.fields is not None:
for field_name in target_array.dtype.fields:
self._write_unique_values(attr_name, target_array[field_name])
# Don't write to integer arrays since these might contain pointers. Also
# don't write directly into the stack.
elif (attr_name != "stack"
and not np.issubdtype(target_array.dtype, np.integer)):
new_contents = np.arange(target_array.size, dtype=target_array.dtype)
new_contents.shape = target_array.shape
target_array[:] = new_contents
np.testing.assert_array_equal(new_contents, target_array[:])
@parameterized.parameters(*_scalar_args)
def testReadWriteScalar(self, parent_name, attr_name):
parent_obj = getattr(self, parent_name)
# Check that we can read the value.
attr = getattr(parent_obj, attr_name)
if not isinstance(attr, SCALAR_TYPES):
raise TypeError("{}.{} has incorrect type {!r} - must be one of {!r}."
.format(parent_name, attr_name, type(attr), SCALAR_TYPES))
# Don't write to integers since these might be pointers.
if not isinstance(attr, int):
# Set the value of this attribute, check that we can read it back.
new_value = type(attr)(99)
setattr(parent_obj, attr_name, new_value)
self.assertEqual(new_value, getattr(parent_obj, attr_name))
self._take_steps() # Take a few steps, check that we don't get segfaults.
@parameterized.parameters(*_skipped_args)
@absltest.unittest.skip("No tests defined for attributes of this type.")
def testSkipped(self, *unused_args):
# This is a do-nothing test that indicates where we currently lack coverage.
pass
def setUp(self):
super().setUp()
self.model = core.MjModel.from_xml_path(HUMANOID_XML_PATH)
self.data = core.MjData(self.model)
def _take_steps(self, n=5):
for _ in range(n):
mujoco.mj_step(self.model.ptr, self.data.ptr)
if __name__ == "__main__":
absltest.main()
| dm_control-main | dm_control/mujoco/wrapper/core_test.py |
# Copyright 2022 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Aliases for the mujoco library, provided for backwards compatibility.
New code should import mujoco directly, instead of accessing these constants or
mjlib through this module.
"""
import mujoco
mjlib = mujoco
mjDISABLESTRING = mujoco.mjDISABLESTRING
mjENABLESTRING = mujoco.mjENABLESTRING
mjTIMERSTRING = mujoco.mjTIMERSTRING
mjLABELSTRING = mujoco.mjLABELSTRING
mjFRAMESTRING = mujoco.mjFRAMESTRING
mjVISSTRING = mujoco.mjVISSTRING
mjRNDSTRING = mujoco.mjRNDSTRING
| dm_control-main | dm_control/mujoco/wrapper/mjbindings/functions.py |
# Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Import core names of MuJoCo ctypes bindings."""
from absl import logging
from dm_control.mujoco.wrapper.mjbindings import constants
from dm_control.mujoco.wrapper.mjbindings import enums
from dm_control.mujoco.wrapper.mjbindings import sizes
# Internal analytics import.
# pylint: disable=g-import-not-at-top
try:
from dm_control.mujoco.wrapper.mjbindings import functions
from dm_control.mujoco.wrapper.mjbindings.functions import mjlib
logging.info('MuJoCo library version is: %s', mjlib.mj_versionString())
# Internal analytics.
except (IOError, OSError):
logging.warning('mjbindings failed to import mjlib and other functions. '
'libmujoco.so may not be accessible.')
| dm_control-main | dm_control/mujoco/wrapper/mjbindings/__init__.py |
# Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for image_utils."""
import os
from absl.testing import absltest
from absl.testing import parameterized
from dm_control.mujoco.testing import image_utils
import mock
import numpy as np
from PIL import Image
SEED = 0
class ImageUtilsTest(parameterized.TestCase):
@parameterized.parameters(
dict(frame_index1=0, frame_index2=0, expected_rms=0.0),
dict(frame_index1=0, frame_index2=1, expected_rms=23.214),
dict(frame_index1=0, frame_index2=9, expected_rms=55.738))
def test_compute_rms(self, frame_index1, frame_index2, expected_rms):
# Force loading of the software rendering reference images regardless of the
# actual GL backend, since these should match the expected RMS values.
with mock.patch.object(image_utils, 'BACKEND_STRING', new='software'):
frames = list(image_utils.humanoid.iter_load())
camera_idx = 0
num_cameras = image_utils.humanoid.num_cameras
image1 = frames[camera_idx + frame_index1 * num_cameras]
image2 = frames[camera_idx + frame_index2 * num_cameras]
rms = image_utils.compute_rms(image1, image2)
self.assertAlmostEqual(rms, expected_rms, places=3)
def test_assert_images_close(self):
random_state = np.random.RandomState(SEED)
image1 = random_state.randint(0, 255, size=(64, 64, 3), dtype=np.uint8)
image2 = random_state.randint(0, 255, size=(64, 64, 3), dtype=np.uint8)
image_utils.assert_images_close(image1, image1, tolerance=0)
with self.assertRaisesRegex( # pylint: disable=g-error-prone-assert-raises
image_utils.ImagesNotCloseError, 'RMS error exceeds tolerance'):
image_utils.assert_images_close(image1, image2)
def test_save_images_on_failure(self):
random_state = np.random.RandomState(SEED)
image1 = random_state.randint(0, 255, size=(64, 64, 3), dtype=np.uint8)
image2 = random_state.randint(0, 255, size=(64, 64, 3), dtype=np.uint8)
diff = (0.5 * (image2.astype(np.int16) - image1 + 255)).astype(np.uint8)
message = 'exception message'
output_dir = absltest.get_default_test_tmpdir()
@image_utils.save_images_on_failure(output_dir=output_dir)
def func():
raise image_utils.ImagesNotCloseError(message, image1, image2)
with self.assertRaisesRegex(image_utils.ImagesNotCloseError,
'{}.*'.format(message)):
func()
def validate_saved_file(name, expected_contents):
path = os.path.join(output_dir, '{}-{}.png'.format('func', name))
self.assertTrue(os.path.isfile(path))
image = Image.open(path)
actual_contents = np.array(image)
np.testing.assert_array_equal(expected_contents, actual_contents)
validate_saved_file('expected', image1)
validate_saved_file('actual', image2)
validate_saved_file('difference', diff)
if __name__ == '__main__':
absltest.main()
| dm_control-main | dm_control/mujoco/testing/image_utils_test.py |
# Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Utilities for testing rendering."""
import collections
import functools
import io
import os
import sys
from dm_control import _render
from dm_control import mujoco
from dm_control.mujoco.testing import assets
import numpy as np
from PIL import Image
BACKEND_STRING = 'hardware' if _render.USING_GPU else 'software'
class ImagesNotCloseError(AssertionError):
"""Exception raised when two images are not sufficiently close."""
def __init__(self, message, expected, actual):
super().__init__(message)
self.expected = expected
self.actual = actual
_CameraSpec = collections.namedtuple(
'_CameraSpec', ['height', 'width', 'camera_id', 'render_flag_overrides'])
_SUBDIR_TEMPLATE = (
'{name}_seed_{seed}_camera_{camera_id}_{width}x{height}_{backend_string}'
'{render_flag_overrides_string}'
)
def _get_subdir(name, seed, backend_string, camera_spec):
if camera_spec.render_flag_overrides:
overrides = ('{}_{}'.format(k, v) for k, v in
sorted(camera_spec.render_flag_overrides.items()))
render_flag_overrides_string = '_' + '_'.join(overrides)
else:
render_flag_overrides_string = ''
return _SUBDIR_TEMPLATE.format(
name=name,
seed=seed,
camera_id=camera_spec.camera_id,
width=camera_spec.width,
height=camera_spec.height,
backend_string=backend_string,
render_flag_overrides_string=render_flag_overrides_string,
)
class _FrameSequence:
"""A sequence of pre-rendered frames used in integration tests."""
_ASSETS_DIR = 'assets'
_FRAMES_DIR = 'frames'
_FILENAME_TEMPLATE = 'frame_{frame_num:03}.png'
def __init__(self,
name,
xml_string,
camera_specs,
num_frames=20,
steps_per_frame=10,
seed=0):
"""Initializes a new `_FrameSequence`.
Args:
name: A string containing the name to be used for the sequence.
xml_string: An MJCF XML string containing the model to be rendered.
camera_specs: A list of `_CameraSpec` instances specifying the cameras to
render on each frame.
num_frames: The number of frames to render.
steps_per_frame: The interval between frames, in simulation steps.
seed: Integer or None, used to initialize the random number generator for
generating actions.
"""
self._name = name
self._xml_string = xml_string
self._camera_specs = camera_specs
self._num_frames = num_frames
self._steps_per_frame = steps_per_frame
self._seed = seed
@property
def num_cameras(self):
return len(self._camera_specs)
def iter_render(self):
"""Returns an iterator that yields newly rendered frames as numpy arrays."""
random_state = np.random.RandomState(self._seed)
physics = mujoco.Physics.from_xml_string(self._xml_string)
action_spec = mujoco.action_spec(physics)
for _ in range(self._num_frames):
for _ in range(self._steps_per_frame):
actions = random_state.uniform(action_spec.minimum, action_spec.maximum)
physics.set_control(actions)
physics.step()
for camera_spec in self._camera_specs:
yield physics.render(**camera_spec._asdict())
def iter_load(self):
"""Returns an iterator that yields saved frames as numpy arrays."""
for directory, filename in self._iter_paths():
path = os.path.join(directory, filename)
yield _load_pixels(path)
def save(self):
"""Saves a new set of golden output frames to disk."""
for pixels, (relative_to_assets, filename) in zip(self.iter_render(),
self._iter_paths()):
full_directory_path = os.path.join(self._ASSETS_DIR, relative_to_assets)
if not os.path.exists(full_directory_path):
os.makedirs(full_directory_path)
path = os.path.join(full_directory_path, filename)
_save_pixels(pixels, path)
def _iter_paths(self):
"""Returns an iterator over paths to the reference images."""
for frame_num in range(self._num_frames):
filename = self._FILENAME_TEMPLATE.format(frame_num=frame_num)
for camera_spec in self._camera_specs:
subdir_name = _get_subdir(
name=self._name,
seed=self._seed,
backend_string=BACKEND_STRING,
camera_spec=camera_spec)
directory = os.path.join(self._FRAMES_DIR, subdir_name)
yield directory, filename
cartpole = _FrameSequence(
name='cartpole',
xml_string=assets.get_contents('cartpole.xml'),
camera_specs=(
_CameraSpec(
width=320, height=240, camera_id=0, render_flag_overrides={}),
),
steps_per_frame=5)
humanoid = _FrameSequence(
name='humanoid',
xml_string=assets.get_contents('humanoid.xml'),
camera_specs=(
_CameraSpec(
width=240, height=320, camera_id=0, render_flag_overrides={}),
_CameraSpec(
width=240,
height=320,
camera_id=0,
render_flag_overrides={
'shadow': False,
'reflection': False,
}),
_CameraSpec(
width=64,
height=64,
camera_id='head_track',
render_flag_overrides={}),
))
SEQUENCES = {
'cartpole': cartpole,
'humanoid': humanoid,
}
def _save_pixels(pixels, path):
image = Image.fromarray(pixels)
image.save(path)
def _load_pixels(path):
image_bytes = assets.get_contents(path)
image = Image.open(io.BytesIO(image_bytes))
return np.array(image)
def compute_rms(image1, image2):
"""Computes the RMS difference between two images."""
abs_diff = np.abs(image1.astype(np.int16) - image2)
values, counts = np.unique(abs_diff, return_counts=True)
sum_of_squares = np.sum(counts * values.astype(np.int64) ** 2)
return np.sqrt(float(sum_of_squares) / abs_diff.size)
def assert_images_close(expected, actual, tolerance=10.):
"""Tests whether two images are almost equal.
Args:
expected: A numpy array, the expected image.
actual: A numpy array, the actual image.
tolerance: A float specifying the maximum allowable RMS error between the
expected and actual images.
Raises:
ImagesNotCloseError: If the images are not sufficiently close.
"""
rms = compute_rms(expected, actual)
if rms > tolerance:
message = 'RMS error exceeds tolerance ({} > {})'.format(rms, tolerance)
raise ImagesNotCloseError(message, expected=expected, actual=actual)
def save_images_on_failure(output_dir):
"""Decorator that saves debugging images if `ImagesNotCloseError` is raised.
Args:
output_dir: Path to the directory where the output images will be saved.
Returns:
A decorator function.
"""
def decorator(test_method):
"""Decorator, saves debugging images if `ImagesNotCloseError` is raised."""
method_name = test_method.__name__
@functools.wraps(test_method)
def decorated_method(*args, **kwargs):
"""Call test method, save images if `ImagesNotCloseError` is raised."""
try:
test_method(*args, **kwargs)
except ImagesNotCloseError as e:
_, _, tb = sys.exc_info()
if not os.path.exists(output_dir):
os.makedirs(output_dir)
difference = e.actual.astype(np.double) - e.expected
difference = (0.5 * (difference + 255)).astype(np.uint8)
base_name = os.path.join(output_dir, method_name)
_save_pixels(e.expected, base_name + '-expected.png')
_save_pixels(e.actual, base_name + '-actual.png')
_save_pixels(difference, base_name + '-difference.png')
msg = ('{}. Debugging images saved to '
'{}-{{expected,actual,difference}}.png.'.format(e, base_name))
new_e = ImagesNotCloseError(msg, expected=e.expected, actual=e.actual)
# Reraise the exception with the original traceback.
raise new_e.with_traceback(tb)
return decorated_method
return decorator
| dm_control-main | dm_control/mujoco/testing/image_utils.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.