python_code
stringlengths
0
780k
repo_name
stringlengths
7
38
file_path
stringlengths
5
103
# 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. # ============================================================================ """Utility functions that operate on MJCF elements.""" _ACTUATOR_TAGS = ('general', 'motor', 'position', 'velocity', 'cylinder', 'muscle') def get_freejoint(element): """Retrieves the free joint of a body. Returns `None` if there isn't one.""" if element.tag != 'body': return None elif hasattr(element, 'freejoint') and element.freejoint is not None: return element.freejoint else: joints = element.find_all('joint', immediate_children_only=True) for joint in joints: if joint.type == 'free': return joint return None def get_attachment_frame(mjcf_model): return mjcf_model.parent_model.find('attachment_frame', mjcf_model.model) def get_frame_freejoint(mjcf_model): frame = get_attachment_frame(mjcf_model) return get_freejoint(frame) def get_frame_joints(mjcf_model): """Retrieves all joints belonging to the attachment frame of an MJCF model.""" frame = get_attachment_frame(mjcf_model) if frame: return frame.find_all('joint', immediate_children_only=True) else: return None def commit_defaults(element, attributes=None): """Commits default values into attributes of the specified element. Args: element: A PyMJCF element. attributes: (optional) A list of strings specifying the attributes to be copied from defaults, or `None` if all attributes should be copied. """ dclass = element.dclass parent = element.parent while dclass is None and parent != element.root: dclass = getattr(parent, 'childclass', None) parent = parent.parent if dclass is None: dclass = element.root.default while dclass != element.root: if element.tag in _ACTUATOR_TAGS: tags = _ACTUATOR_TAGS else: tags = (element.tag,) for tag in tags: default_element = getattr(dclass, tag) for name, value in default_element.get_attributes().items(): if attributes is None or name in attributes: if hasattr(element, name) and getattr(element, name) is None: setattr(element, name, value) dclass = dclass.parent
dm_control-main
dm_control/mjcf/traversal_utils.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 `dm_control.mjcf.export_with_assets`.""" import os import zipfile from absl import flags from absl.testing import absltest from absl.testing import parameterized from dm_control import mjcf from dm_control.mujoco.wrapper import util FLAGS = flags.FLAGS _ASSETS_DIR = os.path.join(os.path.dirname(__file__), 'test_assets') _TEST_MODEL_WITH_ASSETS = os.path.join(_ASSETS_DIR, 'model_with_assets.xml') _TEST_MODEL_WITHOUT_ASSETS = os.path.join(_ASSETS_DIR, 'lego_brick.xml') def setUpModule(): # Flags are not parsed when this test is invoked by `nosetests`, so we fall # back on using the default value for `--test_tmpdir`. if not FLAGS.is_parsed(): FLAGS.test_tmpdir = absltest.get_default_test_tmpdir() FLAGS.mark_as_parsed() class ExportWithAssetsAsZipTest(parameterized.TestCase): @parameterized.named_parameters( ('with_assets', _TEST_MODEL_WITH_ASSETS, 'mujoco_with_assets'), ('without_assets', _TEST_MODEL_WITHOUT_ASSETS, 'mujoco'), ) def test_export_model(self, xml_path, model_name): """Save processed MJCF model.""" out_dir = self.create_tempdir().full_path mjcf_model = mjcf.from_path(xml_path) mjcf.export_with_assets_as_zip( mjcf_model, out_dir=out_dir, model_name=model_name) # Read the .zip file in the output directory. # Check that the only directory is named `model_name`/, and put all the # contents under any directory in a dict a directory in a dict. zip_file_contents = {} zip_filename = os.path.join(out_dir, (model_name + '.zip')) self.assertTrue(zipfile.is_zipfile(zip_filename)) with zipfile.ZipFile(zip_filename, 'r') as zip_file: for zip_info in zip_file.infolist(): # Note: zip_info.is_dir() is not Python 2 compatible, but directories # inside a ZipFile are guaranteed to end with '/'. if not zip_info.filename.endswith(os.path.sep): with zip_file.open(zip_info.filename) as f: zip_file_contents[zip_info.filename] = f.read() else: self.assertEqual(os.path.join(model_name), zip_info.filename) # Check that the output directory contains an XML file of the correct name. xml_filename = os.path.join(model_name, model_name) + '.xml' self.assertIn(xml_filename, zip_file_contents) # Check that its contents match the output of `mjcf_model.to_xml_string()`. xml_contents = util.to_native_string(zip_file_contents.pop(xml_filename)) expected_xml_contents = mjcf_model.to_xml_string() self.assertEqual(xml_contents, expected_xml_contents) # Check that the other files in the directory match the contents of the # model's `assets` dict. assets = mjcf_model.get_assets() for asset_name, asset_contents in assets.items(): self.assertEqual(asset_contents, zip_file_contents[os.path.join(model_name, asset_name)]) def test_default_model_filename(self): out_dir = self.create_tempdir().full_path mjcf_model = mjcf.from_path(_TEST_MODEL_WITH_ASSETS) mjcf.export_with_assets_as_zip(mjcf_model, out_dir, model_name=None) expected_name = mjcf_model.model + '.zip' self.assertTrue(os.path.isfile(os.path.join(out_dir, expected_name))) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/mjcf/export_with_assets_as_zip_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 `dm_control.mjcf.copier`.""" import os from absl.testing import absltest from dm_control import mjcf from dm_control.mjcf import parser import numpy as np _ASSETS_DIR = os.path.join(os.path.dirname(__file__), 'test_assets') _TEST_MODEL_XML = os.path.join(_ASSETS_DIR, 'test_model.xml') _MODEL_WITH_ASSETS_XML = os.path.join(_ASSETS_DIR, 'model_with_assets.xml') class CopierTest(absltest.TestCase): def testSimpleCopy(self): mjcf_model = parser.from_path(_TEST_MODEL_XML) mixin = mjcf.RootElement(model='test_mixin') mixin.compiler.boundmass = 1 mjcf_model.include_copy(mixin) self.assertEqual(mjcf_model.model, 'test') # Model name should not change self.assertEqual(mjcf_model.compiler.boundmass, mixin.compiler.boundmass) mixin.compiler.boundinertia = 2 mjcf_model.include_copy(mixin) self.assertEqual(mjcf_model.compiler.boundinertia, mixin.compiler.boundinertia) mixin.compiler.boundinertia = 1 with self.assertRaisesRegex(ValueError, 'Conflicting values'): mjcf_model.include_copy(mixin) mixin.worldbody.add('body', name='b_0', pos=[0, 1, 2]) mjcf_model.include_copy(mixin, override_attributes=True) self.assertEqual(mjcf_model.compiler.boundmass, mixin.compiler.boundmass) self.assertEqual(mjcf_model.compiler.boundinertia, mixin.compiler.boundinertia) np.testing.assert_array_equal(mjcf_model.worldbody.body['b_0'].pos, [0, 1, 2]) def testCopyingWithReference(self): sensor_mixin = mjcf.RootElement('sensor_mixin') touch_site = sensor_mixin.worldbody.add('site', name='touch_site') sensor_mixin.sensor.add('touch', name='touch_sensor', site=touch_site) mjcf_model = mjcf.RootElement('model') mjcf_model.include_copy(sensor_mixin) # Copied reference should be updated to the copied site. self.assertIs(mjcf_model.find('sensor', 'touch_sensor').site, mjcf_model.find('site', 'touch_site')) def testCopyingWithAssets(self): mjcf_model = parser.from_path(_MODEL_WITH_ASSETS_XML) copied = mjcf.RootElement() copied.include_copy(mjcf_model) original_assets = (mjcf_model.find_all('mesh') + mjcf_model.find_all('texture') + mjcf_model.find_all('hfield')) copied_assets = (copied.find_all('mesh') + copied.find_all('texture') + copied.find_all('hfield')) self.assertLen(copied_assets, len(original_assets)) for original_asset, copied_asset in zip(original_assets, copied_assets): self.assertIs(copied_asset.file, original_asset.file) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/mjcf/copier_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 `dm_control.mjcf.traversal_utils`.""" from absl.testing import absltest from dm_control import mjcf import numpy as np class TraversalUtilsTest(absltest.TestCase): def assert_same_attributes(self, element, expected_attributes): actual_attributes = element.get_attributes() self.assertEqual(set(actual_attributes.keys()), set(expected_attributes.keys())) for name in actual_attributes: actual_value = actual_attributes[name] expected_value = expected_attributes[name] np.testing.assert_array_equal(actual_value, expected_value, name) def test_resolve_root_defaults(self): root = mjcf.RootElement() root.default.geom.type = 'box' root.default.geom.pos = [0, 1, 0] root.default.joint.ref = 2 root.default.joint.pos = [0, 0, 1] # Own attribute overriding default. body = root.worldbody.add('body') geom1 = body.add('geom', type='sphere') mjcf.commit_defaults(geom1) self.assert_same_attributes(geom1, dict( type='sphere', pos=[0, 1, 0])) # No explicit attributes. geom2 = body.add('geom') mjcf.commit_defaults(geom2) self.assert_same_attributes(geom2, dict( type='box', pos=[0, 1, 0])) # Attributes mutually exclusive with those defined in default. joint1 = body.add('joint', margin=3) mjcf.commit_defaults(joint1) self.assert_same_attributes(joint1, dict( pos=[0, 0, 1], ref=2, margin=3)) def test_resolve_defaults_for_some_attributes(self): root = mjcf.RootElement() root.default.geom.type = 'box' root.default.geom.pos = [0, 1, 0] geom1 = root.worldbody.add('geom') mjcf.commit_defaults(geom1, attributes=['pos']) self.assert_same_attributes(geom1, dict( pos=[0, 1, 0])) def test_resolve_hierarchies_of_defaults(self): root = mjcf.RootElement() root.default.geom.type = 'box' root.default.joint.pos = [0, 1, 0] top1 = root.default.add('default', dclass='top1') top1.geom.pos = [0.1, 0, 0] top1.joint.pos = [1, 0, 0] top1.joint.axis = [0, 0, 1] sub1 = top1.add('default', dclass='sub1') sub1.geom.size = [0.5] top2 = root.default.add('default', dclass='top2') top2.joint.pos = [0, 0, 1] top2.joint.axis = [0, 1, 0] top2.geom.type = 'sphere' body = root.worldbody.add('body') geom1 = body.add('geom', dclass=sub1) mjcf.commit_defaults(geom1) self.assert_same_attributes(geom1, dict( dclass=sub1, type='box', size=[0.5], pos=[0.1, 0, 0])) geom2 = body.add('geom', dclass=top1) mjcf.commit_defaults(geom2) self.assert_same_attributes(geom2, dict( dclass=top1, type='box', pos=[0.1, 0, 0])) geom3 = body.add('geom', dclass=top2) mjcf.commit_defaults(geom3) self.assert_same_attributes(geom3, dict( dclass=top2, type='sphere')) geom4 = body.add('geom') mjcf.commit_defaults(geom4) self.assert_same_attributes(geom4, dict( type='box')) joint1 = body.add('joint', dclass=sub1) mjcf.commit_defaults(joint1) self.assert_same_attributes(joint1, dict( dclass=sub1, pos=[1, 0, 0], axis=[0, 0, 1])) joint2 = body.add('joint', dclass=top2) mjcf.commit_defaults(joint2) self.assert_same_attributes(joint2, dict( dclass=top2, pos=[0, 0, 1], axis=[0, 1, 0])) joint3 = body.add('joint') mjcf.commit_defaults(joint3) self.assert_same_attributes(joint3, dict( pos=[0, 1, 0])) def test_resolve_actuator_defaults(self): root = mjcf.RootElement() root.default.general.forcelimited = 'true' root.default.motor.forcerange = [-2, 3] root.default.position.kp = 0.1 root.default.velocity.kv = 0.2 body = root.worldbody.add('body') joint = body.add('joint') motor = root.actuator.add('motor', joint=joint) mjcf.commit_defaults(motor) self.assert_same_attributes(motor, dict( joint=joint, forcelimited='true', forcerange=[-2, 3])) position = root.actuator.add('position', joint=joint) mjcf.commit_defaults(position) self.assert_same_attributes(position, dict( joint=joint, kp=0.1, forcelimited='true', forcerange=[-2, 3])) velocity = root.actuator.add('velocity', joint=joint) mjcf.commit_defaults(velocity) self.assert_same_attributes(velocity, dict( joint=joint, kv=0.2, forcelimited='true', forcerange=[-2, 3])) def test_resolve_childclass(self): root = mjcf.RootElement() root.default.geom.type = 'capsule' top = root.default.add('default', dclass='top') top.geom.pos = [0, 1, 0] sub = top.add('default', dclass='sub') sub.geom.pos = [0, 0, 1] # Element only affected by the childclass of immediate parent. body = root.worldbody.add('body', childclass=sub) geom1 = body.add('geom') mjcf.commit_defaults(geom1) self.assert_same_attributes(geom1, dict( type='capsule', pos=[0, 0, 1])) # Element overrides parent's childclass. geom2 = body.add('geom', dclass=top) mjcf.commit_defaults(geom2) self.assert_same_attributes(geom2, dict( dclass=top, type='capsule', pos=[0, 1, 0])) # Element's parent overrides grandparent's childclass. subbody1 = body.add('body', childclass=top) geom3 = subbody1.add('geom') mjcf.commit_defaults(geom3) self.assert_same_attributes(geom3, dict( type='capsule', pos=[0, 1, 0])) # Element's grandparent does not specify a childclass, but grandparent does. subbody2 = body.add('body') geom4 = subbody2.add('geom') mjcf.commit_defaults(geom4) self.assert_same_attributes(geom4, dict( type='capsule', pos=[0, 0, 1])) # Direct child of worldbody, not affected by any childclass. geom5 = root.worldbody.add('geom') mjcf.commit_defaults(geom5) self.assert_same_attributes(geom5, dict( type='capsule')) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/mjcf/traversal_utils_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 various MJCF attribute data types.""" import abc import collections import hashlib import io import os from dm_control.mjcf import base from dm_control.mjcf import constants from dm_control.mjcf import debugging from dm_control.mjcf import skin from dm_control.mujoco.wrapper import util import numpy as np # Copybara placeholder for internal file handling dependency. from dm_control.utils import io as resources _INVALID_REFERENCE_TYPE = ( 'Reference should be an MJCF Element whose type is {valid_type!r}: ' 'got {actual_type!r}.') _MESH_EXTENSIONS = ('.stl', '.msh', '.obj') # MuJoCo's compiler enforces this. _INVALID_MESH_EXTENSION = ( 'Mesh files must have one of the following extensions: {}, got {{}}.' .format(_MESH_EXTENSIONS)) class _Attribute(metaclass=abc.ABCMeta): """Abstract base class for MJCF attribute data types.""" def __init__(self, name, required, parent, value, conflict_allowed, conflict_behavior): self._name = name self._required = required self._parent = parent self._value = None self._conflict_allowed = conflict_allowed self._conflict_behavior = conflict_behavior self._check_and_assign(value) def _check_and_assign(self, new_value): if new_value is None: self.clear() elif isinstance(new_value, str): self._assign_from_string(new_value) else: self._assign(new_value) if debugging.debug_mode(): self._last_modified_stack = debugging.get_current_stack_trace() @property def last_modified_stack(self): if debugging.debug_mode(): return self._last_modified_stack @property def value(self): return self._value @value.setter def value(self, new_value): self._check_and_assign(new_value) @abc.abstractmethod def _assign(self, value): raise NotImplementedError # pragma: no cover def clear(self): if self._required: raise AttributeError( 'Attribute {!r} of element <{}> is required' .format(self._name, self._parent.tag)) else: self._force_clear() def _force_clear(self): self._before_clear() self._value = None if debugging.debug_mode(): self._last_modified_stack = debugging.get_current_stack_trace() def _before_clear(self): pass def _assign_from_string(self, string): self._assign(string) def to_xml_string(self, prefix_root, **kwargs): # pylint: disable=unused-argument if self._value is None: return None else: return str(self._value) @property def conflict_allowed(self): return self._conflict_allowed @property def conflict_behavior(self): return self._conflict_behavior class String(_Attribute): """A string MJCF attribute.""" def _assign(self, value): if not isinstance(value, str): raise ValueError('Expect a string value: got {}'.format(value)) elif not value: self.clear() else: self._value = value class Integer(_Attribute): """An integer MJCF attribute.""" def _assign(self, value): try: float_value = float(value) int_value = int(float(value)) if float_value != int_value: raise ValueError except ValueError: raise ValueError( 'Expect an integer value: got {}'.format(value)) from None self._value = int_value class Float(_Attribute): """An float MJCF attribute.""" def _assign(self, value): try: float_value = float(value) except ValueError: raise ValueError('Expect a float value: got {}'.format(value)) from None self._value = float_value def to_xml_string(self, prefix_root=None, *, precision=constants.XML_DEFAULT_PRECISION, zero_threshold=0, **kwargs): if self._value is None: return None else: out = io.BytesIO() value = self._value if abs(value) < zero_threshold: value = 0.0 np.savetxt(out, [value], fmt=f'%.{precision:d}g', newline=' ') return util.to_native_string(out.getvalue())[:-1] # Strip trailing space. class Keyword(_Attribute): """A keyword MJCF attribute.""" def __init__(self, name, required, parent, value, conflict_allowed, conflict_behavior, valid_values): self._valid_values = collections.OrderedDict( (value.lower(), value) for value in valid_values) super().__init__(name, required, parent, value, conflict_allowed, conflict_behavior) def _assign(self, value): if value is None or value == '': # pylint: disable=g-explicit-bool-comparison self.clear() else: try: self._value = self._valid_values[str(value).lower()] except KeyError: raise ValueError('Expect keyword to be one of {} but got: {}'.format( list(self._valid_values.values()), value)) from None @property def valid_values(self): return list(self._valid_values.keys()) class Array(_Attribute): """An array MJCF attribute.""" def __init__(self, name, required, parent, value, conflict_allowed, conflict_behavior, length, dtype): self._length = length self._dtype = dtype super().__init__(name, required, parent, value, conflict_allowed, conflict_behavior) def _assign(self, value): self._value = self._check_shape(np.array(value, dtype=self._dtype)) def _assign_from_string(self, string): self._assign(np.fromstring(string, dtype=self._dtype, sep=' ')) def to_xml_string(self, prefix_root=None, *, precision=constants.XML_DEFAULT_PRECISION, zero_threshold=0, **kwargs): if self._value is None: return None else: out = io.BytesIO() value = self._value if zero_threshold: value = np.copy(value) value[np.abs(value) < zero_threshold] = 0 np.savetxt(out, value, fmt=f'%.{precision:d}g', newline=' ') return util.to_native_string(out.getvalue())[:-1] # Strip trailing space. def _check_shape(self, array): actual_length = array.shape[0] if len(array.shape) > 1: raise ValueError('Expect one-dimensional array: got {}'.format(array)) if self._length and actual_length > self._length: raise ValueError('Expect array with no more than {} entries: got {}' .format(self._length, array)) return array class Identifier(_Attribute): """A string attribute that represents a unique identifier of an element.""" def _assign(self, value): if not isinstance(value, str): raise ValueError('Expect a string value: got {}'.format(value)) elif not value: self.clear() elif self._parent.spec.namespace == 'body' and value == 'world': raise ValueError('A body cannot be named \'world\'. ' 'The name \'world\' is used by MuJoCo to refer to the ' '<worldbody>.') elif constants.PREFIX_SEPARATOR in value: raise ValueError( 'An identifier cannot contain a {!r}, ' 'as this is reserved for scoping purposes: got {!r}' .format(constants.PREFIX_SEPARATOR, value)) else: old_value = self._value if value != old_value: self._parent.namescope.add( self._parent.spec.namespace, value, self._parent) if old_value: self._parent.namescope.remove(self._parent.spec.namespace, old_value) self._value = value def _before_clear(self): if self._value: self._parent.namescope.remove(self._parent.spec.namespace, self._value) def _defaults_string(self, prefix_root): prefix = self._parent.namescope.full_prefix(prefix_root, as_list=True) prefix.append(self._value or '') return constants.PREFIX_SEPARATOR.join(prefix) or constants.PREFIX_SEPARATOR def to_xml_string(self, prefix_root=None, **kwargs): if self._parent.tag == constants.DEFAULT: return self._defaults_string(prefix_root) elif self._value: prefix = self._parent.namescope.full_prefix(prefix_root, as_list=True) prefix.append(self._value) return constants.PREFIX_SEPARATOR.join(prefix) else: return self._value class Reference(_Attribute): """A string attribute that represents a reference to an identifier.""" def __init__(self, name, required, parent, value, conflict_allowed, conflict_behavior, reference_namespace): self._reference_namespace = reference_namespace super().__init__(name, required, parent, value, conflict_allowed, conflict_behavior) def _check_dead_reference(self): if isinstance(self._value, base.Element) and self._value.is_removed: self.clear() @property def value(self): self._check_dead_reference() return super().value @value.setter def value(self, new_value): super(Reference, self.__class__).value.fset(self, new_value) @property def reference_namespace(self): if isinstance(self._reference_namespace, _Attribute): return constants.INDIRECT_REFERENCE_ATTRIB.get( self._reference_namespace.value, self._reference_namespace.value) else: return self._reference_namespace def _assign(self, value): if not isinstance(value, (base.Element, str)): raise ValueError( 'Expect a string or `mjcf.Element` value: got {}'.format(value)) elif not value: self.clear() else: if isinstance(value, base.Element): value_namespace = ( value.spec.namespace.split(constants.NAMESPACE_SEPARATOR)[0]) if value_namespace != self.reference_namespace: raise ValueError(_INVALID_REFERENCE_TYPE.format( valid_type=self.reference_namespace, actual_type=value_namespace)) self._value = value def _before_clear(self): if isinstance(self._value, base.Element): if isinstance(self._reference_namespace, _Attribute): self._reference_namespace._force_clear() # pylint: disable=protected-access def _defaults_string(self, prefix_root): """Generates the XML string if this is a reference to a defaults class. To prevent global defaults from clashing, we turn all global defaults into a properly named defaults class. Therefore, care must be taken when this attribute is not explicitly defined. If the parent element can be traced up to a body with a nontrivial 'childclass' then must continue to leave this attribute undefined. Args: prefix_root: A `NameScope` object to be treated as root for the purpose of calculating the prefix. Returns: A string to be used in the generated XML. """ self._check_dead_reference() prefix = self._parent.namescope.full_prefix(prefix_root) if not self._value: defaults_root = self._parent.parent while defaults_root is not None: if (hasattr(defaults_root, constants.CHILDCLASS) and defaults_root.childclass): break defaults_root = defaults_root.parent if defaults_root is None: # This element doesn't belong to a childclass'd body. global_class = self._parent.root.default.dclass or '' out_string = (prefix + global_class) or constants.PREFIX_SEPARATOR else: out_string = None else: out_string = prefix + self._value return out_string def to_xml_string(self, prefix_root, **kwargs): self._check_dead_reference() if isinstance(self._value, base.Element): return self._value.prefixed_identifier(prefix_root) elif (self.reference_namespace == constants.DEFAULT and self._name != constants.CHILDCLASS): return self._defaults_string(prefix_root) elif self._value: return self._parent.namescope.full_prefix(prefix_root) + self._value else: return None class BasePath(_Attribute): """A string attribute that represents a base path for an asset type.""" def __init__(self, name, required, parent, value, conflict_allowed, conflict_behavior, path_namespace): self._path_namespace = path_namespace super().__init__(name, required, parent, value, conflict_allowed, conflict_behavior) def _assign(self, value): if not isinstance(value, str): raise ValueError('Expect a string value: got {}'.format(value)) elif not value: self.clear() else: self._parent.namescope.replace( constants.BASEPATH, self._path_namespace, value) self._value = value def _before_clear(self): if self._value: self._parent.namescope.remove(constants.BASEPATH, self._path_namespace) def to_xml_string(self, prefix_root=None, **kwargs): return None class BaseAsset: """Base class for binary assets.""" __slots__ = ('extension', 'prefix') def __init__(self, extension, prefix=''): self.extension = extension self.prefix = prefix def __eq__(self, other): return self.get_vfs_filename() == other.get_vfs_filename() def get_vfs_filename(self): """Returns the name of the asset file as registered in MuJoCo's VFS.""" # Hash the contents of the asset to get a unique identifier. hash_string = hashlib.sha1(util.to_binary_string(self.contents)).hexdigest() # Prepend the prefix, if one exists. if self.prefix: prefix = self.prefix raw_length = len(prefix) + len(hash_string) + len(self.extension) + 1 if raw_length > constants.MAX_VFS_FILENAME_LENGTH: trim_amount = raw_length - constants.MAX_VFS_FILENAME_LENGTH prefix = prefix[:-trim_amount] filename = '-'.join([prefix, hash_string]) else: filename = hash_string # An extension is needed because MuJoCo's compiler looks at this when # deciding how to load meshes and heightfields. return filename + self.extension class Asset(BaseAsset): """Class representing a binary asset.""" __slots__ = ('contents',) def __init__(self, contents, extension, prefix=''): """Initializes a new `Asset`. Args: contents: The contents of the file as a bytestring. extension: A string specifying the file extension (e.g. '.png', '.stl'). prefix: (optional) A prefix applied to the filename given in MuJoCo's VFS. """ self.contents = contents super().__init__(extension, prefix) class SkinAsset(BaseAsset): """Class representing a binary asset corresponding to a skin.""" __slots__ = ('skin', 'parent', '_cached_revision', '_cached_contents') def __init__(self, contents, parent, extension, prefix=''): self.skin = skin.parse( contents, lambda body_name: parent.root.find('body', body_name)) self.parent = parent self._cached_revision = -1 self._cached_contents = None super().__init__(extension, prefix) @property def contents(self): if self._cached_revision < self.parent.namescope.revision: self._cached_contents = skin.serialize(self.skin) self._cached_revision = self.parent.namescope.revision return self._cached_contents class File(_Attribute): """Attribute representing an asset file.""" def __init__(self, name, required, parent, value, conflict_allowed, conflict_behavior, path_namespace): self._path_namespace = path_namespace super().__init__(name, required, parent, value, conflict_allowed, conflict_behavior) parent.namescope.files.add(self) def _assign(self, value): if not value: self.clear() else: if isinstance(value, str): asset = self._get_asset_from_path(value) elif isinstance(value, Asset): asset = value else: raise ValueError('Expect either a string or `Asset` value: got {}' .format(value)) self._validate_extension(asset.extension) self._value = asset def _get_asset_from_path(self, path): """Constructs a `Asset` given a file path.""" _, basename = os.path.split(path) filename, extension = os.path.splitext(basename) # Look in the dict of pre-loaded assets before checking the filesystem. try: contents = self._parent.namescope.assets[path] except KeyError: # Construct the full path to the asset file, prefixed by the path to the # model directory, and by `meshdir` or `texturedir` if appropriate. path_parts = [] if self._parent.namescope.model_dir: path_parts.append(self._parent.namescope.model_dir) try: base_path = self._parent.namescope.get(constants.BASEPATH, self._path_namespace) path_parts.append(base_path) except KeyError: pass path_parts.append(path) full_path = os.path.join(*path_parts) # pylint: disable=no-value-for-parameter contents = resources.GetResource(full_path) if self._parent.tag == constants.SKIN: return SkinAsset(contents=contents, parent=self._parent, extension=extension, prefix=filename) else: return Asset(contents=contents, extension=extension, prefix=filename) def _validate_extension(self, extension): if self._parent.tag == constants.MESH: if extension.lower() not in _MESH_EXTENSIONS: raise ValueError(_INVALID_MESH_EXTENSION.format(extension)) def get_contents(self): """Returns a bytestring representing the contents of the asset.""" if self._value is None: raise RuntimeError('You must assign a value to this attribute before ' 'querying the contents.') return self._value.contents def to_xml_string(self, prefix_root=None, **kwargs): """Returns the asset filename as it will appear in the generated XML.""" del prefix_root # Unused if self._value is not None: return self._value.get_vfs_filename() else: return None
dm_control-main
dm_control/mjcf/attribute.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. # ============================================================================ """Magic constants used within `dm_control.mjcf`.""" PREFIX_SEPARATOR = '/' PREFIX_SEPARATOR_ESCAPE = '\\' # Used to disambiguate namespaces between attachment frames. NAMESPACE_SEPARATOR = '@' # Magic attribute names BASEPATH = 'basepath' CHILDCLASS = 'childclass' CLASS = 'class' DEFAULT = 'default' DCLASS = 'dclass' # Magic tags ACTUATOR = 'actuator' BODY = 'body' DEFAULT = 'default' MESH = 'mesh' SITE = 'site' SKIN = 'skin' TENDON = 'tendon' WORLDBODY = 'worldbody' MJDATA_TRIGGERS_DIRTY = [ 'qpos', 'qvel', 'act', 'ctrl', 'qfrc_applied', 'xfrc_applied'] MJMODEL_DOESNT_TRIGGER_DIRTY = [ 'rgba', 'matid', 'emission', 'specular', 'shininess', 'reflectance', 'needstage', ] # When writing into `model.{body,geom,site}_{pos,quat}` we must ensure that the # corresponding rows in `model.{body,geom,site}_sameframe` are set to zero, # otherwise MuJoCo will use the body or inertial frame instead of our modified # pos/quat values. We must do the same for `body_{ipos,iquat}` and # `body_simple`. MJMODEL_DISABLE_ON_WRITE = { # Field name in MjModel: (attribute names of Binding instance to be zeroed) 'body_pos': ('sameframe',), 'body_quat': ('sameframe',), 'geom_pos': ('sameframe',), 'geom_quat': ('sameframe',), 'site_pos': ('sameframe',), 'site_quat': ('sameframe',), 'body_ipos': ('simple', 'sameframe'), 'body_iquat': ('simple', 'sameframe'), } # This is the actual upper limit on VFS filename length, despite what it says # in the header file (100) or the error message (99). MAX_VFS_FILENAME_LENGTH = 98 # The prefix used in the schema to denote reference_namespace that are defined # via another attribute. INDIRECT_REFERENCE_NAMESPACE_PREFIX = 'attrib:' INDIRECT_REFERENCE_ATTRIB = { 'xbody': 'body', } # 17 decimal digits is sufficient to represent a double float without loss # of precision. # https://en.wikipedia.org/wiki/IEEE_754#Character_representation XML_DEFAULT_PRECISION = 17
dm_control-main
dm_control/mjcf/constants.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. # ============================================================================ """PyMJCF: an MJCF object-model library.""" from dm_control.mjcf.attribute import Asset from dm_control.mjcf.base import Element from dm_control.mjcf.constants import PREFIX_SEPARATOR from dm_control.mjcf.element import RootElement from dm_control.mjcf.export_with_assets import export_with_assets from dm_control.mjcf.export_with_assets_as_zip import export_with_assets_as_zip from dm_control.mjcf.parser import from_file from dm_control.mjcf.parser import from_path from dm_control.mjcf.parser import from_xml_string from dm_control.mjcf.physics import Physics from dm_control.mjcf.traversal_utils import commit_defaults from dm_control.mjcf.traversal_utils import get_attachment_frame from dm_control.mjcf.traversal_utils import get_frame_freejoint from dm_control.mjcf.traversal_utils import get_frame_joints from dm_control.mjcf.traversal_utils import get_freejoint
dm_control-main
dm_control/mjcf/__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. # ============================================================================ """Implements PyMJCF debug mode. PyMJCF debug mode stores a stack trace each time the MJCF object is modified. If Mujoco raises a compile error on the generated XML model, we would then be able to find the original source line that created the offending element. """ import collections import contextlib import copy import os import re import sys import traceback from absl import flags from lxml import etree FLAGS = flags.FLAGS flags.DEFINE_boolean( 'pymjcf_debug', False, 'Enables PyMJCF debug mode (SLOW!). In this mode, a stack trace is logged ' 'each the MJCF object is modified. This may be helpful in locating the ' 'Python source line corresponding to a problematic element in the ' 'generated XML.') flags.DEFINE_string( 'pymjcf_debug_full_dump_dir', '', 'Path to dump full debug info when Mujoco error is encountered.') StackTraceEntry = collections.namedtuple( 'StackTraceEntry', ('filename', 'line_number', 'function_name', 'text')) ElementDebugInfo = collections.namedtuple( 'ElementDebugInfo', ('element', 'init_stack', 'attribute_stacks')) MODULE_PATH = os.path.dirname(sys.modules[__name__].__file__) DEBUG_METADATA_PREFIX = 'pymjcfdebug' _DEBUG_METADATA_TAG_PREFIX = '<!--' + DEBUG_METADATA_PREFIX _DEBUG_METADATA_SEARCH_PATTERN = re.compile( r'<!--{}:(\d+)-->'.format(DEBUG_METADATA_PREFIX)) # Modified by `freeze_current_stack_trace`. _CURRENT_FROZEN_STACK = None # These globals will take their default values from the `--pymjcf_debug` and # `--pymjcf_debug_full_dump_dir` flags respectively. We cannot use `FLAGS` as # global variables because flag parsing might not have taken place (e.g. when # running `nosetests`). _DEBUG_MODE_ENABLED = None _DEBUG_FULL_DUMP_DIR = None def debug_mode(): """Returns a boolean that indicates whether PyMJCF debug mode is enabled.""" global _DEBUG_MODE_ENABLED if _DEBUG_MODE_ENABLED is None: if FLAGS.is_parsed(): _DEBUG_MODE_ENABLED = FLAGS.pymjcf_debug else: _DEBUG_MODE_ENABLED = FLAGS['pymjcf_debug'].default return _DEBUG_MODE_ENABLED def enable_debug_mode(): """Enables PyMJCF debug mode.""" global _DEBUG_MODE_ENABLED _DEBUG_MODE_ENABLED = True def disable_debug_mode(): """Disables PyMJCF debug mode.""" global _DEBUG_MODE_ENABLED _DEBUG_MODE_ENABLED = False def get_full_dump_dir(): """Gets the directory to dump full debug info files.""" global _DEBUG_FULL_DUMP_DIR if _DEBUG_FULL_DUMP_DIR is None: if FLAGS.is_parsed(): _DEBUG_FULL_DUMP_DIR = FLAGS.pymjcf_debug_full_dump_dir else: _DEBUG_FULL_DUMP_DIR = FLAGS['pymjcf_debug_full_dump_dir'].default return _DEBUG_FULL_DUMP_DIR def set_full_dump_dir(dump_path): """Sets the directory to dump full debug info files.""" global _DEBUG_FULL_DUMP_DIR _DEBUG_FULL_DUMP_DIR = dump_path def get_current_stack_trace(): """Returns the stack trace of the current execution frame. Returns: A list of `StackTraceEntry` named tuples corresponding to the current stack trace of the process, truncated to immediately before entry into PyMJCF internal code. """ if _CURRENT_FROZEN_STACK: return copy.deepcopy(_CURRENT_FROZEN_STACK) else: return _get_actual_current_stack_trace() def _get_actual_current_stack_trace(): """Returns the stack trace of the current execution frame. Returns: A list of `StackTraceEntry` named tuples corresponding to the current stack trace of the process, truncated to immediately before entry into PyMJCF internal code. """ raw_stack = traceback.extract_stack() processed_stack = [] for raw_stack_item in raw_stack: stack_item = StackTraceEntry(*raw_stack_item) if (stack_item.filename.startswith(MODULE_PATH) and not stack_item.filename.endswith('_test.py')): break else: processed_stack.append(stack_item) return processed_stack @contextlib.contextmanager def freeze_current_stack_trace(): """A context manager that freezes the stack trace. AVOID USING THIS CONTEXT MANAGER OUTSIDE OF INTERNAL PYMJCF IMPLEMENTATION, AS IT REDUCES THE USEFULNESS OF DEBUG MODE. If PyMJCF debug mode is enabled, calls to `debugging.get_current_stack_trace` within this context will always return the stack trace from when this context was entered. The frozen stack is global to this debugging module. That is, if the context is entered while another one is still active, then the stack trace of the outermost one is returned. This context significantly speeds up bulk operations in debug mode, e.g. parsing an existing XML string or creating a deeply-nested element, as it prevents the same stack trace from being repeatedly constructed. Yields: `None` """ global _CURRENT_FROZEN_STACK if debug_mode() and _CURRENT_FROZEN_STACK is None: _CURRENT_FROZEN_STACK = _get_actual_current_stack_trace() yield _CURRENT_FROZEN_STACK = None else: yield class DebugContext: """A helper object to store debug information for a generated XML string. This class is intended for internal use within the PyMJCF implementation. """ def __init__(self): self._xml_string = None self._debug_info_for_element_ids = {} def register_element_for_debugging(self, elem): """Registers an `Element` and returns debugging metadata for the XML. Args: elem: An `mjcf.Element`. Returns: An `lxml.etree.Comment` that represents debugging metadata in the generated XML. """ if not debug_mode(): return None else: self._debug_info_for_element_ids[id(elem)] = ElementDebugInfo( elem, copy.deepcopy(elem.get_init_stack()), copy.deepcopy(elem.get_last_modified_stacks_for_all_attributes())) return etree.Comment('{}:{}'.format(DEBUG_METADATA_PREFIX, id(elem))) def commit_xml_string(self, xml_string): """Commits the XML string associated with this debug context. This function also formats the XML string to make sure that the debugging metadata appears on the same line as the corresponding XML element. Args: xml_string: A pretty-printed XML string. Returns: A reformatted XML string where all debugging metadata appears on the same line as the corresponding XML element. """ formatted = re.sub(r'\n\s*' + _DEBUG_METADATA_TAG_PREFIX, _DEBUG_METADATA_TAG_PREFIX, xml_string) self._xml_string = formatted return formatted def process_and_raise_last_exception(self): """Processes and re-raises the last ValueError caught. This function will insert the relevant line from the source XML to the error message. If debug mode is enabled, additional debugging information is appended to the error message. If debug mode is not enabled, the error message instructs the user to enable it by rerunning the executable with an appropriate flag. """ err_type, err, tb = sys.exc_info() line_number_match = re.search(r'[Ll][Ii][Nn][Ee]\s*[:=]?\s*(\d+)', str(err)) if line_number_match: xml_line_number = int(line_number_match.group(1)) xml_line = self._xml_string.split('\n')[xml_line_number - 1] stripped_xml_line = xml_line.strip() comment_match = re.search(_DEBUG_METADATA_TAG_PREFIX, stripped_xml_line) if comment_match: stripped_xml_line = stripped_xml_line[:comment_match.start()] else: xml_line = '' stripped_xml_line = '' message_lines = [] if debug_mode(): if get_full_dump_dir(): self.dump_full_debug_info_to_disk() message_lines.extend([ 'Compile error raised by Mujoco.', str(err)]) if xml_line: message_lines.extend([ stripped_xml_line, self._generate_debug_message_from_xml_line(xml_line)]) else: message_lines.extend([ 'Compile error raised by Mujoco; ' + 'run again with --pymjcf_debug for additional debug information.', str(err) ]) if xml_line: message_lines.append(stripped_xml_line) raise err_type('\n'.join(message_lines)).with_traceback(tb) @property def default_dump_dir(self): return get_full_dump_dir() @property def debug_mode(self): return debug_mode() def dump_full_debug_info_to_disk(self, dump_dir=None): """Dumps full debug information to disk. Full debug information consists of an XML file whose elements are tagged with a unique ID, and a stack trace file for each element ID. Each stack trace file consists of a stack trace for when the element was created, and when each attribute was last modified. Args: dump_dir: Full path to the directory in which dump files are created. Raises: ValueError: If neither `dump_dir` nor the global dump path is given. The global dump path can be specified either via the --pymjcf_debug_full_dump_dir flag or via `debugging.set_full_dump_dir`. """ dump_dir = dump_dir or self.default_dump_dir if not dump_dir: raise ValueError('`dump_dir` is not specified') section_separator = '\n' + ('=' * 80) + '\n' def dump_stack(header, stack, f): indent = ' ' f.write(header + '\n') for stack_entry in stack: f.write(indent + '`{}` at {}:{}\n' .format(stack_entry.function_name, stack_entry.filename, stack_entry.line_number)) f.write((indent * 2) + str(stack_entry.text) + '\n') f.write(section_separator) with open(os.path.join(dump_dir, 'model.xml'), 'w') as f: f.write(self._xml_string) for elem_id, debug_info in self._debug_info_for_element_ids.items(): with open(os.path.join(dump_dir, str(elem_id) + '.dump'), 'w') as f: f.write('{}:{}\n'.format(DEBUG_METADATA_PREFIX, elem_id)) f.write(str(debug_info.element) + '\n') dump_stack('Element creation', debug_info.init_stack, f) for attrib_name, stack in debug_info.attribute_stacks.items(): attrib_value = ( debug_info.element.get_attribute_xml_string(attrib_name)) if stack[-1] == debug_info.init_stack[-1]: if attrib_value is not None: f.write('Attribute {}="{}"\n'.format(attrib_name, attrib_value)) f.write(' was set when the element was created\n') f.write(section_separator) else: if attrib_value is not None: dump_stack('Attribute {}="{}"'.format(attrib_name, attrib_value), stack, f) else: dump_stack( 'Attribute {} was CLEARED'.format(attrib_name), stack, f) def _generate_debug_message_from_xml_line(self, xml_line): """Generates a debug message by parsing the metadata on an XML line.""" metadata_match = _DEBUG_METADATA_SEARCH_PATTERN.search(xml_line) if metadata_match: elem_id = int(metadata_match.group(1)) return self._generate_debug_message_from_element_id(elem_id) else: return '' def _generate_debug_message_from_element_id(self, elem_id): """Generates a debug message for the specified Element.""" out = [] debug_info = self._debug_info_for_element_ids[elem_id] out.append('Debug summary for element:') if not get_full_dump_dir(): out.append( ' * Full debug info can be dumped to disk by setting the ' 'flag --pymjcf_debug_full_dump_dir=path/to/dump>') out.append(' * Element object was created by `{}` at {}:{}' .format(debug_info.init_stack[-1].function_name, debug_info.init_stack[-1].filename, debug_info.init_stack[-1].line_number)) for attrib_name, stack in debug_info.attribute_stacks.items(): attrib_value = debug_info.element.get_attribute_xml_string(attrib_name) if stack[-1] == debug_info.init_stack[-1]: if attrib_value is not None: out.append(' * {}="{}" was set when the element was created' .format(attrib_name, attrib_value)) else: if attrib_value is not None: out.append(' * {}="{}" was set by `{}` at `{}:{}`' .format(attrib_name, attrib_value, stack[-1].function_name, stack[-1].filename, stack[-1].line_number)) else: out.append(' * {} was CLEARED by `{}` at {}:{}' .format(attrib_name, stack[-1].function_name, stack[-1].filename, stack[-1].line_number)) return '\n'.join(out)
dm_control-main
dm_control/mjcf/debugging.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 to represent MJCF elements in the object model.""" import collections import copy import os import sys from dm_control.mjcf import attribute as attribute_types from dm_control.mjcf import base from dm_control.mjcf import constants from dm_control.mjcf import copier from dm_control.mjcf import debugging from dm_control.mjcf import namescope from dm_control.mjcf import schema from dm_control.mujoco.wrapper import util from lxml import etree import numpy as np _raw_property = property # pylint: disable=invalid-name _UNITS = ('K', 'M', 'G', 'T', 'P', 'E') def _to_bytes(value_str): """Converts a `str` value representing a size in bytes to `int`. Args: value_str: `str` value to be converted. Returns: `int` corresponding size in bytes. Raises: ValueError: if the `str` value passed has an unsupported unit. """ if value_str.isdigit(): value_int = int(value_str) else: value_int = int(value_str[:-1]) unit = value_str[-1].upper() if unit not in _UNITS: raise ValueError( f'unit of `size.memory` should be one of [{", ".join(_UNITS)}], got' f' {unit}') power = 10 * (_UNITS.index(unit) + 1) value_int *= 2**power return value_int def _max_bytes(first, second): return str(max(_to_bytes(first), _to_bytes(second))) _CONFLICT_BEHAVIOR_FUNC = {'min': min, 'max': max, 'max_bytes': _max_bytes} def property(method): # pylint: disable=redefined-builtin """Modifies `@property` to keep track of any `AttributeError` raised. Our `Element` implementations overrides the `__getattr__` method. This does not interact well with `@property`: if a `property`'s code is buggy so as to raise an `AttributeError`, then Python would silently discard it and redirect to our `__getattr__` instead, leading to an uninformative stack trace. This makes it very difficult to debug issues that involve properties. To remedy this, we modify `@property` within this module to store any `AttributeError` raised within the respective `Element` object. Then, in our `__getattr__` logic, we could re-raise it to preserve the original stack trace. The reason that this is not implemented as a different decorator is that we could accidentally use @property on a new method. This would work fine until someone triggers a subtle bug. This is when a proper trace would be most useful, but we would still end up with a strange undebuggable stack trace anyway. Note that at the end of this module, we have a `del property` to prevent this override from being broadcasted externally. Args: method: The method that is being decorated. Returns: A `property` corresponding to the decorated method. """ def _mjcf_property(self): try: return method(self) except: _, err, tb = sys.exc_info() err_with_next_tb = err.with_traceback(tb.tb_next) if isinstance(err, AttributeError): self._last_attribute_error = err_with_next_tb # pylint: disable=protected-access raise err_with_next_tb # pylint: disable=raise-missing-from return _raw_property(_mjcf_property) def _make_element(spec, parent, attributes=None): """Helper function to generate the right kind of Element given a spec.""" if (spec.name == constants.WORLDBODY or (spec.name == constants.SITE and (parent.tag == constants.BODY or parent.tag == constants.WORLDBODY))): return _AttachableElement(spec, parent, attributes) elif isinstance(parent, _AttachmentFrame): return _AttachmentFrameChild(spec, parent, attributes) elif spec.name == constants.DEFAULT: return _DefaultElement(spec, parent, attributes) elif spec.name == constants.ACTUATOR: return _ActuatorElement(spec, parent, attributes) else: return _ElementImpl(spec, parent, attributes) _DEFAULT_NAME_FROM_FILENAME = frozenset(['mesh', 'hfield', 'texture']) class _ElementImpl(base.Element): """Actual implementation of a generic MJCF element object.""" __slots__ = ['__weakref__', '_spec', '_parent', '_attributes', '_children', '_own_attributes', '_attachments', '_is_removed', '_init_stack', '_is_worldbody', '_cached_namescope', '_cached_root', '_cached_full_identifier', '_cached_revision', '_last_attribute_error'] def __init__(self, spec, parent, attributes=None): attributes = attributes or {} # For certain `asset` elements the `name` attribute can be omitted, in which # case the name will be the filename without the leading path and extension. # See http://www.mujoco.org/book/XMLreference.html#asset. if ('name' not in attributes and 'file' in attributes and spec.name in _DEFAULT_NAME_FROM_FILENAME): _, filename = os.path.split(attributes['file']) basename, _ = os.path.splitext(filename) attributes['name'] = basename self._spec = spec self._parent = parent self._attributes = collections.OrderedDict() self._own_attributes = None self._children = [] self._attachments = collections.OrderedDict() self._is_removed = False self._is_worldbody = (self.tag == 'worldbody') if self._parent: self._cached_namescope = self._parent.namescope self._cached_root = self._parent.root self._cached_full_identifier = '' self._cached_revision = -1 self._last_attribute_error = None if debugging.debug_mode(): self._init_stack = debugging.get_current_stack_trace() with debugging.freeze_current_stack_trace(): for child_spec in self._spec.children.values(): if not (child_spec.repeated or child_spec.on_demand): self._children.append(_make_element(spec=child_spec, parent=self)) if constants.DCLASS in attributes: attributes[constants.CLASS] = attributes[constants.DCLASS] del attributes[constants.DCLASS] for attribute_name in attributes.keys(): self._check_valid_attribute(attribute_name) for attribute_spec in self._spec.attributes.values(): value = None # Some Reference attributes refer to a namespace that is specified # via another attribute. We therefore have to set things up for # the additional indirection. if attribute_spec.type is attribute_types.Reference: reference_namespace = ( attribute_spec.other_kwargs['reference_namespace']) if reference_namespace.startswith( constants.INDIRECT_REFERENCE_NAMESPACE_PREFIX): attribute_spec = copy.deepcopy(attribute_spec) namespace_attrib_name = reference_namespace[ len(constants.INDIRECT_REFERENCE_NAMESPACE_PREFIX):] attribute_spec.other_kwargs['reference_namespace'] = ( self._attributes[namespace_attrib_name]) if attribute_spec.name in attributes: value = attributes[attribute_spec.name] try: self._attributes[attribute_spec.name] = attribute_spec.type( name=attribute_spec.name, required=attribute_spec.required, conflict_allowed=attribute_spec.conflict_allowed, conflict_behavior=attribute_spec.conflict_behavior, parent=self, value=value, **attribute_spec.other_kwargs) except: # On failure, clear attributes already created for attribute_obj in self._attributes.values(): attribute_obj._force_clear() # pylint: disable=protected-access # Then raise a meaningful error err_type, err, tb = sys.exc_info() raise err_type( # pylint: disable=raise-missing-from f'during initialization of attribute {attribute_spec.name!r} of ' f'element <{self._spec.name}>: {err}').with_traceback(tb) def get_init_stack(self): """Gets the stack trace where this element was first initialized.""" if debugging.debug_mode(): return self._init_stack def get_last_modified_stacks_for_all_attributes(self): """Gets a dict of stack traces where each attribute was last modified.""" return collections.OrderedDict( [(name, self._attributes[name].last_modified_stack) for name in self._spec.attributes]) def is_same_as(self, other): """Checks whether another element is semantically equivalent to this one. Two elements are considered equivalent if they have the same specification (i.e. same tag appearing in the same context), the same attribute values, and all of their children are equivalent. The ordering of non-repeated children is not important for this comparison, while the ordering of repeated children are important only amongst the same type* of children. In other words, for two bodies to be considered equivalent, their child sites must appear in the same order, and their child geoms must appear in the same order, but permutations between sites and geoms are disregarded. (The only exception is in tendon definition, where strict ordering of all children is necessary for equivalence.) *Note that the notion of "same type" in this function is very loose: for example different actuator element subtypes are treated as separate types when children ordering is considered. Therefore, two <actuator> elements might be considered equivalent even though they result in different orderings of `mjData.ctrl` when compiled. As it stands, this function is designed primarily as a testing aid and should not be used to guarantee that models are actually identical. Args: other: An `mjcf.Element` Returns: `True` if `other` element is semantically equivalent to this one. """ if other is None or other.spec != self._spec: return False for attribute_name in self._spec.attributes.keys(): attribute = self._attributes[attribute_name] other_attribute = getattr(other, attribute_name) if isinstance(attribute.value, base.Element): if attribute.value.full_identifier != other_attribute.full_identifier: return False elif not np.all(attribute.value == other_attribute): return False if (self._parent and self._parent.tag == constants.TENDON and self._parent.parent == self.root): return self._tendon_has_same_children_as(other) else: return self._has_same_children_as(other) def _has_same_children_as(self, other): """Helper function to check whether another element has the same children. See docstring for `is_same_as` for explanation about the treatment of children ordering. Args: other: An `mjcf.Element` Returns: A boolean """ for child_name, child_spec in self._spec.children.items(): child = self.get_children(child_name) other_child = getattr(other, child_name) if not child_spec.repeated: if ((child is None and other_child is not None) or (child is not None and not child.is_same_as(other_child))): return False else: if len(child) != len(other_child): return False else: for grandchild, other_grandchild in zip(child, other_child): if not grandchild.is_same_as(other_grandchild): return False return True def _tendon_has_same_children_as(self, other): return all(child.is_same_as(other_child) for child, other_child in zip(self.all_children(), other.all_children())) def _alias_attributes_dict(self, other): if self._own_attributes is None: self._own_attributes = self._attributes self._attributes = other def _restore_attributes_dict(self): if self._own_attributes is not None: for attribute_name, attribute in self._attributes.items(): self._own_attributes[attribute_name].value = attribute.value self._attributes = self._own_attributes self._own_attributes = None @property def tag(self): return self._spec.name @property def spec(self): return self._spec @property def parent(self): return self._parent @property def namescope(self): return self._cached_namescope @property def root(self): return self._cached_root def prefixed_identifier(self, prefix_root): if not self._spec.identifier and not self._is_worldbody: return None elif self._is_worldbody: prefix = self.namescope.full_prefix(prefix_root=prefix_root) return prefix or 'world' else: full_identifier = ( self._attributes[self._spec.identifier].to_xml_string( prefix_root=prefix_root)) if full_identifier: return full_identifier else: prefix = self.namescope.full_prefix(prefix_root=prefix_root) prefix = prefix or constants.PREFIX_SEPARATOR return prefix + self._default_identifier @property def full_identifier(self): """Fully-qualified identifier used for this element in the generated XML.""" if self.namescope.revision > self._cached_revision: self._cached_full_identifier = self.prefixed_identifier( prefix_root=self.namescope.root) self._cached_revision = self.namescope.revision return self._cached_full_identifier @property def _default_identifier(self): """The default identifier used if this element is not named by the user.""" if not self._spec.identifier: return None else: siblings = self.root.find_all(self._spec.namespace, exclude_attachments=True) return '{separator}unnamed_{namespace}_{index}'.format( separator=constants.PREFIX_SEPARATOR, namespace=self._spec.namespace, index=siblings.index(self)) def __dir__(self): out_dir = set() classes = (type(self),) while classes: super_classes = set() for klass in classes: out_dir.update(klass.__dict__) super_classes.update(klass.__bases__) classes = super_classes out_dir.update(self._spec.children) out_dir.update(self._spec.attributes) if constants.CLASS in out_dir: out_dir.remove(constants.CLASS) out_dir.add(constants.DCLASS) return sorted(out_dir) def find(self, namespace, identifier): """Finds an element with a particular identifier. This function allows the direct access to an arbitrarily deeply nested child element by name, without the need to manually traverse through the object tree. The `namespace` argument specifies the kind of element to find. In most cases, this corresponds to the element's XML tag name. However, if an element has multiple specialized tags, then the namespace corresponds to the tag name of the most general element of that kind. For example, `namespace='joint'` would search for `<joint>` and `<freejoint>`, while `namespace='actuator'` would search for `<general>`, `<motor>`, `<position>`, `<velocity>`, and `<cylinder>`. Args: namespace: A string specifying the namespace being searched. See the docstring above for explanation. identifier: The identifier string of the desired element. Returns: An `mjcf.Element` object, or `None` if an element with the specified identifier is not found. Raises: ValueError: if either `namespace` or `identifier` is not a string, or if `namespace` is not a valid namespace. """ if not isinstance(namespace, str): raise ValueError( '`namespace` should be a string: got {!r}'.format(namespace)) if not isinstance(identifier, str): raise ValueError( '`identifier` should be a string: got {!r}'.format(identifier)) if namespace not in schema.FINDABLE_NAMESPACES: raise ValueError('{!r} is not a valid namespace. Available: {}.'.format( namespace, schema.FINDABLE_NAMESPACES)) if constants.PREFIX_SEPARATOR in identifier: scope_name = identifier.split(constants.PREFIX_SEPARATOR)[0] try: attachment = self.namescope.get('attached_model', scope_name) found_element = attachment.find( namespace, identifier[(len(scope_name) + 1):]) except (KeyError, ValueError): found_element = None else: try: found_element = self.namescope.get(namespace, identifier) except KeyError: found_element = None if found_element and self._parent: next_parent = found_element.parent while next_parent and next_parent != self: next_parent = next_parent.parent if not next_parent: found_element = None return found_element def find_all(self, namespace, immediate_children_only=False, exclude_attachments=False): """Finds all elements of a particular kind. The `namespace` argument specifies the kind of element to find. In most cases, this corresponds to the element's XML tag name. However, if an element has multiple specialized tags, then the namespace corresponds to the tag name of the most general element of that kind. For example, `namespace='joint'` would search for `<joint>` and `<freejoint>`, while `namespace='actuator'` would search for `<general>`, `<motor>`, `<position>`, `<velocity>`, and `<cylinder>`. Args: namespace: A string specifying the namespace being searched. See the docstring above for explanation. immediate_children_only: (optional) A boolean, if `True` then only the immediate children of this element are returned. exclude_attachments: (optional) A boolean, if `True` then elements belonging to attached models are excluded. Returns: A list of `mjcf.Element`. Raises: ValueError: if `namespace` is not a valid namespace. """ if namespace not in schema.FINDABLE_NAMESPACES: raise ValueError('{!r} is not a valid namespace. Available: {}'.format( namespace, schema.FINDABLE_NAMESPACES)) out = [] children = self._children if exclude_attachments else self.all_children() for child in children: if (namespace == child.spec.namespace or # Direct children of attachment frames have custom namespaces of the # form "joint@attachment_frame_<id>". child.spec.namespace and child.spec.namespace.startswith( namespace + constants.NAMESPACE_SEPARATOR) or # Attachment frames are considered part of the "body" namespace. namespace == constants.BODY and isinstance(child, _AttachmentFrame)): out.append(child) if not immediate_children_only: out.extend(child.find_all(namespace, exclude_attachments=exclude_attachments)) return out def enter_scope(self, scope_identifier): """Finds the root element of the given scope and returns it. This function allows the access to a nested scope that is a child of this element. The `scope_identifier` argument specifies the path to the child scope element. Args: scope_identifier: The path of the desired scope element. Returns: An `mjcf.Element` object, or `None` if a scope element with the specified path is not found. """ if constants.PREFIX_SEPARATOR in scope_identifier: scope_name = scope_identifier.split(constants.PREFIX_SEPARATOR)[0] try: attachment = self.namescope.get('attached_model', scope_name) except KeyError: return None scope_suffix = scope_identifier[(len(scope_name) + 1):] if scope_suffix: return attachment.enter_scope(scope_suffix) else: return attachment else: try: return self.namescope.get('attached_model', scope_identifier) except KeyError: return None def _check_valid_attribute(self, attribute_name): if attribute_name not in self._spec.attributes: raise AttributeError( '{!r} is not a valid attribute for <{}>'.format( attribute_name, self._spec.name)) def _get_attribute(self, attribute_name): self._check_valid_attribute(attribute_name) return self._attributes[attribute_name].value def get_attribute_xml_string(self, attribute_name, prefix_root=None, *, precision=constants.XML_DEFAULT_PRECISION, zero_threshold=0): self._check_valid_attribute(attribute_name) return self._attributes[attribute_name].to_xml_string( prefix_root, precision=precision, zero_threshold=zero_threshold) def get_attributes(self): fix_attribute_name = ( lambda name: constants.DCLASS if name == constants.CLASS else name) return collections.OrderedDict( [(fix_attribute_name(name), self._get_attribute(name)) for name in self._spec.attributes.keys() if self._get_attribute(name) is not None]) def _set_attribute(self, attribute_name, value): self._check_valid_attribute(attribute_name) self._attributes[attribute_name].value = value self.namescope.increment_revision() def set_attributes(self, **kwargs): if constants.DCLASS in kwargs: kwargs[constants.CLASS] = kwargs[constants.DCLASS] del kwargs[constants.DCLASS] old_values = [] with debugging.freeze_current_stack_trace(): for attribute_name, new_value in kwargs.items(): old_value = self._get_attribute(attribute_name) try: self._set_attribute(attribute_name, new_value) old_values.append((attribute_name, old_value)) except: # On failure, restore old attribute values for those already set. for name, old_value in old_values: self._set_attribute(name, old_value) # Then raise a meaningful error. err_type, err, tb = sys.exc_info() raise err_type( # pylint: disable=raise-missing-from f'during assignment to attribute {attribute_name!r} of ' f'element <{self._spec.name}>: {err}').with_traceback(tb) def _remove_attribute(self, attribute_name): self._check_valid_attribute(attribute_name) self._attributes[attribute_name].clear() self.namescope.increment_revision() def _check_valid_child(self, element_name): try: return self._spec.children[element_name] except KeyError: raise AttributeError( # pylint: disable=raise-missing-from '<{}> is not a valid child of <{}>' .format(element_name, self._spec.name)) def get_children(self, element_name): child_spec = self._check_valid_child(element_name) if child_spec.repeated: return _ElementListView(spec=child_spec, parent=self) else: for child in self._children: if child.tag == element_name: return child if child_spec.on_demand: return None else: raise RuntimeError( 'Cannot find the non-repeated child <{}> of <{}>. ' 'This should never happen, as we pre-create these in __init__. ' 'Please file an bug report. Thank you.' .format(element_name, self._spec.name)) def add(self, element_name, **kwargs): """Add a new child element to this element. Args: element_name: The tag of the element to add. **kwargs: Attributes of the new element being created. Raises: ValueError: If the 'element_name' is not a valid child, or if an invalid attribute is specified in `kwargs`. Returns: An `mjcf.Element` corresponding to the newly created child element. """ return self.insert(element_name, position=None, **kwargs) def insert(self, element_name, position, **kwargs): """Add a new child element to this element. Args: element_name: The tag of the element to add. position: Where to insert the new element. **kwargs: Attributes of the new element being created. Raises: ValueError: If the 'element_name' is not a valid child, or if an invalid attribute is specified in `kwargs`. Returns: An `mjcf.Element` corresponding to the newly created child element. """ child_spec = self._check_valid_child(element_name) if child_spec.on_demand: need_new_on_demand = self.get_children(element_name) is None else: need_new_on_demand = False if not (child_spec.repeated or need_new_on_demand): raise ValueError('A <{}> child already exists, please access it directly.' .format(element_name)) new_element = _make_element(child_spec, self, attributes=kwargs) if position is not None: self._children.insert(position, new_element) else: self._children.append(new_element) self.namescope.increment_revision() return new_element def __getattr__(self, name): if self._last_attribute_error: # This means that we got here through a @property raising AttributeError. # We therefore just re-raise the last AttributeError back to the user. # Note that self._last_attribute_error was set by our specially # instrumented @property decorator. exc = self._last_attribute_error self._last_attribute_error = None raise exc # pylint: disable=raising-bad-type elif name in self._spec.children: return self.get_children(name) elif name in self._spec.attributes: return self._get_attribute(name) elif name == constants.DCLASS and constants.CLASS in self._spec.attributes: return self._get_attribute(constants.CLASS) else: raise AttributeError('object has no attribute: {}'.format(name)) def __setattr__(self, name, value): # If this name corresponds to a descriptor for a slotted attribute or # settable property then try to invoke the descriptor to set the attribute # and return if successful. klass_attr = getattr(type(self), name, None) if klass_attr is not None: try: return klass_attr.__set__(self, value) except AttributeError: pass # If we did not find a settable descriptor then we look in the attribute # spec to see if there is a MuJoCo attribute matching this name. attribute_name = name if name != constants.DCLASS else constants.CLASS if attribute_name in self._spec.attributes: self._set_attribute(attribute_name, value) else: raise AttributeError('can\'t set attribute: {}'.format(name)) def __delattr__(self, name): if name in self._spec.children: if self._spec.children[name].repeated: raise AttributeError( '`{0}` is a collection of child elements, ' 'which cannot be deleted. Did you mean to call `{0}.clear()`?' .format(name)) else: return self.get_children(name).remove() elif name in self._spec.attributes: return self._remove_attribute(name) else: raise AttributeError('object has no attribute: {}'.format(name)) def _check_attachments_on_remove(self, affect_attachments): if not affect_attachments and self._attachments: raise ValueError( 'please use remove(affect_attachments=True) as this will affect some ' 'attributes and/or children belonging to an attached model') for child in self._children: child._check_attachments_on_remove(affect_attachments) # pylint: disable=protected-access def remove(self, affect_attachments=False): """Removes this element from the model.""" self._check_attachments_on_remove(affect_attachments) if affect_attachments: for attachment in self._attachments.values(): attachment.remove(affect_attachments=True) for child in list(self._children): child.remove(affect_attachments) if self._spec.repeated or self._spec.on_demand: self._parent._children.remove(self) # pylint: disable=protected-access for attribute in self._attributes.values(): attribute._force_clear() # pylint: disable=protected-access self._parent = None self._is_removed = True else: for attribute in self._attributes.values(): attribute._force_clear() # pylint: disable=protected-access self.namescope.increment_revision() @property def is_removed(self): return self._is_removed def all_children(self): all_children = [child for child in self._children] for attachment in self._attachments.values(): all_children += [child for child in attachment.all_children() if child.spec.repeated] return all_children def to_xml(self, prefix_root=None, debug_context=None, *, precision=constants.XML_DEFAULT_PRECISION, zero_threshold=0): """Generates an etree._Element corresponding to this MJCF element. Args: prefix_root: (optional) A `NameScope` object to be treated as root for the purpose of calculating the prefix. If `None` then no prefix is included. debug_context: (optional) A `debugging.DebugContext` object to which the debugging information associated with the generated XML is written. This is intended for internal use within PyMJCF; users should never need manually pass this argument. precision: (optional) Number of digits to output for floating point quantities. zero_threshold: (optional) When outputting XML, floating point quantities whose absolute value falls below this threshold will be treated as zero. Returns: An etree._Element object. """ prefix_root = prefix_root or self.namescope xml_element = etree.Element(self._spec.name) self._attributes_to_xml(xml_element, prefix_root, debug_context, precision=precision, zero_threshold=zero_threshold) self._children_to_xml(xml_element, prefix_root, debug_context, precision=precision, zero_threshold=zero_threshold) return xml_element def _attributes_to_xml(self, xml_element, prefix_root, debug_context=None, *, precision, zero_threshold): del debug_context # Unused. for attribute_name, attribute in self._attributes.items(): attribute_value = attribute.to_xml_string(prefix_root, precision=precision, zero_threshold=zero_threshold) if attribute_name == self._spec.identifier and attribute_value is None: xml_element.set(attribute_name, self.full_identifier) elif attribute_value is None: continue else: xml_element.set(attribute_name, attribute_value) def _children_to_xml(self, xml_element, prefix_root, debug_context=None, *, precision, zero_threshold): for child in self.all_children(): child_xml = child.to_xml(prefix_root, debug_context, precision=precision, zero_threshold=zero_threshold) if (child_xml.attrib or len(child_xml) # pylint: disable=g-explicit-length-test or child.spec.repeated or child.spec.on_demand): xml_element.append(child_xml) if debugging.debug_mode() and debug_context: debug_comment = debug_context.register_element_for_debugging(child) xml_element.append(debug_comment) if len(child_xml) > 0: # pylint: disable=g-explicit-length-test child_xml.insert(0, copy.deepcopy(debug_comment)) def to_xml_string(self, prefix_root=None, self_only=False, pretty_print=True, debug_context=None, *, precision=constants.XML_DEFAULT_PRECISION, zero_threshold=0): """Generates an XML string corresponding to this MJCF element. Args: prefix_root: (optional) A `NameScope` object to be treated as root for the purpose of calculating the prefix. If `None` then no prefix is included. self_only: (optional) A boolean, whether to generate an XML corresponding only to this element without any children. pretty_print: (optional) A boolean, whether to the XML string should be properly indented. debug_context: (optional) A `debugging.DebugContext` object to which the debugging information associated with the generated XML is written. This is intended for internal use within PyMJCF; users should never need manually pass this argument. precision: (optional) Number of digits to output for floating point quantities. zero_threshold: (optional) When outputting XML, floating point quantities whose absolute value falls below this threshold will be treated as zero. Returns: A string. """ xml_element = self.to_xml(prefix_root, debug_context, precision=precision, zero_threshold=zero_threshold) if self_only and len(xml_element) > 0: # pylint: disable=g-explicit-length-test etree.strip_elements(xml_element, '*') xml_element.text = '...' if (self_only and self._spec.identifier and not self._attributes[self._spec.identifier].to_xml_string( prefix_root, precision=precision, zero_threshold=zero_threshold)): del xml_element.attrib[self._spec.identifier] xml_string = util.to_native_string( etree.tostring(xml_element, pretty_print=pretty_print)) if pretty_print and debug_context: return debug_context.commit_xml_string(xml_string) else: return xml_string def __str__(self): return self.to_xml_string(self_only=True, pretty_print=False) def __repr__(self): return 'MJCF Element: ' + str(self) def _check_valid_attachment(self, other): self_spec = self._spec if self_spec.name == constants.WORLDBODY: self_spec = self._spec.children[constants.BODY] other_spec = other.spec if other_spec.name == constants.WORLDBODY: other_spec = other_spec.children[constants.BODY] if other_spec != self_spec: raise ValueError( 'The attachment must have the same spec as this element.') def _attach(self, other, exclude_worldbody=False, dry_run=False): """Attaches another element of the same spec to this element. All children of `other` will be treated as children of this element. All XML attributes which are defined in `other` but not defined in this element will be copied over, and any conflicting XML attribute value causes an error. After the attachment, any XML attribute modified in this element will also affect `other` and vice versa. Children of this element which are not a repeated elements will also be attached by the corresponding children of `other`. Args: other: Another Element with the same spec. exclude_worldbody: (optional) A boolean. If `True`, then don't do anything if `other` is a worldbody. dry_run: (optional) A boolean, if `True` only verify that the operation is valid without actually committing any change. Raises: ValueError: If `other` has a different spec, or if there are conflicting XML attribute values. """ self._check_valid_attachment(other) if exclude_worldbody and other.tag == constants.WORLDBODY: return if dry_run: self._check_conflicting_attributes(other, copying=False) else: self._attachments[other.namescope] = other self._sync_attributes(other, copying=False) self._attach_children(other, exclude_worldbody, dry_run) if other.tag != constants.WORLDBODY and not dry_run: other._alias_attributes_dict(self._attributes) # pylint: disable=protected-access def _detach(self, other_namescope): """Detaches a model with the specified namescope.""" attached_element = self._attachments.get(other_namescope) if attached_element: attached_element._restore_attributes_dict() # pylint: disable=protected-access del self._attachments[other_namescope] for child in self._children: child._detach(other_namescope) # pylint: disable=protected-access def _check_conflicting_attributes(self, other, copying): for attribute_name, other_attribute in other.get_attributes().items(): if attribute_name == constants.DCLASS: attribute_name = constants.CLASS if ((not self._attributes[attribute_name].conflict_allowed) and self._attributes[attribute_name].value is not None and other_attribute is not None and np.asarray( self._attributes[attribute_name].value != other_attribute).any()): raise ValueError( 'Conflicting values for attribute `{}`: {} vs {}' .format(attribute_name, self._attributes[attribute_name].value, other_attribute)) def _sync_attributes(self, other, copying): self._check_conflicting_attributes(other, copying) for attribute_name, other_attribute in other.get_attributes().items(): if attribute_name == constants.DCLASS: attribute_name = constants.CLASS self_attribute = self._attributes[attribute_name] if other_attribute is not None: if self_attribute.conflict_behavior in _CONFLICT_BEHAVIOR_FUNC: if self_attribute.value is not None: self_attribute.value = ( _CONFLICT_BEHAVIOR_FUNC[self_attribute.conflict_behavior]( self_attribute.value, other_attribute)) else: self_attribute.value = other_attribute elif copying or not self_attribute.conflict_allowed: self_attribute.value = other_attribute def _attach_children(self, other, exclude_worldbody, dry_run=False): for other_child in other.all_children(): if not other_child.spec.repeated: self_child = self.get_children(other_child.spec.name) self_child._attach(other_child, exclude_worldbody, dry_run) # pylint: disable=protected-access def resolve_references(self): for attribute in self._attributes.values(): if isinstance(attribute, attribute_types.Reference): if attribute.value and isinstance(attribute.value, str): referred = self.root.find( attribute.reference_namespace, attribute.value) if referred: attribute.value = referred for child in self.all_children(): child.resolve_references() def _update_references(self, reference_dict): for attribute in self._attributes.values(): if isinstance(attribute, attribute_types.Reference): if attribute.value in reference_dict: attribute.value = reference_dict[attribute.value] for child in self.all_children(): child._update_references(reference_dict) # pylint: disable=protected-access class _AttachableElement(_ElementImpl): """Specialized object representing a <site> or <worldbody> element. This element defines a frame to which another MJCF model can be attached. """ __slots__ = [] def attach(self, attachment): """Attaches another MJCF model at this site. An empty <body> will be created as an attachment frame. All children of `attachment`'s <worldbody> will be treated as children of this frame. Furthermore, all other elements in `attachment` are merged into the root of the MJCF model to which this element belongs. Args: attachment: An MJCF `RootElement` Returns: An `mjcf.Element` corresponding to the attachment frame. A joint can be added directly to this frame to give degrees of freedom to the attachment. Raises: ValueError: If `other` is not a valid attachment to this element. """ if not isinstance(attachment, RootElement): raise ValueError('Expected a mjcf.RootElement: got {}' .format(attachment)) if attachment.namescope.parent is not None: raise ValueError('The model specified is already attached elsewhere') if attachment.namescope == self.namescope: raise ValueError('Cannot merge a model to itself') self.root._attach(attachment, exclude_worldbody=True, dry_run=True) # pylint: disable=protected-access if self.namescope.has_identifier('namescope', attachment.model): id_number = 1 while self.namescope.has_identifier( 'namescope', '{}_{}'.format(attachment.model, id_number)): id_number += 1 attachment.model = '{}_{}'.format(attachment.model, id_number) attachment.namescope.parent = self.namescope if self.tag == constants.WORLDBODY: frame_parent = self frame_siblings = self._children index = len(frame_siblings) else: frame_parent = self._parent frame_siblings = self._parent._children # pylint: disable=protected-access index = frame_siblings.index(self) + 1 while (index < len(frame_siblings) and isinstance(frame_siblings[index], _AttachmentFrame)): index += 1 frame = _AttachmentFrame(frame_parent, self, attachment) frame_siblings.insert(index, frame) self.root._attach(attachment, exclude_worldbody=True) # pylint: disable=protected-access return frame class _AttachmentFrame(_ElementImpl): """An specialized <body> representing a frame holding an external attachment. """ __slots__ = ['_site', '_attachment'] def __init__(self, parent, site, attachment): if parent.tag == constants.WORLDBODY: spec = schema.WORLD_ATTACHMENT_FRAME else: spec = schema.ATTACHMENT_FRAME spec_is_copied = False for child_name, child_spec in spec.children.items(): if child_spec.namespace: if not spec_is_copied: spec = copy.deepcopy(spec) spec_is_copied = True spec_as_dict = child_spec._asdict() spec_as_dict['namespace'] = '{}{}attachment_frame_{}'.format( child_spec.namespace, constants.NAMESPACE_SEPARATOR, id(self)) spec.children[child_name] = type(child_spec)(**spec_as_dict) attributes = {} with debugging.freeze_current_stack_trace(): for attribute_name in spec.attributes.keys(): if hasattr(site, attribute_name): attributes[attribute_name] = getattr(site, attribute_name) super().__init__(spec, parent, attributes) self._site = site self._attachment = attachment self._attachments[attachment.namescope] = attachment.worldbody self.namescope.add('attachment_frame', attachment.namescope.name, self) self.namescope.add('attached_model', attachment.namescope.name, attachment) def prefixed_identifier(self, prefix_root=None): prefix = self.namescope.full_prefix(prefix_root) return prefix + self._attachment.namescope.name + constants.PREFIX_SEPARATOR def to_xml(self, prefix_root=None, debug_context=None, *, precision=constants.XML_DEFAULT_PRECISION, zero_threshold=0): xml_element = (super().to_xml(prefix_root, debug_context, precision=precision, zero_threshold=zero_threshold)) xml_element.set('name', self.prefixed_identifier(prefix_root)) return xml_element @property def full_identifier(self): return self.prefixed_identifier(self.namescope.root) def _detach(self, other_namescope): super()._detach(other_namescope) if other_namescope is self._attachment.namescope: self.namescope.remove('attachment_frame', self._attachment.namescope.name) self.namescope.remove('attached_model', self._attachment.namescope.name) self.remove() class _AttachmentFrameChild(_ElementImpl): """A child element of an attachment frame. Right now, this is always a <joint> or a <freejoint>. The name of the joint is not freely specifiable, but instead just inherits from the parent frame. This ensures uniqueness, as attachment frame identifiers always end in '/'. """ __slots__ = [] def to_xml(self, prefix_root=None, debug_context=None, *, precision=constants.XML_DEFAULT_PRECISION, zero_threshold=0): xml_element = (super().to_xml(prefix_root, debug_context, precision=precision, zero_threshold=zero_threshold)) if self.spec.namespace is not None: if self.name: name = (self._parent.prefixed_identifier(prefix_root) + self.name + constants.PREFIX_SEPARATOR) else: name = self._parent.prefixed_identifier(prefix_root) xml_element.set('name', name) return xml_element def prefixed_identifier(self, prefix_root=None): if self.name: return (self._parent.prefixed_identifier(prefix_root) + self.name + constants.PREFIX_SEPARATOR) else: return self._parent.prefixed_identifier(prefix_root) class _DefaultElement(_ElementImpl): """Specialized object representing a <default> element. This is necessary for the proper handling of global defaults. """ __slots__ = [] def _attach(self, other, exclude_worldbody=False, dry_run=False): self._check_valid_attachment(other) if ((not isinstance(self._parent, RootElement)) or (not isinstance(other.parent, RootElement))): raise ValueError('Only global <{}> can be attached' .format(constants.DEFAULT)) if not dry_run: self._attachments[other.namescope] = other def all_children(self): return [child for child in self._children] def to_xml(self, prefix_root=None, debug_context=None, *, precision=constants.XML_DEFAULT_PRECISION, zero_threshold=0): prefix_root = prefix_root or self.namescope xml_element = (super().to_xml(prefix_root, debug_context, precision=precision, zero_threshold=zero_threshold)) if isinstance(self._parent, RootElement): root_default = etree.Element(self._spec.name) root_default.append(xml_element) for attachment in self._attachments.values(): attachment_xml = attachment.to_xml(prefix_root, debug_context, precision=precision, zero_threshold=zero_threshold) for attachment_child_xml in attachment_xml: root_default.append(attachment_child_xml) xml_element = root_default return xml_element class _ActuatorElement(_ElementImpl): """Specialized object representing an <actuator> element.""" __slots__ = () def _children_to_xml(self, xml_element, prefix_root, debug_context=None, *, precision=constants.XML_DEFAULT_PRECISION, zero_threshold=0): debug_comments = {} for child in self.all_children(): child_xml = child.to_xml(prefix_root, debug_context, precision=precision, zero_threshold=zero_threshold) if debugging.debug_mode() and debug_context: debug_comment = debug_context.register_element_for_debugging(child) debug_comments[child_xml] = debug_comment if len(child_xml) > 0: # pylint: disable=g-explicit-length-test child_xml.insert(0, copy.deepcopy(debug_comment)) xml_element.append(child_xml) if debugging.debug_mode() and debug_context: xml_element.append(debug_comments[child_xml]) class RootElement(_ElementImpl): """The root `<mujoco>` element of an MJCF model.""" __slots__ = ['_namescope'] def __init__(self, model=None, model_dir='', assets=None): model = model or 'unnamed_model' self._namescope = namescope.NameScope( model, self, model_dir=model_dir, assets=assets) super().__init__( spec=schema.MUJOCO, parent=None, attributes={'model': model}) def _attach(self, other, exclude_worldbody=False, dry_run=False): self._check_valid_attachment(other) if not dry_run: self._attachments[other.namescope] = other self._attach_children(other, exclude_worldbody, dry_run) self.namescope.increment_revision() @property def namescope(self): return self._namescope @property def root(self): return self @property def model(self): return self._namescope.name @model.setter def model(self, new_name): old_name = self._namescope.name self._namescope.name = new_name self._attributes['model'].value = new_name if self.parent_model: self.parent_model.namescope.rename('attachment_frame', old_name, new_name) self.parent_model.namescope.rename('attached_model', old_name, new_name) def attach(self, other): return self.worldbody.attach(other) def detach(self): parent_model = self.parent_model if not parent_model: raise RuntimeError( 'Cannot `detach` a model that is not attached to some other model.') else: parent_model._detach(self.namescope) # pylint: disable=protected-access self.namescope.parent = None def include_copy(self, other, override_attributes=False): other_copier = copier.Copier(other) new_elements = other_copier.copy_into(self, override_attributes) self._update_references(new_elements) self.namescope.increment_revision() @property def parent_model(self): """The RootElement of the MJCF model to which this one is attached.""" namescope_parent = self._namescope.parent return namescope_parent.mjcf_model if namescope_parent else None @property def root_model(self): return self.parent_model.root_model if self.parent_model else self def get_assets(self): """Returns a dict containing the binary assets referenced in this model. This will contain `{vfs_filename: contents}` pairs. `vfs_filename` will be the name of the asset in MuJoCo's Virtual File System, which corresponds to the filename given in the XML returned by `to_xml_string()`. `contents` is a bytestring. This dict can be used together with the result of `to_xml_string()` to construct a `mujoco.Physics` instance: ```python physics = mujoco.Physics.from_xml_string( xml_string=mjcf_model.to_xml_string(), assets=mjcf_model.get_assets()) ``` """ # Get the assets referenced within this `RootElement`'s namescope. assets = {file_obj.to_xml_string(): file_obj.get_contents() for file_obj in self.namescope.files if file_obj.value} # Recursively add assets belonging to attachments. for attached_model in self._attachments.values(): assets.update(attached_model.get_assets()) return assets @property def full_identifier(self): return self._namescope.full_prefix(self._namescope.root) def __copy__(self): new_model = RootElement(model=self._namescope.name, model_dir=self.namescope.model_dir) new_model.include_copy(self) return new_model def __deepcopy__(self, _): return self.__copy__() def is_same_as(self, other): if other is None or other.spec != self._spec: return False return self._has_same_children_as(other) class _ElementListView: """A hybrid list/dict-like view to a group of repeated MJCF elements.""" def __init__(self, spec, parent): self._spec = spec self._parent = parent self._elements = self._parent._children # pylint: disable=protected-access self._scoped_elements = collections.OrderedDict( [(scope_namescope.name, getattr(scoped_parent, self._spec.name)) for scope_namescope, scoped_parent in self._parent._attachments.items()]) @property def spec(self): return self._spec @property def tag(self): return self._spec.name @property def namescope(self): return self._parent.namescope @property def parent(self): return self._parent def __len__(self): return len(self._full_list()) def __iter__(self): return iter(self._full_list()) def _identifier_not_found_error(self, index): return KeyError('An element <{}> with {}={!r} does not exist' .format(self._spec.name, self._spec.identifier, index)) def _find_index(self, index): """Locates an element given the index among siblings with the same tag.""" if isinstance(index, str) and self._spec.identifier: for i, element in enumerate(self._elements): if (element.tag == self._spec.name and getattr(element, self._spec.identifier) == index): return i raise self._identifier_not_found_error(index) else: count = 0 for i, element in enumerate(self._elements): if element.tag == self._spec.name: if index == count: return i else: count += 1 raise IndexError('list index out of range') def _full_list(self): out_list = [element for element in self._elements if element.tag == self._spec.name] for scoped_elements in self._scoped_elements.values(): out_list += scoped_elements[:] return out_list def clear(self): for child in self._full_list(): child.remove() def __getitem__(self, index): if (isinstance(index, str) and self._spec.identifier and constants.PREFIX_SEPARATOR in index): scope_name = index.split(constants.PREFIX_SEPARATOR)[0] scoped_elements = self._scoped_elements[scope_name] try: return scoped_elements[index[(len(scope_name) + 1):]] except KeyError: # Re-raise so that the error shows the full, un-stripped index string raise self._identifier_not_found_error(index) # pylint: disable=raise-missing-from elif isinstance(index, slice) or (isinstance(index, int) and index < 0): return self._full_list()[index] else: return self._elements[self._find_index(index)] def __delitem__(self, index): found_index = self._find_index(index) self._elements[found_index].remove() def __str__(self): return str( [element.to_xml_string( prefix_root=self.namescope, self_only=True, pretty_print=False) for element in self._full_list()]) def __repr__(self): return 'MJCF Elements List: ' + str(self) # This restores @property back to Python's built-in one. del property del _raw_property
dm_control-main
dm_control/mjcf/element.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 that generated XML string is valid.""" import os from absl.testing import absltest from dm_control.mjcf import parser from dm_control.mujoco import wrapper ASSETS_DIR = os.path.join(os.path.dirname(__file__), 'test_assets') _ARENA_XML = os.path.join(ASSETS_DIR, 'arena.xml') _LEGO_BRICK_XML = os.path.join(ASSETS_DIR, 'lego_brick.xml') _ROBOT_XML = os.path.join(ASSETS_DIR, 'robot_arm.xml') def validate(xml_string): """Validates that an XML string is a valid MJCF. Validation is performed by constructing Mujoco model from the string. The construction process contains compilation and validation phases by Mujoco engine, the best validation tool we have access to. Args: xml_string: XML string to validate """ mjmodel = wrapper.MjModel.from_xml_string(xml_string) wrapper.MjData(mjmodel) class XMLValidationTest(absltest.TestCase): def testXmlAttach(self): robot_arm = parser.from_file(_ROBOT_XML) arena = parser.from_file(_ARENA_XML) lego = parser.from_file(_LEGO_BRICK_XML) # validate MJCF strings before changing them validate(robot_arm.to_xml_string()) validate(arena.to_xml_string()) validate(lego.to_xml_string()) # combine objects in complex scene robot_arm.find('site', 'fingertip1').attach(lego) arena.worldbody.attach(robot_arm) # validate validate(arena.to_xml_string()) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/mjcf/xml_validation_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. # ============================================================================ """Functions for parsing XML into an MJCF object model.""" import os import sys from dm_control.mjcf import constants from dm_control.mjcf import debugging from dm_control.mjcf import element from lxml import etree from dm_control.utils import io as resources def from_xml_string(xml_string, escape_separators=False, model_dir='', resolve_references=True, assets=None): """Parses an XML string into an MJCF object model. Args: xml_string: An XML string representing an MJCF model. escape_separators: (optional) A boolean, whether to replace '/' characters in element identifiers. If `False`, any '/' present in the XML causes a ValueError to be raised. model_dir: (optional) Path to the directory containing the model XML file. This is used to prefix the paths of all asset files. resolve_references: (optional) A boolean indicating whether the parser should attempt to resolve reference attributes to a corresponding element. assets: (optional) A dictionary of pre-loaded assets, of the form `{filename: bytestring}`. If present, PyMJCF will search for assets in this dictionary before attempting to load them from the filesystem. Returns: An `mjcf.RootElement`. """ xml_root = etree.fromstring(xml_string) return _parse(xml_root, escape_separators, model_dir=model_dir, resolve_references=resolve_references, assets=assets) def from_file(file_handle, escape_separators=False, model_dir='', resolve_references=True, assets=None): """Parses an XML file into an MJCF object model. Args: file_handle: A Python file-like handle. escape_separators: (optional) A boolean, whether to replace '/' characters in element identifiers. If `False`, any '/' present in the XML causes a ValueError to be raised. model_dir: (optional) Path to the directory containing the model XML file. This is used to prefix the paths of all asset files. resolve_references: (optional) A boolean indicating whether the parser should attempt to resolve reference attributes to a corresponding element. assets: (optional) A dictionary of pre-loaded assets, of the form `{filename: bytestring}`. If present, PyMJCF will search for assets in this dictionary before attempting to load them from the filesystem. Returns: An `mjcf.RootElement`. """ xml_root = etree.parse(file_handle).getroot() return _parse(xml_root, escape_separators, model_dir=model_dir, resolve_references=resolve_references, assets=assets) def from_path(path, escape_separators=False, resolve_references=True, assets=None): """Parses an XML file into an MJCF object model. Args: path: A path to an XML file. This path should be loadable using `resources.GetResource`. escape_separators: (optional) A boolean, whether to replace '/' characters in element identifiers. If `False`, any '/' present in the XML causes a ValueError to be raised. resolve_references: (optional) A boolean indicating whether the parser should attempt to resolve reference attributes to a corresponding element. assets: (optional) A dictionary of pre-loaded assets, of the form `{filename: bytestring}`. If present, PyMJCF will search for assets in this dictionary before attempting to load them from the filesystem. Returns: An `mjcf.RootElement`. """ model_dir, _ = os.path.split(path) contents = resources.GetResource(path) xml_root = etree.fromstring(contents) return _parse(xml_root, escape_separators, model_dir=model_dir, resolve_references=resolve_references, assets=assets) def _parse(xml_root, escape_separators=False, model_dir='', resolve_references=True, assets=None): """Parses a complete MJCF model from an XML. Args: xml_root: An `etree.Element` object. escape_separators: (optional) A boolean, whether to replace '/' characters in element identifiers. If `False`, any '/' present in the XML causes a ValueError to be raised. model_dir: (optional) Path to the directory containing the model XML file. This is used to prefix the paths of all asset files. resolve_references: (optional) A boolean indicating whether the parser should attempt to resolve reference attributes to a corresponding element. assets: (optional) A dictionary of pre-loaded assets, of the form `{filename: bytestring}`. If present, PyMJCF will search for assets in this dictionary before attempting to load them from the filesystem. Returns: An `mjcf.RootElement`. Raises: ValueError: If `xml_root`'s tag is not 'mujoco.*'. """ assets = assets or {} if not xml_root.tag.startswith('mujoco'): raise ValueError('Root element of the XML should be <mujoco.*>: got <{}>' .format(xml_root.tag)) with debugging.freeze_current_stack_trace(): # Recursively parse any included XML files. to_include = [] for include_tag in xml_root.findall('include'): try: # First look for the path to the included XML file in the assets dict. path_or_xml_string = assets[include_tag.attrib['file']] parsing_func = from_xml_string except KeyError: # If it's not present in the assets dict then attempt to load the XML # from the filesystem. path_or_xml_string = os.path.join(model_dir, include_tag.attrib['file']) parsing_func = from_path included_mjcf = parsing_func( path_or_xml_string, escape_separators=escape_separators, resolve_references=resolve_references, assets=assets) to_include.append(included_mjcf) # We must remove <include/> tags before parsing the main XML file, since # these are a schema violation. xml_root.remove(include_tag) # Parse the main XML file. try: model = xml_root.attrib.pop('model') except KeyError: model = None mjcf_root = element.RootElement( model=model, model_dir=model_dir, assets=assets) _parse_children(xml_root, mjcf_root, escape_separators) # Merge in the included XML files. for included_mjcf in to_include: # The included MJCF might have been automatically assigned a model name # that conficts with that of `mjcf_root`, so we override it here. included_mjcf.model = mjcf_root.model mjcf_root.include_copy(included_mjcf) if resolve_references: mjcf_root.resolve_references() return mjcf_root def _parse_children(xml_element, mjcf_element, escape_separators=False): """Parses all children of a given XML element into an MJCF element. Args: xml_element: The source `etree.Element` object. mjcf_element: The target `mjcf.Element` object. escape_separators: (optional) A boolean, whether to replace '/' characters in element identifiers. If `False`, any '/' present in the XML causes a ValueError to be raised. """ for xml_child in xml_element: if xml_child.tag is etree.Comment or xml_child.tag is etree.PI: continue try: child_spec = mjcf_element.spec.children[xml_child.tag] if escape_separators: attributes = {} for name, value in xml_child.attrib.items(): new_value = value.replace( constants.PREFIX_SEPARATOR_ESCAPE, constants.PREFIX_SEPARATOR_ESCAPE * 2) new_value = new_value.replace( constants.PREFIX_SEPARATOR, constants.PREFIX_SEPARATOR_ESCAPE) attributes[name] = new_value else: attributes = dict(xml_child.attrib) if child_spec.repeated or child_spec.on_demand: mjcf_child = mjcf_element.add(xml_child.tag, **attributes) else: mjcf_child = getattr(mjcf_element, xml_child.tag) mjcf_child.set_attributes(**attributes) except: # pylint: disable=bare-except err_type, err, traceback = sys.exc_info() raise err_type( f'Line {xml_child.sourceline}: error while parsing element ' f'<{xml_child.tag}>: {err}').with_traceback(traceback) _parse_children(xml_child, mjcf_child, escape_separators)
dm_control-main
dm_control/mjcf/parser.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. # ============================================================================ """Saves Mujoco models with relevant assets in a .zip file.""" import os import zipfile from dm_control.mjcf import constants def export_with_assets_as_zip(mjcf_model, out_dir, model_name=None, *, precision=constants.XML_DEFAULT_PRECISION, zero_threshold=0): """Saves mjcf_model and all its assets as a .zip file in the given directory. Creates a .zip file named `model_name`.zip in the specified `out_dir`, and a directory inside of this file named `model_name`. The MJCF XML is written into this directory with the name `model_name`.xml, and all the assets are also written into this directory without changing their names. Args: mjcf_model: `mjcf.RootElement` instance to export. out_dir: Directory to save the .zip file. Will be created if it does not already exist. model_name: (Optional) Name of the .zip file, the name of the directory inside the .zip root containing the model and assets, and name of the XML file inside this directory. Defaults to the MJCF model name (`mjcf_model.model`). precision: (optional) Number of digits to output for floating point quantities. zero_threshold: (optional) When outputting XML, floating point quantities whose absolute value falls below this threshold will be treated as zero. """ if model_name is None: model_name = mjcf_model.model xml_name = model_name + '.xml' zip_name = model_name + '.zip' files_to_zip = mjcf_model.get_assets() files_to_zip[xml_name] = mjcf_model.to_xml_string( precision=precision, zero_threshold=zero_threshold) if not os.path.exists(out_dir): os.makedirs(out_dir) with zipfile.ZipFile(os.path.join(out_dir, zip_name), 'w') as zip_file: for filename, contents in files_to_zip.items(): zip_file.writestr(os.path.join(model_name, filename), contents)
dm_control-main
dm_control/mjcf/export_with_assets_as_zip.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 `dm_control.mjcf.physics`.""" import copy import os import pickle from absl.testing import absltest from absl.testing import parameterized from dm_control import mjcf from dm_control.mjcf import physics as mjcf_physics from dm_control.mujoco.wrapper import mjbindings import mock import mujoco import numpy as np mjlib = mjbindings.mjlib ARM_MODEL = os.path.join(os.path.dirname(__file__), 'test_assets/robot_arm.xml') class PhysicsTest(parameterized.TestCase): """Tests for `mjcf.Physics`.""" def setUp(self): super().setUp() self.model = mjcf.from_path(ARM_MODEL) self.physics = mjcf.Physics.from_xml_string( self.model.to_xml_string(), assets=self.model.get_assets()) self.random = np.random.RandomState(0) def sample_elements(self, namespace, single_element): all_elements = self.model.find_all(namespace) if single_element: # A single randomly chosen element from this namespace. elements = self.random.choice(all_elements) full_identifiers = elements.full_identifier else: # A random permutation of all elements in this namespace. elements = self.random.permutation(all_elements) full_identifiers = [element.full_identifier for element in elements] return elements, full_identifiers def test_construct_and_reload_from_mjcf_model(self): physics = mjcf.Physics.from_mjcf_model(self.model) physics.data.time = 1. physics.reload_from_mjcf_model(self.model) self.assertEqual(physics.data.time, 0.) @parameterized.parameters( # namespace, single_element ('geom', True), ('geom', False), ('joint', True), ('joint', False), ('actuator', True), ('actuator', False)) def test_id(self, namespace, single_element): elements, full_identifiers = self.sample_elements(namespace, single_element) actual = self.physics.bind(elements).element_id if single_element: expected = self.physics.model.name2id(full_identifiers, namespace) else: expected = [self.physics.model.name2id(name, namespace) for name in full_identifiers] np.testing.assert_array_equal(expected, actual) def assertCanGetAndSetBindingArray( self, binding, attribute_name, named_indexer, full_identifiers): # Read the values using the binding attribute. actual = getattr(binding, attribute_name) # Read them using the normal named indexing machinery. expected = named_indexer[full_identifiers] np.testing.assert_array_equal(expected, actual) # Assign an array of unique values to the attribute. expected = np.arange(actual.size, dtype=actual.dtype).reshape(actual.shape) setattr(binding, attribute_name, expected) # Read the values back using the normal named indexing machinery. actual = named_indexer[full_identifiers] np.testing.assert_array_equal(expected, actual) @parameterized.parameters( # namespace, attribute_name, model_or_data, field_name, single_element ('geom', 'xpos', 'data', 'geom_xpos', True), ('geom', 'xpos', 'data', 'geom_xpos', False), ('joint', 'qpos', 'data', 'qpos', True), ('joint', 'qpos', 'data', 'qpos', False), ('site', 'rgba', 'model', 'site_rgba', True), ('site', 'rgba', 'model', 'site_rgba', False), ('sensor', 'sensordata', 'data', 'sensordata', True), ('sensor', 'sensordata', 'data', 'sensordata', False)) def test_attribute_access(self, namespace, attribute_name, model_or_data, field_name, single_element): elements, full_identifiers = self.sample_elements(namespace, single_element) named_indexer = getattr(getattr(self.physics.named, model_or_data), field_name) binding = self.physics.bind(elements) self.assertCanGetAndSetBindingArray( binding, attribute_name, named_indexer, full_identifiers) @parameterized.parameters( # namespace, attribute_name, model_or_data, field_name, single_element, # column_index ('geom', 'pos', 'model', 'geom_pos', True, None), ('geom', 'pos', 'model', 'geom_pos', False, None), ('geom', 'pos', 'model', 'geom_pos', True, 1), ('geom', 'pos', 'model', 'geom_pos', False, 1), ('geom', 'pos', 'model', 'geom_pos', True, 'y'), ('geom', 'pos', 'model', 'geom_pos', False, 'y'), ('geom', 'pos', 'model', 'geom_pos', True, slice(0, None, 2)), ('geom', 'pos', 'model', 'geom_pos', False, slice(0, None, 2)), ('geom', 'pos', 'model', 'geom_pos', True, [0, 2]), ('geom', 'pos', 'model', 'geom_pos', False, [0, 2]), ('geom', 'pos', 'model', 'geom_pos', True, ['x', 'z']), ('geom', 'pos', 'model', 'geom_pos', False, ['x', 'z']), ('joint', 'qpos', 'data', 'qpos', True, None), ('joint', 'qpos', 'data', 'qpos', False, None)) def test_indexing(self, namespace, attribute_name, model_or_data, field_name, single_element, column_index): elements, full_identifiers = self.sample_elements(namespace, single_element) named_indexer = getattr(getattr(self.physics.named, model_or_data), field_name) binding = self.physics.bind(elements) if column_index is not None: binding_index = (attribute_name, column_index) try: named_index = np.ix_(full_identifiers, column_index) except ValueError: named_index = (full_identifiers, column_index) else: binding_index = attribute_name named_index = full_identifiers # Read the values by indexing the binding. actual = binding[binding_index] # Read them using the normal named indexing machinery. expected = named_indexer[named_index] np.testing.assert_array_equal(expected, actual) # Write an array of unique values into the binding. expected = np.arange(actual.size, dtype=actual.dtype).reshape(actual.shape) binding[binding_index] = expected # Read the values back using the normal named indexing machinery. actual = named_indexer[named_index] np.testing.assert_array_equal(expected, actual) def test_bind_mocap_body(self): pos = [1, 2, 3] quat = [1, 0, 0, 0] model = mjcf.RootElement() # Bodies are non-mocap by default. normal_body = model.worldbody.add('body', pos=pos, quat=quat) mocap_body = model.worldbody.add('body', pos=pos, quat=quat, mocap='true') physics = mjcf.Physics.from_xml_string(model.to_xml_string()) binding = physics.bind(mocap_body) np.testing.assert_array_equal(pos, binding.mocap_pos) np.testing.assert_array_equal(quat, binding.mocap_quat) new_pos = [4, 5, 6] new_quat = [0, 1, 0, 0] binding.mocap_pos = new_pos binding.mocap_quat = new_quat np.testing.assert_array_equal( new_pos, physics.named.data.mocap_pos[mocap_body.full_identifier]) np.testing.assert_array_equal( new_quat, physics.named.data.mocap_quat[mocap_body.full_identifier]) with self.assertRaises(AttributeError): _ = physics.bind(normal_body).mocap_pos with self.assertRaisesRegex( ValueError, 'Cannot bind to a collection containing multiple element types'): physics.bind([mocap_body, normal_body]) def test_bind_worldbody(self): expected_mass = 10 model = mjcf.RootElement() child = model.worldbody.add('body') child.add('geom', type='sphere', size=[0.1], mass=expected_mass) physics = mjcf.Physics.from_mjcf_model(model) mass = physics.bind(model.worldbody).subtreemass self.assertEqual(mass, expected_mass) def test_bind_stateful_actuator(self): model = mjcf.RootElement() body = model.worldbody.add('body') body.add('joint', name='joint') body.add('geom', type='sphere', size=[1]) model.actuator.add( 'general', name='act1', joint='joint', dyntype='integrator') physics = mjcf.Physics.from_mjcf_model(model) actuator = model.find('actuator', 'act1') binding = physics.bind(actuator) # This used to crash self.assertEqual(0, binding.act) def test_caching(self): all_joints = self.model.find_all('joint') original = self.physics.bind(all_joints) cached = self.physics.bind(all_joints) self.assertIs(cached, original) different_order = self.physics.bind(all_joints[::-1]) self.assertIsNot(different_order, original) # Reloading the `Physics` instance should clear the cache. self.physics.reload_from_xml_string( self.model.to_xml_string(), assets=self.model.get_assets()) after_reload = self.physics.bind(all_joints) self.assertIsNot(after_reload, original) def test_exceptions(self): joint = self.model.find_all('joint')[0] geom = self.model.find_all('geom')[0] with self.assertRaisesRegex( ValueError, 'Cannot bind to a collection containing multiple element types'): self.physics.bind([joint, geom]) with self.assertRaisesRegex(ValueError, 'cannot be bound to physics'): mjcf.physics.Binding(self.physics, 'invalid_namespace', 'whatever') binding = self.physics.bind(joint) with self.assertRaisesRegex(AttributeError, 'does not have attribute'): getattr(binding, 'invalid_attribute') def test_dirty(self): self.physics.forward() self.assertFalse(self.physics.is_dirty) joints, _ = self.sample_elements('joint', single_element=False) sites, _ = self.sample_elements('site', single_element=False) # Accessing qpos shouldn't trigger a recalculation. _ = self.physics.bind(joints).qpos self.assertFalse(self.physics.is_dirty) # Reassignments to qpos should cause the physics to become dirty. site_xpos_before = copy.deepcopy(self.physics.bind(sites).xpos) self.physics.bind(joints).qpos += 0.5 self.assertTrue(self.physics.is_dirty) # Accessing stuff in mjModel shouldn't trigger a recalculation. _ = self.physics.bind(sites).pos self.assertTrue(self.physics.is_dirty) # Accessing stuff in mjData should trigger a recalculation. actual_sites_xpos_after = copy.deepcopy(self.physics.bind(sites).xpos) self.assertFalse(self.physics.is_dirty) self.assertFalse((actual_sites_xpos_after == site_xpos_before).all()) # Automatic recalculation should render `forward` a no-op here. self.physics.forward() expected_sites_xpos_after = self.physics.bind(sites).xpos np.testing.assert_array_equal(actual_sites_xpos_after, expected_sites_xpos_after) # `forward` should not be called on subsequent queries to xpos. with mock.patch.object( self.physics, 'forward', side_effect=self.physics.forward) as mock_forward: _ = self.physics.bind(sites).xpos mock_forward.assert_not_called() @parameterized.parameters(True, False) def test_assign_while_dirty(self, assign_via_slice): actuators = self.model.find_all('actuator') if assign_via_slice: self.physics.bind(actuators).ctrl[:] = 0.75 else: self.physics.bind(actuators).ctrl = 0.75 self.assertTrue(self.physics.is_dirty) self.physics.step() self.assertTrue(self.physics.is_dirty) sensors = self.model.find_all('sensor') if assign_via_slice: self.physics.bind(sensors).sensordata[:] = 12345 else: self.physics.bind(sensors).sensordata = 12345 self.assertFalse(self.physics.is_dirty) np.testing.assert_array_equal( self.physics.bind(sensors).sensordata, [12345] * len(self.physics.bind(sensors).sensordata)) def test_setitem_on_binding_attr(self): bodies, _ = self.sample_elements('body', single_element=False) xfrc_binding = self.physics.bind(bodies).xfrc_applied xfrc_binding[:, 1] = list(range(len(bodies))) for i, body in enumerate(bodies): self.assertEqual(xfrc_binding[i, 1], i) self.assertEqual( self.physics.named.data.xfrc_applied[body.full_identifier][1], i) xfrc_binding[:, 1] *= 2 for i, body in enumerate(bodies): self.assertEqual(xfrc_binding[i, 1], 2 * i) self.assertEqual( self.physics.named.data.xfrc_applied[body.full_identifier][1], 2 * i) xfrc_binding[[1, 3, 5], 2] = 42 for i, body in enumerate(bodies): actual_value = ( self.physics.named.data.xfrc_applied[body.full_identifier][2]) if i in [1, 3, 5]: self.assertEqual(actual_value, 42) else: self.assertNotEqual(actual_value, 42) # Bind to a single element. single_binding = self.physics.bind(bodies[0]).xfrc_applied single_binding[:2] = 55 np.testing.assert_array_equal(single_binding[:2], [55, 55]) np.testing.assert_array_equal( self.physics.named.data.xfrc_applied[bodies[0].full_identifier][:2], [55, 55]) def test_empty_binding(self): binding = self.physics.bind([]) self.assertEqual(binding.xpos.shape, (0,)) with self.assertRaisesWithLiteralMatch( ValueError, 'Cannot assign a value to an empty binding.'): binding.xpos = 5 @parameterized.parameters([('data', 'act'), ('data', 'act_dot')]) def test_actuator_state_binding(self, model_or_data, attribute_name): def make_model_with_mixed_actuators(): actuators = [] is_stateful = [] root = mjcf.RootElement() body = root.worldbody.add('body') body.add('geom', type='sphere', size=[0.1]) slider = body.add('joint', type='slide', name='slide_joint') # Third-order `general` actuator. actuators.append( root.actuator.add( 'general', dyntype='integrator', biastype='affine', dynprm=[1, 0, 0], joint=slider, name='general_act')) is_stateful.append(True) # Cylinder actuators are also third-order. actuators.append( root.actuator.add('cylinder', joint=slider, name='cylinder_act')) is_stateful.append(True) # A second-order actuator, added after the third-order actuators. The # actuators will be automatically reordered in the generated XML so that # the second-order actuator comes first. actuators.append( root.actuator.add('velocity', joint=slider, name='velocity_act')) is_stateful.append(False) return root, actuators, is_stateful model, actuators, is_stateful = make_model_with_mixed_actuators() physics = mjcf.Physics.from_mjcf_model(model) binding = physics.bind(actuators) named_indexer = getattr( getattr(physics.named, model_or_data), attribute_name) stateful_actuator_names = [ actuator.full_identifier for actuator, stateful in zip(actuators, is_stateful) if stateful] self.assertCanGetAndSetBindingArray( binding, attribute_name, named_indexer, stateful_actuator_names) def test_bind_stateless_actuators_only(self): actuators = [] root = mjcf.RootElement() body = root.worldbody.add('body') body.add('geom', type='sphere', size=[0.1]) slider = body.add('joint', type='slide', name='slide_joint') actuators.append( root.actuator.add('velocity', joint=slider, name='velocity_act')) actuators.append( root.actuator.add('motor', joint=slider, name='motor_act')) # `act` should be an empty array if there are no stateful actuators. physics = mjcf.Physics.from_mjcf_model(root) self.assertEqual(physics.bind(actuators).act.shape, (0,)) def make_simple_model(self): def add_submodel(root): body = root.worldbody.add('body') geom = body.add('geom', type='ellipsoid', size=[0.1, 0.2, 0.3]) site = body.add('site', type='sphere', size=[0.1]) return body, geom, site root = mjcf.RootElement() add_submodel(root) add_submodel(root) return root def quat2mat(self, quat): result = np.empty(9, dtype=np.double) mujoco.mju_quat2Mat(result, np.asarray(quat)) return result @parameterized.parameters(['body', 'geom', 'site']) def test_write_to_pos(self, entity_type): root = self.make_simple_model() entity1, entity2 = root.find_all(entity_type) physics = mjcf.Physics.from_mjcf_model(root) first = physics.bind(entity1) second = physics.bind(entity2) # Initially both entities should be 'sameframe' self.assertEqual(first.sameframe, 1) self.assertEqual(second.sameframe, 1) # Assigning to `pos` should disable 'sameframe' only for that entity. new_pos = (0., 0., 0.1) first.pos = new_pos self.assertEqual(first.sameframe, 0) self.assertEqual(second.sameframe, 1) # `xpos` should reflect the new position. np.testing.assert_array_equal(first.xpos, new_pos) # Writing into the `pos` array should also disable 'sameframe'. new_x = -0.1 pos_array = second.pos pos_array[0] = new_x self.assertEqual(second.sameframe, 0) # `xpos` should reflect the new position. self.assertEqual(second.xpos[0], new_x) @parameterized.parameters(['body', 'geom', 'site']) def test_write_to_quat(self, entity_type): root = self.make_simple_model() entity1, entity2 = root.find_all(entity_type) physics = mjcf.Physics.from_mjcf_model(root) first = physics.bind(entity1) second = physics.bind(entity2) # Initially both entities should be 'sameframe' self.assertEqual(first.sameframe, 1) self.assertEqual(second.sameframe, 1) # Assigning to `quat` should disable 'sameframe' only for that entity. new_quat = (0., 0., 0., 1.) first.quat = new_quat self.assertEqual(first.sameframe, 0) self.assertEqual(second.sameframe, 1) # `xmat` should reflect the new quaternion. np.testing.assert_allclose(first.xmat, self.quat2mat(new_quat)) # Writing into the `quat` array should also disable 'sameframe'. new_w = -1. quat_array = second.quat quat_array[0] = new_w self.assertEqual(second.sameframe, 0) # `xmat` should reflect the new quaternion. np.testing.assert_allclose(second.xmat, self.quat2mat(quat_array)) def test_write_to_ipos(self): root = self.make_simple_model() entity1, entity2 = root.find_all('body') physics = mjcf.Physics.from_mjcf_model(root) first = physics.bind(entity1) second = physics.bind(entity2) # Initially both bodies should be 'simple' and 'sameframe' self.assertEqual(first.simple, 1) self.assertEqual(first.sameframe, 1) self.assertEqual(second.simple, 1) self.assertEqual(second.sameframe, 1) # Assigning to `ipos` should disable 'simple' and 'sameframe' only for that # body. new_ipos = (0., 0., 0.1) first.ipos = new_ipos self.assertEqual(first.simple, 0) self.assertEqual(first.sameframe, 0) self.assertEqual(second.simple, 1) self.assertEqual(second.sameframe, 1) # `xipos` should reflect the new position. np.testing.assert_array_equal(first.xipos, new_ipos) # Writing into the `ipos` array should also disable 'simple' and # 'sameframe'. new_x = -0.1 ipos_array = second.ipos ipos_array[0] = new_x self.assertEqual(second.simple, 0) self.assertEqual(second.sameframe, 0) # `xipos` should reflect the new position. self.assertEqual(second.xipos[0], new_x) def test_write_to_iquat(self): root = self.make_simple_model() entity1, entity2 = root.find_all('body') physics = mjcf.Physics.from_mjcf_model(root) first = physics.bind(entity1) second = physics.bind(entity2) # Initially both bodies should be 'simple' and 'sameframe' self.assertEqual(first.simple, 1) self.assertEqual(first.sameframe, 1) self.assertEqual(second.simple, 1) self.assertEqual(second.sameframe, 1) # Assigning to `iquat` should disable 'simple' and 'sameframe' only for that # body. new_iquat = (0., 0., 0., 1.) first.iquat = new_iquat self.assertEqual(first.simple, 0) self.assertEqual(first.sameframe, 0) self.assertEqual(second.simple, 1) self.assertEqual(second.sameframe, 1) # `ximat` should reflect the new quaternion. np.testing.assert_allclose(first.ximat, self.quat2mat(new_iquat)) # Writing into the `iquat` array should also disable 'simple' and # 'sameframe'. new_w = -0.1 iquat_array = second.iquat iquat_array[0] = new_w self.assertEqual(second.simple, 0) self.assertEqual(second.sameframe, 0) # `ximat` should reflect the new quaternion. np.testing.assert_allclose(second.ximat, self.quat2mat(iquat_array)) @parameterized.parameters([dict(order='C'), dict(order='F')]) def test_copy_synchronizing_array_wrapper(self, order): root = self.make_simple_model() physics = mjcf.Physics.from_mjcf_model(root) xpos_view = physics.bind(root.find_all('body')).xpos xpos_view_copy = xpos_view.copy(order=order) np.testing.assert_array_equal(xpos_view, xpos_view_copy) self.assertFalse(np.may_share_memory(xpos_view, xpos_view_copy), msg='Original and copy should not share memory.') self.assertIs(type(xpos_view_copy), np.ndarray) # Check that `order=` is respected. if order == 'C': self.assertTrue(xpos_view_copy.flags.c_contiguous) self.assertFalse(xpos_view_copy.flags.f_contiguous) elif order == 'F': self.assertFalse(xpos_view_copy.flags.c_contiguous) self.assertTrue(xpos_view_copy.flags.f_contiguous) # The copy should be writeable. self.assertTrue(xpos_view_copy.flags.writeable) new_value = 99. xpos_view_copy[0, -1] = new_value self.assertEqual(xpos_view_copy[0, -1], new_value) def test_error_when_pickling_synchronizing_array_wrapper(self): root = self.make_simple_model() physics = mjcf.Physics.from_mjcf_model(root) xpos_view = physics.bind(root.find_all('body')).xpos with self.assertRaisesWithLiteralMatch( NotImplementedError, mjcf_physics._PICKLING_NOT_SUPPORTED.format(type=type(xpos_view))): pickle.dumps(xpos_view) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/mjcf/physics_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. # ============================================================================ """Helpers for MJCF elements to interact with `dm_control.mujoco.Physics`.""" import collections import re import weakref from absl import flags from absl import logging from dm_control import mujoco from dm_control.mjcf import constants from dm_control.mjcf import debugging from dm_control.mujoco.wrapper.mjbindings import sizes import numpy as np FLAGS = flags.FLAGS flags.DEFINE_boolean('pymjcf_log_xml', False, 'Whether to log the generated XML on model compilation.') _XML_PRINT_SHARD_SIZE = 100 _PICKLING_NOT_SUPPORTED = 'Objects of type {type} cannot be pickled.' _Attribute = collections.namedtuple( 'Attribute', ('name', 'get_named_indexer', 'triggers_dirty', 'disable_on_write')) # Object types that can be used to index into numpy arrays. _TUPLE = tuple _ARRAY_LIKE = (np.ndarray, list) # We don't need to differentiate between other types of index, e.g. integers, # slices. def _get_index_type(index): for index_type in (_TUPLE, _ARRAY_LIKE): if isinstance(index, index_type): return index_type def _pymjcf_log_xml(): """Returns True if the generated XML should be logged on model compilation.""" if FLAGS.is_parsed(): return FLAGS.pymjcf_log_xml else: return FLAGS['pymjcf_log_xml'].default def _get_attributes(size_names, strip_prefixes): """Creates a dict of valid attribute from Mujoco array size name.""" strip_regex = re.compile(r'\A({})_'.format('|'.join(strip_prefixes))) strip = lambda string: strip_regex.sub('', string) out = {} for name, size in sizes.array_sizes['mjdata'].items(): if size[0] in size_names: attrib_name = strip(name) named_indexer_getter = ( lambda physics, name=name: getattr(physics.named.data, name)) triggers_dirty = attrib_name in constants.MJDATA_TRIGGERS_DIRTY out[attrib_name] = _Attribute( name=attrib_name, get_named_indexer=named_indexer_getter, triggers_dirty=triggers_dirty, disable_on_write=()) for name, size in sizes.array_sizes['mjmodel'].items(): if size[0] in size_names: attrib_name = strip(name) named_indexer_getter = ( lambda physics, name=name: getattr(physics.named.model, name)) triggers_dirty = attrib_name not in constants.MJMODEL_DOESNT_TRIGGER_DIRTY disable_on_write = constants.MJMODEL_DISABLE_ON_WRITE.get(name, ()) out[attrib_name] = _Attribute( name=attrib_name, get_named_indexer=named_indexer_getter, triggers_dirty=triggers_dirty, disable_on_write=disable_on_write) return out _ATTRIBUTES = { 'actuator': _get_attributes(['na', 'nu'], strip_prefixes=['actuator']), 'body': _get_attributes(['nbody'], strip_prefixes=['body']), 'mocap_body': _get_attributes(['nbody', 'nmocap'], strip_prefixes=['body']), 'camera': _get_attributes(['ncam'], strip_prefixes=['cam']), 'equality': _get_attributes(['neq'], strip_prefixes=['eq']), 'geom': _get_attributes(['ngeom'], strip_prefixes=['geom']), 'hfield': _get_attributes(['nhfield'], strip_prefixes=['hfield']), 'joint': _get_attributes(['nq', 'nv', 'njnt'], strip_prefixes=['jnt', 'dof']), 'light': _get_attributes(['nlight'], strip_prefixes=['light']), 'material': _get_attributes(['nmat'], strip_prefixes=['mat']), 'mesh': _get_attributes(['nmesh'], strip_prefixes=['mesh']), 'numeric': _get_attributes(['nnumeric', 'nnumericdata'], strip_prefixes=['numeric']), 'sensor': _get_attributes(['nsensor', 'nsensordata'], strip_prefixes=['sensor']), 'site': _get_attributes(['nsite'], strip_prefixes=['site']), 'tendon': _get_attributes(['ntendon'], strip_prefixes=['tendon', 'ten']), 'text': _get_attributes(['ntext', 'ntextdata'], strip_prefixes=['text']), 'texture': _get_attributes(['ntex'], strip_prefixes=['tex']), } def names_from_elements(mjcf_elements): """Returns `namespace` and `named_index` for `mjcf_elements`. Args: mjcf_elements: Either an `mjcf.Element`, or an iterable of `mjcf.Element` of the same kind. Returns: A tuple of `(namespace, named_indices)` where -`namespace` is the Mujoco element type (eg: 'geom', 'body', etc.) -`named_indices` are the names of `mjcf_elements`, either as a single string or an iterable of strings depending on whether `mjcf_elements` was an `mjcf.Element` or an iterable of `mjcf_Element`s. Raises: ValueError: If `mjcf_elements` cannot be bound to this Physics. """ if isinstance(mjcf_elements, collections.abc.Iterable): elements_tuple = tuple(mjcf_elements) if elements_tuple: namespace = _get_namespace(elements_tuple[0]) else: return None, None for element in elements_tuple: element_namespace = _get_namespace(element) if element_namespace != namespace: raise ValueError('Cannot bind to a collection containing multiple ' 'element types ({!r} != {!r}).' .format(element_namespace, namespace)) named_index = [element.full_identifier for element in elements_tuple] else: namespace = _get_namespace(mjcf_elements) named_index = mjcf_elements.full_identifier return namespace, named_index class SynchronizingArrayWrapper(np.ndarray): """A non-contiguous view of an ndarray that synchronizes with the original. Note: this class should not be instantiated directly. """ __slots__ = ( '_backing_array', '_backing_index', '_backing_index_is_array_like', '_physics', '_triggers_dirty', '_disable_on_write', ) def __new__(cls, backing_array, backing_index, physics, triggers_dirty, disable_on_write): obj = backing_array[backing_index].view(SynchronizingArrayWrapper) # pylint: disable=protected-access obj._backing_array = backing_array obj._backing_index = backing_index # Performance optimization: avoid repeatedly checking the type of the # backing index. backing_index_type = _get_index_type(backing_index) obj._backing_index_is_array_like = backing_index_type is _ARRAY_LIKE obj._physics = physics obj._triggers_dirty = triggers_dirty obj._disable_on_write = disable_on_write # pylint: enable=protected-access return obj def _synchronize_from_backing_array(self): if self._physics.is_dirty and not self._triggers_dirty: self._physics.forward() updated_values = self._backing_array[self._backing_index] # Faster than `super(...).__setitem__(slice(None), updated_values)` np.copyto(self, updated_values) def copy(self, order='C'): return np.copy(self, order=order) def __copy__(self): return self.copy() def __deepcopy__(self, memo): return self.copy() def __reduce__(self): raise NotImplementedError(_PICKLING_NOT_SUPPORTED.format(type=type(self))) def __setitem__(self, index, value): if self._physics.is_dirty and not self._triggers_dirty: self._physics.forward() super().__setitem__(index, value) # Performance optimization: avoid repeatedly checking the type of the index. index_type = _get_index_type(index) if self._backing_index_is_array_like: if index_type is _TUPLE: resolved_index = (self._backing_index[index[0]],) + index[1:] else: resolved_index = self._backing_index[index] self._backing_array[resolved_index] = value for backing_array, backing_index in self._disable_on_write: if index_type is _TUPLE: # We only need the row component of the index. resolved_index = backing_index[index[0]] elif index_type is _ARRAY_LIKE: resolved_index = backing_index[index] else: # If it is only an index into the columns of the backing array then we # just discard it and use the backing index. resolved_index = backing_index backing_array[resolved_index] = 0 if self._triggers_dirty: self._physics.mark_as_dirty() def __setslice__(self, start, stop, value): self.__setitem__(slice(start, stop, None), value) class Binding: """Binding between a mujoco.Physics and an mjcf.Element or a list of Elements. This object should normally be created by calling `physics.bind(element)` where `physics` is an instance of `mjcf.Physics`. See docstring for that function for details. """ __slots__ = ( '_attributes', '_physics', '_namespace', '_named_index', '_named_indexers', '_getattr_cache', '_array_index_cache', ) def __init__(self, physics, namespace, named_index): try: self._attributes = _ATTRIBUTES[namespace] except KeyError: raise ValueError('elements of type {!r} cannot be bound to physics' .format(namespace)) from None self._physics = physics self._namespace = namespace self._named_index = named_index self._named_indexers = {} self._getattr_cache = {} self._array_index_cache = {} def __dir__(self): return sorted(set(dir(type(self))).union(self._attributes)) def _get_cached_named_indexer(self, name): named_indexer = self._named_indexers.get(name) if named_indexer is None: try: named_indexer = self._attributes[name].get_named_indexer(self._physics) self._named_indexers[name] = named_indexer except KeyError as e: raise AttributeError('bound element <{}> does not have attribute {!r}' .format(self._namespace, name)) from e return named_indexer def _get_cached_array_and_index(self, name): """Returns `(array, index)` for a given field name.""" named_indexer = self._get_cached_named_indexer(name) array = named_indexer._field # pylint: disable=protected-access try: index = self._array_index_cache[name] except KeyError: index = named_indexer._convert_key(self._named_index) # pylint: disable=protected-access self._array_index_cache[name] = index return array, index @property def element_id(self): """The ID number of this element within MuJoCo's data structures.""" try: element_id = self._getattr_cache['element_id'] except KeyError: if isinstance(self._named_index, list): element_id = np.array( [self._physics.model.name2id(item_name, self._namespace) for item_name in self._named_index]) element_id.flags.writeable = False else: element_id = self._physics.model.name2id( self._named_index, self._namespace) self._getattr_cache['element_id'] = element_id return element_id def __getattr__(self, name): if name in Binding.__slots__: return super().__getattr__(name) else: try: out = self._getattr_cache[name] out._synchronize_from_backing_array() # pylint: disable=protected-access except KeyError: array, index = self._get_cached_array_and_index(name) triggers_dirty = self._attributes[name].triggers_dirty # A list of (array, index) tuples specifying other addresses that need # to be zeroed out when this array attribute is written to. disable_on_write = [] for name_to_disable in self._attributes[name].disable_on_write: array_to_disable, index_to_disable = self._get_cached_array_and_index( name_to_disable) # Ensure that the result of indexing is a `SynchronizingArrayWrapper` # rather than a scalar, otherwise we won't be able to write into it. if array_to_disable.ndim == 1: if isinstance(index_to_disable, np.ndarray): index_to_disable = index_to_disable.copy().reshape(-1, 1) else: index_to_disable = [index_to_disable] disable_on_write.append((array_to_disable, index_to_disable)) if self._physics.is_dirty and not triggers_dirty: self._physics.forward() if np.issubdtype(type(index), np.integer) and array.ndim == 1: # Case where indexing results in a scalar. out = array[index] else: # Case where indexing results in an array. out = SynchronizingArrayWrapper( backing_array=array, backing_index=index, physics=self._physics, triggers_dirty=triggers_dirty, disable_on_write=disable_on_write) self._getattr_cache[name] = out return out def __setattr__(self, name, value): if name in Binding.__slots__: super().__setattr__(name, value) else: if self._physics.is_dirty and not self._attributes[name].triggers_dirty: self._physics.forward() array, index = self._get_cached_array_and_index(name) array[index] = value for name_to_disable in self._attributes[name].disable_on_write: disable_array, disable_index = self._get_cached_array_and_index( name_to_disable) disable_array[disable_index] = 0 if self._attributes[name].triggers_dirty: self._physics.mark_as_dirty() def _get_name_and_indexer_and_expression(self, index): """Returns (name, indexer, expression) for a given input to __getitem__.""" if isinstance(index, tuple): name, column_index = index try: # If named_index and column_index are both array-like, reshape # named_index to (n, 1) so that it can be broadcasted against # column_index. expression = np.ix_(self._named_index, column_index) except ValueError: expression = (self._named_index, column_index) else: name = index expression = self._named_index indexer = self._get_cached_named_indexer(name) return name, indexer, expression def __getitem__(self, index): name, indexer, expression = self._get_name_and_indexer_and_expression(index) if self._physics.is_dirty and not self._attributes[name].triggers_dirty: self._physics.forward() return indexer[expression] def __setitem__(self, index, value): name, indexer, expression = self._get_name_and_indexer_and_expression(index) if self._physics.is_dirty and not self._attributes[name].triggers_dirty: self._physics.forward() indexer[expression] = value if self._attributes[name].triggers_dirty: self._physics.mark_as_dirty() class _EmptyBinding: """The result of binding no `mjcf.Elements` to an `mjcf.Physics` instance.""" __slots__ = ('_arr',) def __init__(self): self._arr = np.empty((0)) def __getattr__(self, name): return self._arr def __setattr__(self, name, value): if name in self.__slots__: super().__setattr__(name, value) else: raise ValueError('Cannot assign a value to an empty binding.') _EMPTY_BINDING = _EmptyBinding() def _log_xml(xml_string): xml_lines = xml_string.split('\n') for start_line in range(0, len(xml_lines), _XML_PRINT_SHARD_SIZE): end_line = min(start_line + _XML_PRINT_SHARD_SIZE, len(xml_lines)) template = 'XML lines %d-%d of %d:\n%s' if start_line == 0: template = 'PyMJCF: compiling generated XML:\n' + template logging.info(template, start_line + 1, end_line, len(xml_lines), '\n'.join(xml_lines[start_line:end_line])) class Physics(mujoco.Physics): """A specialized `mujoco.Physics` that supports binding to MJCF elements.""" @classmethod def from_mjcf_model(cls, mjcf_model): """Constructs a new `mjcf.Physics` from an `mjcf.RootElement`. Args: mjcf_model: An `mjcf.RootElement` instance. Returns: A new `mjcf.Physics` instance. """ debug_context = debugging.DebugContext() xml_string = mjcf_model.to_xml_string(debug_context=debug_context) if _pymjcf_log_xml(): if debug_context.debug_mode and debug_context.default_dump_dir: logging.info('Full debug info is dumped to disk at %s', debug_context.default_dump_dir) debug_context.dump_full_debug_info_to_disk() else: logging.info('Full debug info is not yet dumped to disk. If this is ' 'needed, pass all three flags: --pymjcf_log_xml ' '--pymjcf_debug --pymjcf_debug_full_dump_dir=/path/dir/') _log_xml(xml_string) assets = mjcf_model.get_assets() try: return cls.from_xml_string(xml_string=xml_string, assets=assets) except ValueError: debug_context.process_and_raise_last_exception() def reload_from_mjcf_model(self, mjcf_model): """Reloads this `mjcf.Physics` from an `mjcf.RootElement`. After calling this method, the state of this `Physics` instance is the same as a new `Physics` instance created with the `from_mjcf_model` named constructor. Args: mjcf_model: An `mjcf.RootElement` instance. """ debug_context = debugging.DebugContext() xml_string = mjcf_model.to_xml_string(debug_context=debug_context) if _pymjcf_log_xml(): _log_xml(xml_string) assets = mjcf_model.get_assets() try: self.reload_from_xml_string(xml_string=xml_string, assets=assets) except ValueError: debug_context.process_and_raise_last_exception() def _reload_from_data(self, data): """Initializes a new or existing `Physics` instance from a `core.MjData`. Assigns all attributes and sets up rendering contexts and named indexing. The default constructor as well as the other `reload_from` methods should delegate to this method. Args: data: Instance of `core.MjData`. """ super()._reload_from_data(data) self._bindings = {} self._bindings[()] = _EMPTY_BINDING self._dirty = False @property def is_dirty(self): """Whether this physics' internal state needs to be recalculated.""" return self._dirty def mark_as_dirty(self): """Marks this physics as dirty, thus requiring recalculation.""" self._dirty = True def forward(self): """Recomputes the forward dynamics without advancing the simulation.""" super().forward() self._dirty = False def bind(self, mjcf_elements): """Creates a binding between this `Physics` instance and `mjcf.Element`s. The binding allows for easier interaction with the `Physics` data structures related to an MJCF element. For example, in order to access the Cartesian position of a geom, we can use: ```python physics.bind(geom_element).pos ``` instead of the more cumbersome: ```python physics.named.model.geom_pos[geom_element.full_identifier] ``` Note that the binding takes into account the type of element. This allows us to remove prefixes from certain common attributes in order to unify access. For example, we can use: ```python physics.bind(geom_element).pos = [1, 2, 3] physics.bind(site_element).pos = [4, 5, 6] ``` instead of: ```python physics.named.model.geom_pos[geom_element.full_identifier] = [1, 2, 3] physics.named.model.site_pos[site_element.full_identifier] = [4, 5, 6] ``` This in turn allows for the creation of common algorithms that can operate across a wide range of element type. When attribute values are modified through the binding, future queries of derived values are automatically recalculated if necessary. For example, if a joint's `qpos` is modified and a site's `xpos` is later read, the value of the `xpos` is updated according to the new joint configuration. This is done lazily when an updated value is required, so repeated value modifications do not incur a performance penalty. It is also possible to bind a sequence containing one or more elements, provided they are all of the same type. In this case the binding exposes `SynchronizingArrayWrapper`s, which are array-like objects that provide writeable views onto the corresponding memory addresses in MuJoCo. Writing into a `SynchronizingArrayWrapper` causes the underlying values in MuJoCo to be updated, and if necessary causes derived values to be recalculated. Note that in order to trigger recalculation it is necessary to reference a derived attribute of a binding. ```python bound_joints = physics.bind([joint1, joint2]) bound_bodies = physics.bind([body1, body2]) # `qpos_view` and `xpos_view` are `SynchronizingArrayWrapper`s providing # views onto `physics.data.qpos` and `physics.data.xpos` respectively. qpos_view = bound_joints.qpos xpos_view = bound_bodies.xpos # This updates the corresponding values in `physics.data.qpos`, and marks # derived values (such as `physics.data.xpos`) as needing recalculation. qpos_view[0] += 1. # Note: at this point `xpos_view` still contains the old values, since we # need to actually read the value of a derived attribute in order to # trigger recalculation. another_xpos_view = bound_bodies.xpos # Triggers recalculation of `xpos`. # Now both `xpos_view` and `another_xpos_view` will contain the updated # values. ``` Note that `SynchronizingArrayWrapper`s cannot be pickled. We also do not recommend holding references to them - instead hold a reference to the binding object, or call `physics.bind` again. Bindings also support numpy-style square bracket indexing. The first element in the indexing expression should be an attribute name, and the second element (if present) is used to index into the columns of the underlying array. Named indexing into columns is also allowed, provided that the corresponding field in `physics.named` supports it. ```python physics.bind([geom1, geom2])['pos'] = [[1, 2, 3], [4, 5, 6]] physics.bind([geom1, geom2])['pos', ['x', 'z']] = [[1, 3], [4, 6]] ``` Args: mjcf_elements: Either an `mjcf.Element`, or an iterable of `mjcf.Element` of the same kind. Returns: A binding between this Physics instance an `mjcf_elements`, as described above. Raises: ValueError: If `mjcf_elements` cannot be bound to this Physics. """ if mjcf_elements is None: return None # To reduce overhead from processing MJCF elements and making new bindings, # we cache and reuse existing Binding objects. The cheapest version of # caching is when we can use `mjcf_elements` as key directly. However, this # is not always possible since `mjcf_elements` may contain weak references. # In this case, we fallback to using the elements' namespace and identifiers # as cache keys instead. # Checking for iterability in this way is cheaper than using `isinstance`. try: cache_key = tuple(mjcf_elements) except TypeError: # `mjcf_elements` is not iterable. cache_key = mjcf_elements needs_new_binding = False try: binding = self._bindings[cache_key] except KeyError: # This means `mjcf_elements` is hashable, so we use it as cache key. namespace, named_index = names_from_elements(mjcf_elements) needs_new_binding = True except TypeError: # This means `mjcf_elements` is unhashable, fallback to caching by name. namespace, named_index = names_from_elements(mjcf_elements) # Checking for iterability in this way is cheaper than using `isinstance`. try: cache_key = (namespace, tuple(named_index)) except TypeError: # `named_index` is not iterable. cache_key = (namespace, named_index) try: binding = self._bindings[cache_key] except KeyError: needs_new_binding = True if needs_new_binding: binding = Binding(weakref.proxy(self), namespace, named_index) self._bindings[cache_key] = binding return binding def _get_namespace(element): """Returns the element namespace string.""" # The worldbody is treated as a member of the `body` namespace. if element.tag == 'worldbody': namespace = 'body' else: namespace = element.spec.namespace.split(constants.NAMESPACE_SEPARATOR)[0] # Mocap bodies have distinct attributes so we use a dummy namespace for # them. if namespace == 'body' and element.mocap == 'true': namespace = 'mocap_body' return namespace
dm_control-main
dm_control/mjcf/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 `dm_control.mjcf.element`.""" import copy import hashlib import itertools import os import sys import traceback from absl.testing import absltest from absl.testing import parameterized from dm_control import mjcf from dm_control.mjcf import element from dm_control.mjcf import namescope from dm_control.mjcf import parser from dm_control.mujoco.wrapper import util import lxml import numpy as np etree = lxml.etree _ASSETS_DIR = os.path.join(os.path.dirname(__file__), 'test_assets') _TEST_MODEL_XML = os.path.join(_ASSETS_DIR, 'test_model.xml') _TEXTURE_PATH = os.path.join(_ASSETS_DIR, 'textures/deepmind.png') _MESH_PATH = os.path.join(_ASSETS_DIR, 'meshes/cube.stl') _MODEL_WITH_INCLUDE_PATH = os.path.join(_ASSETS_DIR, 'model_with_include.xml') _MODEL_WITH_INVALID_FILENAMES = os.path.join( _ASSETS_DIR, 'model_with_invalid_filenames.xml') _INCLUDED_WITH_INVALID_FILENAMES = os.path.join( _ASSETS_DIR, 'included_with_invalid_filenames.xml') _MODEL_WITH_NAMELESS_ASSETS = os.path.join( _ASSETS_DIR, 'model_with_nameless_assets.xml') class ElementTest(parameterized.TestCase): def assertIsSame(self, mjcf_model, other): self.assertTrue(mjcf_model.is_same_as(other)) self.assertTrue(other.is_same_as(mjcf_model)) def assertIsNotSame(self, mjcf_model, other): self.assertFalse(mjcf_model.is_same_as(other)) self.assertFalse(other.is_same_as(mjcf_model)) def assertHasAttr(self, obj, attrib): self.assertTrue(hasattr(obj, attrib)) def assertNotHasAttr(self, obj, attrib): self.assertFalse(hasattr(obj, attrib)) def _test_properties(self, mjcf_element, parent, root, recursive=False): self.assertEqual(mjcf_element.tag, mjcf_element.spec.name) self.assertEqual(mjcf_element.parent, parent) self.assertEqual(mjcf_element.root, root) self.assertEqual(mjcf_element.namescope, root.namescope) for child_name, child_spec in mjcf_element.spec.children.items(): if not (child_spec.repeated or child_spec.on_demand): child = getattr(mjcf_element, child_name) self.assertEqual(child.tag, child_name) self.assertEqual(child.spec, child_spec) if recursive: self._test_properties(child, parent=mjcf_element, root=root, recursive=True) def testAttributeError(self): mjcf_model = element.RootElement(model='test') mjcf_model.worldbody._spec = None try: _ = mjcf_model.worldbody.tag except AttributeError: _, err, tb = sys.exc_info() else: self.fail('AttributeError was not raised.') # Test that the error comes from the fact that we've set `_spec = None`. self.assertEqual(str(err), '\'NoneType\' object has no attribute \'name\'') _, _, func_name, _ = traceback.extract_tb(tb)[-1] # Test that the error comes from the `root` property, not `__getattr__`. self.assertEqual(func_name, 'tag') def testProperties(self): mujoco = element.RootElement(model='test') self.assertIsInstance(mujoco.namescope, namescope.NameScope) self._test_properties(mujoco, parent=None, root=mujoco, recursive=True) def _test_attributes(self, mjcf_element, expected_values=None, recursive=False): attributes = mjcf_element.get_attributes() self.assertNotIn('class', attributes) for attribute_name in mjcf_element.spec.attributes.keys(): if attribute_name == 'class': attribute_name = 'dclass' self.assertHasAttr(mjcf_element, attribute_name) self.assertIn(attribute_name, dir(mjcf_element)) attribute_value = getattr(mjcf_element, attribute_name) if attribute_value is not None: self.assertIn(attribute_name, attributes) else: self.assertNotIn(attribute_name, attributes) if expected_values: if attribute_name in expected_values: expected_value = expected_values[attribute_name] np.testing.assert_array_equal(attribute_value, expected_value) else: self.assertIsNone(attribute_value) if recursive: for child in mjcf_element.all_children(): self._test_attributes(child, recursive=True) def testAttributes(self): mujoco = element.RootElement(model='test') mujoco.default.dclass = 'main' self._test_attributes(mujoco, recursive=True) def _test_children(self, mjcf_element, recursive=False): children = mjcf_element.all_children() for child_name, child_spec in mjcf_element.spec.children.items(): if not (child_spec.repeated or child_spec.on_demand): self.assertHasAttr(mjcf_element, child_name) self.assertIn(child_name, dir(mjcf_element)) child = getattr(mjcf_element, child_name) self.assertIn(child, children) with self.assertRaisesRegex(AttributeError, 'can\'t set attribute'): setattr(mjcf_element, child_name, 'value') if recursive: self._test_children(child, recursive=True) def testChildren(self): mujoco = element.RootElement(model='test') self._test_children(mujoco, recursive=True) def testInvalidAttr(self): mujoco = element.RootElement(model='test') invalid_attrib_name = 'foobar' def test_invalid_attr_recursively(mjcf_element): self.assertNotHasAttr(mjcf_element, invalid_attrib_name) self.assertNotIn(invalid_attrib_name, dir(mjcf_element)) with self.assertRaisesRegex(AttributeError, 'object has no attribute'): getattr(mjcf_element, invalid_attrib_name) with self.assertRaisesRegex(AttributeError, 'can\'t set attribute'): setattr(mjcf_element, invalid_attrib_name, 'value') with self.assertRaisesRegex(AttributeError, 'object has no attribute'): delattr(mjcf_element, invalid_attrib_name) for child in mjcf_element.all_children(): test_invalid_attr_recursively(child) test_invalid_attr_recursively(mujoco) def testAdd(self): mujoco = element.RootElement(model='test') # repeated elements body_foo_attributes = dict(name='foo', pos=[0, 1, 0], quat=[0, 1, 0, 0]) body_foo = mujoco.worldbody.add('body', **body_foo_attributes) self.assertEqual(body_foo.tag, 'body') joint_foo_attributes = dict(name='foo', type='free') joint_foo = body_foo.add('joint', **joint_foo_attributes) self.assertEqual(joint_foo.tag, 'joint') self._test_properties(body_foo, parent=mujoco.worldbody, root=mujoco) self._test_attributes(body_foo, expected_values=body_foo_attributes) self._test_children(body_foo) self._test_properties(joint_foo, parent=body_foo, root=mujoco) self._test_attributes(joint_foo, expected_values=joint_foo_attributes) self._test_children(joint_foo) # non-repeated, on-demand elements self.assertIsNone(body_foo.inertial) body_foo_inertial_attributes = dict(mass=1.0, pos=[0, 0, 0]) body_foo_inertial = body_foo.add('inertial', **body_foo_inertial_attributes) self._test_properties(body_foo_inertial, parent=body_foo, root=mujoco) self._test_attributes(body_foo_inertial, expected_values=body_foo_inertial_attributes) self._test_children(body_foo_inertial) with self.assertRaisesRegex(ValueError, '<inertial> child already exists'): body_foo.add('inertial', **body_foo_inertial_attributes) # non-repeated, non-on-demand elements with self.assertRaisesRegex(ValueError, '<compiler> child already exists'): mujoco.add('compiler') self.assertIsNotNone(mujoco.compiler) with self.assertRaisesRegex(ValueError, '<default> child already exists'): mujoco.add('default') self.assertIsNotNone(mujoco.default) def testInsert(self): mujoco = element.RootElement(model='test') # add in order mujoco.worldbody.add('body', name='0') mujoco.worldbody.add('body', name='1') mujoco.worldbody.add('body', name='2') # insert into position 0, check order mujoco.worldbody.insert('body', name='foo', position=0) expected_order = ['foo', '0', '1', '2'] for i, child in enumerate(mujoco.worldbody._children): self.assertEqual(child.name, expected_order[i]) # insert into position -1, check order mujoco.worldbody.insert('body', name='bar', position=-1) expected_order = ['foo', '0', '1', 'bar', '2'] for i, child in enumerate(mujoco.worldbody._children): self.assertEqual(child.name, expected_order[i]) def testAddWithInvalidAttribute(self): mujoco = element.RootElement(model='test') with self.assertRaisesRegex(AttributeError, 'not a valid attribute'): mujoco.worldbody.add('body', name='foo', invalid_attribute='some_value') self.assertFalse(mujoco.worldbody.body) self.assertIsNone(mujoco.worldbody.find('body', 'foo')) def testSameness(self): mujoco = element.RootElement(model='test') body_1 = mujoco.worldbody.add('body', pos=[0, 1, 2], quat=[0, 1, 0, 1]) site_1 = body_1.add('site', pos=[0, 1, 2], quat=[0, 1, 0, 1]) geom_1 = body_1.add('geom', pos=[0, 1, 2], quat=[0, 1, 0, 1]) for elem in (body_1, site_1, geom_1): self.assertIsSame(elem, elem) # strict ordering NOT required: adding geom and site is different order body_2 = mujoco.worldbody.add('body', pos=[0, 1, 2], quat=[0, 1, 0, 1]) geom_2 = body_2.add('geom', pos=[0, 1, 2], quat=[0, 1, 0, 1]) site_2 = body_2.add('site', pos=[0, 1, 2], quat=[0, 1, 0, 1]) elems_1 = (body_1, site_1, geom_1) elems_2 = (body_2, site_2, geom_2) for i, j in itertools.product(range(len(elems_1)), range(len(elems_2))): if i == j: self.assertIsSame(elems_1[i], elems_2[j]) else: self.assertIsNotSame(elems_1[i], elems_2[j]) # on-demand child body_1.add('inertial', pos=[0, 0, 0], mass=1) self.assertIsNotSame(body_1, body_2) body_2.add('inertial', pos=[0, 0, 0], mass=1) self.assertIsSame(body_1, body_2) # different number of children subbody_1 = body_1.add('body', pos=[0, 0, 1]) self.assertIsNotSame(body_1, body_2) # attribute mismatch subbody_2 = body_2.add('body') self.assertIsNotSame(subbody_1, subbody_2) self.assertIsNotSame(body_1, body_2) subbody_2.pos = [0, 0, 1] self.assertIsSame(subbody_1, subbody_2) self.assertIsSame(body_1, body_2) # grandchild attribute mismatch subbody_1.add('joint', type='hinge') subbody_2.add('joint', type='ball') self.assertIsNotSame(body_1, body_2) def testTendonSameness(self): mujoco = element.RootElement(model='test') spatial_1 = mujoco.tendon.add('spatial') spatial_1.add('site', site='foo') spatial_1.add('geom', geom='bar') spatial_2 = mujoco.tendon.add('spatial') spatial_2.add('site', site='foo') spatial_2.add('geom', geom='bar') self.assertIsSame(spatial_1, spatial_2) # strict ordering is required spatial_3 = mujoco.tendon.add('spatial') spatial_3.add('site', site='foo') spatial_3.add('geom', geom='bar') spatial_4 = mujoco.tendon.add('spatial') spatial_4.add('geom', geom='bar') spatial_4.add('site', site='foo') self.assertIsNotSame(spatial_3, spatial_4) def testCopy(self): mujoco = parser.from_path(_TEST_MODEL_XML) self.assertIsSame(mujoco, mujoco) copy_mujoco = copy.copy(mujoco) copy_mujoco.model = 'copied_model' self.assertIsSame(copy_mujoco, mujoco) self.assertNotEqual(copy_mujoco, mujoco) deepcopy_mujoco = copy.deepcopy(mujoco) deepcopy_mujoco.model = 'deepcopied_model' self.assertIsSame(deepcopy_mujoco, mujoco) self.assertNotEqual(deepcopy_mujoco, mujoco) self.assertIsSame(deepcopy_mujoco, copy_mujoco) self.assertNotEqual(deepcopy_mujoco, copy_mujoco) def testWorldBodyFullIdentifier(self): mujoco = parser.from_path(_TEST_MODEL_XML) mujoco.model = 'model' self.assertEqual(mujoco.worldbody.full_identifier, 'world') submujoco = copy.copy(mujoco) submujoco.model = 'submodel' self.assertEqual(submujoco.worldbody.full_identifier, 'world') mujoco.attach(submujoco) self.assertEqual(mujoco.worldbody.full_identifier, 'world') self.assertEqual(submujoco.worldbody.full_identifier, 'submodel/') self.assertNotIn('name', mujoco.worldbody.to_xml_string(self_only=True)) self.assertNotIn('name', submujoco.worldbody.to_xml_string(self_only=True)) def testAttach(self): mujoco = parser.from_path(_TEST_MODEL_XML) mujoco.model = 'model' submujoco = copy.copy(mujoco) submujoco.model = 'submodel' subsubmujoco = copy.copy(mujoco) subsubmujoco.model = 'subsubmodel' with self.assertRaisesRegex(ValueError, 'Cannot merge a model to itself'): mujoco.attach(mujoco) attachment_site = submujoco.find('site', 'attachment') attachment_site.attach(subsubmujoco) subsubmodel_frame = submujoco.find('attachment_frame', 'subsubmodel') for attribute_name in ('pos', 'axisangle', 'xyaxes', 'zaxis', 'euler'): np.testing.assert_array_equal( getattr(subsubmodel_frame, attribute_name), getattr(attachment_site, attribute_name)) self._test_properties(subsubmodel_frame, parent=attachment_site.parent, root=submujoco) self.assertEqual( subsubmodel_frame.to_xml_string().split('\n')[0], '<body ' 'pos="0.10000000000000001 0.10000000000000001 0.10000000000000001" ' 'quat="0 1 0 0" ' 'name="subsubmodel/">') self.assertEqual( subsubmodel_frame.to_xml_string(precision=5).split('\n')[0], '<body ' 'pos="0.1 0.1 0.1" ' 'quat="0 1 0 0" ' 'name="subsubmodel/">') self.assertEqual(subsubmodel_frame.all_children(), subsubmujoco.worldbody.all_children()) with self.assertRaisesRegex(ValueError, 'already attached elsewhere'): mujoco.attach(subsubmujoco) with self.assertRaisesRegex(ValueError, 'Expected a mjcf.RootElement'): mujoco.attach(submujoco.contact) submujoco.option.flag.gravity = 'enable' with self.assertRaisesRegex( ValueError, 'Conflicting values for attribute `gravity`'): mujoco.attach(submujoco) submujoco.option.flag.gravity = 'disable' mujoco.attach(submujoco) self.assertEqual(subsubmujoco.parent_model, submujoco) self.assertEqual(submujoco.parent_model, mujoco) self.assertEqual(subsubmujoco.root_model, mujoco) self.assertEqual(submujoco.root_model, mujoco) self.assertEqual(submujoco.full_identifier, 'submodel/') self.assertEqual(subsubmujoco.full_identifier, 'submodel/subsubmodel/') merged_children = ('contact', 'actuator') for child_name in merged_children: for grandchild in getattr(submujoco, child_name).all_children(): self.assertIn(grandchild, getattr(mujoco, child_name).all_children()) for grandchild in getattr(subsubmujoco, child_name).all_children(): self.assertIn(grandchild, getattr(mujoco, child_name).all_children()) self.assertIn(grandchild, getattr(submujoco, child_name).all_children()) base_contact_content = ( '<exclude name="{0}exclude" body1="{0}b_0" body2="{0}b_1"/>') self.assertEqual( mujoco.contact.to_xml_string(pretty_print=False), '<contact>' + base_contact_content.format('') + base_contact_content.format('submodel/') + base_contact_content.format('submodel/subsubmodel/') + '</contact>') actuators_template = ( '<velocity name="{1}b_0_0" class="{0}" joint="{1}b_0_0"/>' '<velocity name="{1}b_1_0" class="{0}" joint="{1}b_1_0"/>') self.assertEqual( mujoco.actuator.to_xml_string(pretty_print=False), '<actuator>' + actuators_template.format('/', '') + actuators_template.format('submodel/', 'submodel/') + actuators_template.format('submodel/subsubmodel/', 'submodel/subsubmodel/') + '</actuator>') self.assertEqual(mujoco.default.full_identifier, '/') self.assertEqual(mujoco.default.default[0].full_identifier, 'big_and_green') self.assertEqual(submujoco.default.full_identifier, 'submodel/') self.assertEqual(submujoco.default.default[0].full_identifier, 'submodel/big_and_green') self.assertEqual(subsubmujoco.default.full_identifier, 'submodel/subsubmodel/') self.assertEqual(subsubmujoco.default.default[0].full_identifier, 'submodel/subsubmodel/big_and_green') default_xml_lines = (mujoco.default.to_xml_string(pretty_print=False) .replace('><', '>><<').split('><')) self.assertEqual(default_xml_lines[0], '<default>') self.assertEqual(default_xml_lines[1], '<default class="/">') self.assertEqual(default_xml_lines[4], '<default class="big_and_green">') self.assertEqual(default_xml_lines[6], '</default>') self.assertEqual(default_xml_lines[7], '</default>') self.assertEqual(default_xml_lines[8], '<default class="submodel/">') self.assertEqual(default_xml_lines[11], '<default class="submodel/big_and_green">') self.assertEqual(default_xml_lines[13], '</default>') self.assertEqual(default_xml_lines[14], '</default>') self.assertEqual(default_xml_lines[15], '<default class="submodel/subsubmodel/">') self.assertEqual(default_xml_lines[18], '<default class="submodel/subsubmodel/big_and_green">') self.assertEqual(default_xml_lines[-3], '</default>') self.assertEqual(default_xml_lines[-2], '</default>') self.assertEqual(default_xml_lines[-1], '</default>') def testDetach(self): root = parser.from_path(_TEST_MODEL_XML) root.model = 'model' submodel = copy.copy(root) submodel.model = 'submodel' unattached_xml_1 = root.to_xml_string() root.attach(submodel) attached_xml_1 = root.to_xml_string() submodel.detach() unattached_xml_2 = root.to_xml_string() root.attach(submodel) attached_xml_2 = root.to_xml_string() self.assertEqual(unattached_xml_1, unattached_xml_2) self.assertEqual(attached_xml_1, attached_xml_2) def testRenameAttachedModel(self): root = parser.from_path(_TEST_MODEL_XML) root.model = 'model' submodel = copy.copy(root) submodel.model = 'submodel' geom = submodel.worldbody.add( 'geom', name='geom', type='sphere', size=[0.1]) frame = root.attach(submodel) submodel.model = 'renamed' self.assertEqual(frame.full_identifier, 'renamed/') self.assertIsSame(root.find('geom', 'renamed/geom'), geom) def testAttachmentFrames(self): mujoco = parser.from_path(_TEST_MODEL_XML) mujoco.model = 'model' submujoco = copy.copy(mujoco) submujoco.model = 'submodel' subsubmujoco = copy.copy(mujoco) subsubmujoco.model = 'subsubmodel' attachment_site = submujoco.find('site', 'attachment') attachment_site.attach(subsubmujoco) mujoco.attach(submujoco) # attachments directly on worldbody can have a <freejoint> submujoco_frame = mujoco.find('attachment_frame', 'submodel') self.assertStartsWith(submujoco_frame.to_xml_string(pretty_print=False), '<body name="submodel/">') self.assertEqual(submujoco_frame.full_identifier, 'submodel/') free_joint = submujoco_frame.add('freejoint') self.assertEqual(free_joint.to_xml_string(pretty_print=False), '<freejoint name="submodel/"/>') self.assertEqual(free_joint.full_identifier, 'submodel/') # attachments elsewhere cannot have a <freejoint> subsubmujoco_frame = submujoco.find('attachment_frame', 'subsubmodel') subsubmujoco_frame_xml = subsubmujoco_frame.to_xml_string( pretty_print=False, prefix_root=mujoco.namescope) self.assertStartsWith( subsubmujoco_frame_xml, '<body ' 'pos="0.10000000000000001 0.10000000000000001 0.10000000000000001" ' 'quat="0 1 0 0" ' 'name="submodel/subsubmodel/">') self.assertEqual(subsubmujoco_frame.full_identifier, 'submodel/subsubmodel/') with self.assertRaisesRegex(AttributeError, 'not a valid child'): subsubmujoco_frame.add('freejoint') hinge_joint = subsubmujoco_frame.add('joint', type='hinge', axis=[1, 2, 3]) hinge_joint_xml = hinge_joint.to_xml_string( pretty_print=False, prefix_root=mujoco.namescope) self.assertEqual( hinge_joint_xml, '<joint class="submodel/" type="hinge" axis="1 2 3" ' 'name="submodel/subsubmodel/"/>') self.assertEqual(hinge_joint.full_identifier, 'submodel/subsubmodel/') def testDuplicateAttachmentFrameJointIdentifiers(self): mujoco = parser.from_path(_TEST_MODEL_XML) mujoco.model = 'model' submujoco_1 = copy.copy(mujoco) submujoco_1.model = 'submodel_1' submujoco_2 = copy.copy(mujoco) submujoco_2.model = 'submodel_2' frame_1 = mujoco.attach(submujoco_1) frame_2 = mujoco.attach(submujoco_2) joint_1 = frame_1.add('joint', type='slide', name='root_x', axis=[1, 0, 0]) joint_2 = frame_2.add('joint', type='slide', name='root_x', axis=[1, 0, 0]) self.assertEqual(joint_1.full_identifier, 'submodel_1/root_x/') self.assertEqual(joint_2.full_identifier, 'submodel_2/root_x/') def testAttachmentFrameReference(self): root_1 = mjcf.RootElement('model_1') root_2 = mjcf.RootElement('model_2') root_2_frame = root_1.attach(root_2) sensor = root_1.sensor.add( 'framelinacc', name='root_2', objtype='body', objname=root_2_frame) self.assertEqual( sensor.to_xml_string(pretty_print=False), '<framelinacc name="root_2" objtype="body" objname="model_2/"/>') def testAttachmentFrameChildReference(self): root_1 = mjcf.RootElement('model_1') root_2 = mjcf.RootElement('model_2') root_2_frame = root_1.attach(root_2) root_2_joint = root_2_frame.add( 'joint', name='root_x', type='slide', axis=[1, 0, 0]) actuator = root_1.actuator.add( 'position', name='root_x', joint=root_2_joint) self.assertEqual( actuator.to_xml_string(pretty_print=False), '<position name="root_x" class="/" joint="model_2/root_x/"/>') def testDeletion(self): mujoco = parser.from_path(_TEST_MODEL_XML) mujoco.model = 'model' submujoco = copy.copy(mujoco) submujoco.model = 'submodel' subsubmujoco = copy.copy(mujoco) subsubmujoco.model = 'subsubmodel' submujoco.find('site', 'attachment').attach(subsubmujoco) mujoco.attach(submujoco) with self.assertRaisesRegex( ValueError, r'use remove\(affect_attachments=True\)'): del mujoco.option mujoco.option.remove(affect_attachments=True) for root in (mujoco, submujoco, subsubmujoco): self.assertIsNotNone(root.option.flag) self.assertEqual( root.option.to_xml_string(pretty_print=False), '<option/>') self.assertIsNotNone(root.option.flag) self.assertEqual( root.option.flag.to_xml_string(pretty_print=False), '<flag/>') with self.assertRaisesRegex( ValueError, r'use remove\(affect_attachments=True\)'): del mujoco.contact mujoco.contact.remove(affect_attachments=True) for root in (mujoco, submujoco, subsubmujoco): self.assertEqual( root.contact.to_xml_string(pretty_print=False), '<contact/>') b_0 = mujoco.find('body', 'b_0') b_0_inertial = b_0.inertial self.assertEqual(b_0_inertial.mass, 1) self.assertIsNotNone(b_0.inertial) del b_0.inertial self.assertIsNone(b_0.inertial) def testRemoveElementWithRequiredAttribute(self): root = mjcf.RootElement() body = root.worldbody.add('body') # `objtype` is a required attribute. sensor = root.sensor.add('framepos', objtype='body', objname=body) self.assertIn(sensor, root.sensor.all_children()) sensor.remove() self.assertNotIn(sensor, root.sensor.all_children()) def testRemoveWithChildren(self): root = mjcf.RootElement() body = root.worldbody.add('body') subbodies = [] for _ in range(5): subbodies.append(body.add('body')) body.remove() for subbody in subbodies: self.assertTrue(subbody.is_removed) def testFind(self): mujoco = parser.from_path(_TEST_MODEL_XML, resolve_references=False) mujoco.model = 'model' submujoco = copy.copy(mujoco) submujoco.model = 'submodel' subsubmujoco = copy.copy(mujoco) subsubmujoco.model = 'subsubmodel' submujoco.find('site', 'attachment').attach(subsubmujoco) mujoco.attach(submujoco) self.assertIsNotNone(mujoco.find('geom', 'b_0_0')) self.assertIsNotNone(mujoco.find('body', 'b_0').find('geom', 'b_0_0')) self.assertIsNone(mujoco.find('body', 'b_1').find('geom', 'b_0_0')) self.assertIsNone(mujoco.find('geom', 'nonexistent')) self.assertIsNone(mujoco.find('geom', 'nonexistent/b_0_0')) self.assertEqual(mujoco.find('geom', 'submodel/b_0_0'), submujoco.find('geom', 'b_0_0')) self.assertEqual(mujoco.find('geom', 'submodel/subsubmodel/b_0_0'), submujoco.find('geom', 'subsubmodel/b_0_0')) self.assertEqual(submujoco.find('geom', 'subsubmodel/b_0_0'), subsubmujoco.find('geom', 'b_0_0')) subsubmujoco.find('geom', 'b_0_0').name = 'foo' self.assertIsNone(mujoco.find('geom', 'submodel/subsubmodel/b_0_0')) self.assertIsNone(submujoco.find('geom', 'subsubmodel/b_0_0')) self.assertIsNone(subsubmujoco.find('geom', 'b_0_0')) self.assertEqual(mujoco.find('geom', 'submodel/subsubmodel/foo'), submujoco.find('geom', 'subsubmodel/foo')) self.assertEqual(submujoco.find('geom', 'subsubmodel/foo'), subsubmujoco.find('geom', 'foo')) self.assertEqual(mujoco.find('actuator', 'b_0_0').root, mujoco) self.assertEqual(mujoco.find('actuator', 'b_0_0').tag, 'velocity') self.assertEqual(mujoco.find('actuator', 'b_0_0').joint, 'b_0_0') self.assertEqual(mujoco.find('actuator', 'submodel/b_0_0').root, submujoco) self.assertEqual(mujoco.find('actuator', 'submodel/b_0_0').tag, 'velocity') self.assertEqual(mujoco.find('actuator', 'submodel/b_0_0').joint, 'b_0_0') def testFindInvalidNamespace(self): mjcf_model = mjcf.RootElement() with self.assertRaisesRegex(ValueError, 'not a valid namespace'): mjcf_model.find('jiont', 'foo') with self.assertRaisesRegex(ValueError, 'not a valid namespace'): mjcf_model.find_all('goem') def testEnterScope(self): mujoco = parser.from_path(_TEST_MODEL_XML, resolve_references=False) mujoco.model = 'model' self.assertIsNone(mujoco.enter_scope('submodel')) submujoco = copy.copy(mujoco) submujoco.model = 'submodel' subsubmujoco = copy.copy(mujoco) subsubmujoco.model = 'subsubmodel' submujoco.find('site', 'attachment').attach(subsubmujoco) mujoco.attach(submujoco) self.assertIsNotNone(mujoco.enter_scope('submodel')) self.assertEqual(mujoco.enter_scope('submodel').find('geom', 'b_0_0'), submujoco.find('geom', 'b_0_0')) self.assertEqual( mujoco.enter_scope('submodel/subsubmodel/').find('geom', 'b_0_0'), subsubmujoco.find('geom', 'b_0_0')) self.assertEqual(mujoco.enter_scope('submodel').enter_scope( 'subsubmodel').find('geom', 'b_0_0'), subsubmujoco.find('geom', 'b_0_0')) self.assertEqual( mujoco.enter_scope('submodel').find('actuator', 'b_0_0').root, submujoco) self.assertEqual( mujoco.enter_scope('submodel').find('actuator', 'b_0_0').tag, 'velocity') self.assertEqual( mujoco.enter_scope('submodel').find('actuator', 'b_0_0').joint, 'b_0_0') def testDefaultIdentifier(self): mujoco = element.RootElement(model='test') body = mujoco.worldbody.add('body') joint_0 = body.add('freejoint') joint_1 = body.add('joint', type='hinge') self.assertIsNone(body.name) self.assertIsNone(joint_0.name) self.assertIsNone(joint_1.name) self.assertEqual(str(body), '<body>...</body>') self.assertEqual(str(joint_0), '<freejoint/>') self.assertEqual(str(joint_1), '<joint class="/" type="hinge"/>') self.assertEqual(body.full_identifier, '//unnamed_body_0') self.assertStartsWith(body.to_xml_string(pretty_print=False), '<body name="{:s}">'.format(body.full_identifier)) self.assertEqual(joint_0.full_identifier, '//unnamed_joint_0') self.assertEqual(joint_0.to_xml_string(pretty_print=False), '<freejoint name="{:s}"/>'.format(joint_0.full_identifier)) self.assertEqual(joint_1.full_identifier, '//unnamed_joint_1') self.assertEqual(joint_1.to_xml_string(pretty_print=False), '<joint name="{:s}" class="/" type="hinge"/>'.format( joint_1.full_identifier)) submujoco = copy.copy(mujoco) submujoco.model = 'submodel' mujoco.attach(submujoco) submujoco_body = submujoco.worldbody.body[0] self.assertEqual(submujoco_body.full_identifier, 'submodel//unnamed_body_0') self.assertEqual(submujoco_body.freejoint.full_identifier, 'submodel//unnamed_joint_0') self.assertEqual(submujoco_body.joint[0].full_identifier, 'submodel//unnamed_joint_1') def testFindAll(self): mujoco = parser.from_path(_TEST_MODEL_XML) mujoco.model = 'model' submujoco = copy.copy(mujoco) submujoco.model = 'submodel' subsubmujoco = copy.copy(mujoco) subsubmujoco.model = 'subsubmodel' submujoco.find('site', 'attachment').attach(subsubmujoco) mujoco.attach(submujoco) geoms = mujoco.find_all('geom') self.assertLen(geoms, 6) self.assertEqual(geoms[0].root, mujoco) self.assertEqual(geoms[1].root, mujoco) self.assertEqual(geoms[2].root, submujoco) self.assertEqual(geoms[3].root, subsubmujoco) self.assertEqual(geoms[4].root, subsubmujoco) self.assertEqual(geoms[5].root, submujoco) b_0 = submujoco.find('body', 'b_0') self.assertLen(b_0.find_all('joint'), 6) self.assertLen(b_0.find_all('joint', immediate_children_only=True), 1) self.assertLen(b_0.find_all('joint', exclude_attachments=True), 2) def testFindAllFrameJoints(self): root_model = parser.from_path(_TEST_MODEL_XML) root_model.model = 'model' submodel = copy.copy(root_model) submodel.model = 'submodel' frame = root_model.attach(submodel) joint_x = frame.add('joint', type='slide', axis=[1, 0, 0]) joint_y = frame.add('joint', type='slide', axis=[0, 1, 0]) joints = frame.find_all('joint', immediate_children_only=True) self.assertListEqual(joints, [joint_x, joint_y]) def testDictLikeInterface(self): mujoco = element.RootElement(model='test') elem = mujoco.worldbody.add('body') with self.assertRaisesRegex(TypeError, 'object is not subscriptable'): _ = elem['foo'] with self.assertRaisesRegex(TypeError, 'does not support item assignment'): elem['foo'] = 'bar' with self.assertRaisesRegex(TypeError, 'does not support item deletion'): del elem['foo'] def testSetAndGetAttributes(self): mujoco = element.RootElement(model='test') foo_attribs = dict(name='foo', pos=[1, 2, 3, 4], quat=[0, 1, 0, 0]) with self.assertRaisesRegex(ValueError, 'no more than 3 entries'): foo = mujoco.worldbody.add('body', **foo_attribs) # failed creationg should not cause the identifier 'foo' to be registered with self.assertRaises(KeyError): mujoco.namescope.get('body', 'foo') foo_attribs['pos'] = [1, 2, 3] foo = mujoco.worldbody.add('body', **foo_attribs) self._test_attributes(foo, expected_values=foo_attribs) foo_attribs['name'] = 'bar' foo_attribs['pos'] = [1, 2, 3, 4] foo_attribs['childclass'] = 'klass' with self.assertRaisesRegex(ValueError, 'no more than 3 entries'): foo.set_attributes(**foo_attribs) # failed assignment should not cause the identifier 'bar' to be registered with self.assertRaises(KeyError): mujoco.namescope.get('body', 'bar') foo_attribs['pos'] = [1, 2, 3] foo.set_attributes(**foo_attribs) self._test_attributes(foo, expected_values=foo_attribs) actual_foo_attribs = foo.get_attributes() for attribute_name, value in foo_attribs.items(): np.testing.assert_array_equal( actual_foo_attribs.pop(attribute_name), value) for value in actual_foo_attribs.values(): self.assertIsNone(value) def testResolveReferences(self): resolved_model = parser.from_path(_TEST_MODEL_XML) self.assertIs( resolved_model.find('geom', 'b_1_0').material, resolved_model.find('material', 'mat_texture')) unresolved_model = parser.from_path( _TEST_MODEL_XML, resolve_references=False) self.assertEqual( unresolved_model.find('geom', 'b_1_0').material, 'mat_texture') unresolved_model.resolve_references() self.assertIs( unresolved_model.find('geom', 'b_1_0').material, unresolved_model.find('material', 'mat_texture')) @parameterized.named_parameters( ('WithoutInclude', _TEST_MODEL_XML), ('WithInclude', _MODEL_WITH_INCLUDE_PATH)) def testParseFromString(self, model_path): with open(model_path) as xml_file: xml_string = xml_file.read() model_dir, _ = os.path.split(model_path) parser.from_xml_string(xml_string, model_dir=model_dir) @parameterized.named_parameters( ('WithoutInclude', _TEST_MODEL_XML), ('WithInclude', _MODEL_WITH_INCLUDE_PATH)) def testParseFromFile(self, model_path): model_dir, _ = os.path.split(model_path) with open(model_path) as xml_file: parser.from_file(xml_file, model_dir=model_dir) @parameterized.named_parameters( ('WithoutInclude', _TEST_MODEL_XML), ('WithInclude', _MODEL_WITH_INCLUDE_PATH)) def testParseFromPath(self, model_path): parser.from_path(model_path) def testGetAssetFromFile(self): with open(_TEXTURE_PATH, 'rb') as f: contents = f.read() _, filename = os.path.split(_TEXTURE_PATH) prefix, extension = os.path.splitext(filename) vfs_filename = prefix + '-' + hashlib.sha1(contents).hexdigest() + extension mujoco = parser.from_path(_TEST_MODEL_XML) self.assertDictEqual({vfs_filename: contents}, mujoco.get_assets()) def testGetAssetFromPlaceholder(self): mujoco = parser.from_path(_TEST_MODEL_XML) # Add an extra texture asset from a placeholder. contents = b'I am a texture bytestring' extension = '.png' vfs_filename = hashlib.sha1(contents).hexdigest() + extension placeholder = mjcf.Asset(contents=contents, extension=extension) mujoco.asset.add('texture', name='fake_texture', file=placeholder) self.assertContainsSubset(set([(vfs_filename, contents)]), set(mujoco.get_assets().items())) def testGetAssetsFromDict(self): with open(_MODEL_WITH_INVALID_FILENAMES, 'rb') as f: xml_string = f.read() with open(_TEXTURE_PATH, 'rb') as f: texture_contents = f.read() with open(_MESH_PATH, 'rb') as f: mesh_contents = f.read() with open(_INCLUDED_WITH_INVALID_FILENAMES, 'rb') as f: included_xml_contents = f.read() assets = { 'invalid_texture_name.png': texture_contents, 'invalid_mesh_name.stl': mesh_contents, 'invalid_included_name.xml': included_xml_contents, } # The paths specified in the main and included XML files are deliberately # invalid, so the parser should fail unless the pre-loaded assets are passed # in as a dict. with self.assertRaises(IOError): parser.from_xml_string(xml_string=xml_string) mujoco = parser.from_xml_string(xml_string=xml_string, assets=assets) expected_assets = {} for path, contents in assets.items(): _, filename = os.path.split(path) prefix, extension = os.path.splitext(filename) if extension != '.xml': vfs_filename = ''.join( [prefix, '-', hashlib.sha1(contents).hexdigest(), extension]) expected_assets[vfs_filename] = contents self.assertDictEqual(expected_assets, mujoco.get_assets()) def testAssetsCanBeCopied(self): with open(_TEXTURE_PATH, 'rb') as f: contents = f.read() _, filename = os.path.split(_TEXTURE_PATH) prefix, extension = os.path.splitext(filename) vfs_filename = prefix + '-' + hashlib.sha1(contents).hexdigest() + extension mujoco = parser.from_path(_TEST_MODEL_XML) mujoco_copy = copy.copy(mujoco) expected = {vfs_filename: contents} self.assertDictEqual(expected, mujoco.get_assets()) self.assertDictEqual(expected, mujoco_copy.get_assets()) def testParseModelWithNamelessAssets(self): mujoco = parser.from_path(path=_MODEL_WITH_NAMELESS_ASSETS) expected_names_derived_from_filenames = [ ('mesh', 'cube'), # ./test_assets/meshes/cube.stl ('texture', 'deepmind'), # ./test_assets/textures/deepmind.png ('hfield', 'deepmind'), # ./test_assets/textures/deepmind.png ] with self.subTest('Expected asset names are present in the parsed model'): for namespace, name in expected_names_derived_from_filenames: self.assertIsNotNone(mujoco.find(namespace, name)) with self.subTest('Can compile and step the simulation'): physics = mjcf.Physics.from_mjcf_model(mujoco) physics.step() def testAssetInheritance(self): parent = element.RootElement(model='parent') child = element.RootElement(model='child') grandchild = element.RootElement(model='grandchild') ext = '.png' parent_str = b'I belong to the parent' child_str = b'I belong to the child' grandchild_str = b'I belong to the grandchild' parent_vfs_name, child_vfs_name, grandchild_vfs_name = ( hashlib.sha1(s).hexdigest() + ext for s in (parent_str, child_str, grandchild_str)) parent_ph = mjcf.Asset(contents=parent_str, extension=ext) child_ph = mjcf.Asset(contents=child_str, extension=ext) grandchild_ph = mjcf.Asset(contents=grandchild_str, extension=ext) parent.asset.add('texture', name='parent_tex', file=parent_ph) child.asset.add('texture', name='child_tex', file=child_ph) grandchild.asset.add('texture', name='grandchild_tex', file=grandchild_ph) parent.attach(child) child.attach(grandchild) # The grandchild should only return its own assets. self.assertDictEqual( {grandchild_vfs_name: grandchild_str}, grandchild.get_assets()) # The child should return its own assets plus those of the grandchild. self.assertDictEqual( {child_vfs_name: child_str, grandchild_vfs_name: grandchild_str}, child.get_assets()) # The parent should return everything. self.assertDictEqual( {parent_vfs_name: parent_str, child_vfs_name: child_str, grandchild_vfs_name: grandchild_str}, parent.get_assets()) def testActuatorReordering(self): def make_model_with_mixed_actuators(name): actuators = [] root = mjcf.RootElement(model=name) body = root.worldbody.add('body') body.add('geom', type='sphere', size=[0.1]) slider = body.add('joint', type='slide', name='slide_joint') # Third-order `general` actuator. actuators.append( root.actuator.add( 'general', dyntype='integrator', biastype='affine', dynprm=[1, 0, 0], joint=slider, name='general_act')) # Cylinder actuators are also third-order. actuators.append( root.actuator.add('cylinder', joint=slider, name='cylinder_act')) # A second-order actuator, added after the third-order actuators. actuators.append( root.actuator.add('velocity', joint=slider, name='velocity_act')) return root, actuators child_1, actuators_1 = make_model_with_mixed_actuators(name='child_1') child_2, actuators_2 = make_model_with_mixed_actuators(name='child_2') child_3, actuators_3 = make_model_with_mixed_actuators(name='child_3') parent = mjcf.RootElement() parent.attach(child_1) parent.attach(child_2) child_2.attach(child_3) # Check that the generated XML contains all of the actuators that we expect # it to have. expected_xml_strings = [ actuator.to_xml_string(prefix_root=parent.namescope) for actuator in actuators_1 + actuators_2 + actuators_3 ] xml_strings = [ util.to_native_string(etree.tostring(node, pretty_print=True)) for node in parent.to_xml().find('actuator').getchildren() ] self.assertSameElements(expected_xml_strings, xml_strings) # MuJoCo requires that all 3rd-order actuators (i.e. those with internal # dynamics) come after all 2nd-order actuators in the XML. Attempting to # compile this model will result in an error unless PyMJCF internally # reorders the actuators so that the 3rd-order actuator comes last in the # generated XML. _ = mjcf.Physics.from_mjcf_model(child_1) # Actuator re-ordering should also work in cases where there are multiple # attached submodels with mixed 2nd- and 3rd-order actuators. _ = mjcf.Physics.from_mjcf_model(parent) def testMaxConflictingValues(self): model_1 = mjcf.RootElement() model_1.size.nconmax = 123 model_1.size.njmax = 456 model_2 = mjcf.RootElement() model_2.size.nconmax = 345 model_2.size.njmax = 234 model_1.attach(model_2) self.assertEqual(model_1.size.nconmax, 345) self.assertEqual(model_1.size.njmax, 456) def testMaxBytesConflictingValues(self): model_1 = mjcf.RootElement() model_1.size.memory = '10000' model_2 = mjcf.RootElement() model_2.size.memory = '1M' model_1.attach(model_2) self.assertEqual(model_1.size.memory, '1048576') if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/mjcf/element_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 `dm_control.mjcf.attribute`.""" import contextlib import hashlib import os from absl.testing import absltest from absl.testing import parameterized from dm_control.mjcf import attribute from dm_control.mjcf import element from dm_control.mjcf import namescope from dm_control.mjcf import schema import numpy as np ASSETS_DIR = os.path.join(os.path.dirname(__file__), 'test_assets') FAKE_SCHEMA_FILENAME = 'attribute_test_schema.xml' ORIGINAL_SCHEMA_PATH = os.path.join(os.path.dirname(__file__), 'schema.xml') class AttributeTest(parameterized.TestCase): """Test for Attribute classes. Our tests here reflect actual usages of the Attribute classes, namely that we never directly create attributes but instead access them through Elements. """ def setUp(self): super().setUp() schema.override_schema(os.path.join(ASSETS_DIR, FAKE_SCHEMA_FILENAME)) self._alpha = namescope.NameScope('alpha', None) self._beta = namescope.NameScope('beta', None) self._beta.parent = self._alpha self._mujoco = element.RootElement() self._mujoco.namescope.parent = self._beta def tearDown(self): super().tearDown() schema.override_schema(ORIGINAL_SCHEMA_PATH) def assertXMLStringIsNone(self, mjcf_element, attribute_name): for prefix_root in (self._alpha, self._beta, self._mujoco.namescope, None): self.assertIsNone( mjcf_element.get_attribute_xml_string(attribute_name, prefix_root)) def assertXMLStringEqual(self, mjcf_element, attribute_name, expected): for prefix_root in (self._alpha, self._beta, self._mujoco.namescope, None): self.assertEqual( mjcf_element.get_attribute_xml_string(attribute_name, prefix_root), expected) def assertXMLStringIsCorrectlyScoped( self, mjcf_element, attribute_name, expected): for prefix_root in (self._alpha, self._beta, self._mujoco.namescope, None): self.assertEqual( mjcf_element.get_attribute_xml_string(attribute_name, prefix_root), self._mujoco.namescope.full_prefix(prefix_root) + expected) def assertCorrectXMLStringForDefaultsClass( self, mjcf_element, attribute_name, expected): for prefix_root in (self._alpha, self._beta, self._mujoco.namescope, None): self.assertEqual( mjcf_element.get_attribute_xml_string(attribute_name, prefix_root), (self._mujoco.namescope.full_prefix(prefix_root) + expected) or '/') def assertElementIsIdentifiedByName(self, mjcf_element, expected): self.assertEqual(mjcf_element.name, expected) self.assertEqual(self._mujoco.find(mjcf_element.spec.namespace, expected), mjcf_element) @contextlib.contextmanager def assertAttributeIsNoneWhenDone(self, mjcf_element, attribute_name): yield self.assertIsNone(getattr(mjcf_element, attribute_name)) self.assertXMLStringIsNone(mjcf_element, attribute_name) def assertCorrectClearBehavior(self, mjcf_element, attribute_name, required): if required: return self.assertRaisesRegex(AttributeError, 'is required') else: return self.assertAttributeIsNoneWhenDone(mjcf_element, attribute_name) def assertCorrectClearBehaviorByAllMethods( self, mjcf_element, attribute_name, required): original_value = getattr(mjcf_element, attribute_name) def reset_value(): setattr(mjcf_element, attribute_name, original_value) if original_value is not None: self.assertIsNotNone(getattr(mjcf_element, attribute_name)) # clear by using del with self.assertCorrectClearBehavior( mjcf_element, attribute_name, required): delattr(mjcf_element, attribute_name) # clear by assigning None reset_value() with self.assertCorrectClearBehavior( mjcf_element, attribute_name, required): setattr(mjcf_element, attribute_name, None) if isinstance(original_value, str): # clear by assigning empty string reset_value() with self.assertCorrectClearBehavior( mjcf_element, attribute_name, required): setattr(mjcf_element, attribute_name, '') def assertCanBeCleared(self, mjcf_element, attribute_name): self.assertCorrectClearBehaviorByAllMethods( mjcf_element, attribute_name, required=False) def assertCanNotBeCleared(self, mjcf_element, attribute_name): self.assertCorrectClearBehaviorByAllMethods( mjcf_element, attribute_name, required=True) def testFloatScalar(self): mujoco = self._mujoco mujoco.optional.float = 0.357357 self.assertEqual(mujoco.optional.float, 0.357357) self.assertEqual(type(mujoco.optional.float), float) with self.assertRaisesRegex(ValueError, 'Expect a float value'): mujoco.optional.float = 'five' # failed assignment should not change the value self.assertEqual(mujoco.optional.float, 0.357357) self.assertEqual( mujoco.optional.get_attribute_xml_string('float', precision=1), '0.4') self.assertEqual( mujoco.optional.get_attribute_xml_string('float', precision=2), '0.36') self.assertEqual( mujoco.optional.get_attribute_xml_string('float', precision=3), '0.357') self.assertEqual( mujoco.optional.get_attribute_xml_string('float', precision=4), '0.3574') self.assertEqual( mujoco.optional.get_attribute_xml_string('float', precision=5), '0.35736') self.assertEqual( mujoco.optional.get_attribute_xml_string('float', precision=6), '0.357357') self.assertEqual( mujoco.optional.get_attribute_xml_string('float', precision=7), '0.357357') self.assertEqual( mujoco.optional.get_attribute_xml_string('float', precision=8), '0.357357') def testIntScalar(self): mujoco = self._mujoco mujoco.optional.int = 12345 self.assertEqual(mujoco.optional.int, 12345) self.assertEqual(type(mujoco.optional.int), int) with self.assertRaisesRegex(ValueError, 'Expect an integer value'): mujoco.optional.int = 10.5 # failed assignment should not change the value self.assertEqual(mujoco.optional.int, 12345) self.assertXMLStringEqual(mujoco.optional, 'int', '12345') self.assertCanBeCleared(mujoco.optional, 'int') def testStringScalar(self): mujoco = self._mujoco mujoco.optional.string = 'foobar' self.assertEqual(mujoco.optional.string, 'foobar') self.assertXMLStringEqual(mujoco.optional, 'string', 'foobar') with self.assertRaisesRegex(ValueError, 'Expect a string value'): mujoco.optional.string = mujoco.optional self.assertCanBeCleared(mujoco.optional, 'string') def testFloatArray(self): mujoco = self._mujoco mujoco.optional.float_array = [3, 2, 1] np.testing.assert_array_equal(mujoco.optional.float_array, [3, 2, 1]) self.assertEqual(mujoco.optional.float_array.dtype, float) with self.assertRaisesRegex(ValueError, 'no more than 3 entries'): mujoco.optional.float_array = [0, 0, 0, -10] with self.assertRaisesRegex(ValueError, 'one-dimensional array'): mujoco.optional.float_array = np.array([[1, 2], [3, 4]]) # failed assignments should not change the value np.testing.assert_array_equal(mujoco.optional.float_array, [3, 2, 1]) # XML string should not be affected by global print options np.set_printoptions(precision=3, suppress=True) mujoco.optional.float_array = [np.pi, 2, 1e-16] self.assertXMLStringEqual(mujoco.optional, 'float_array', '3.1415926535897931 2 9.9999999999999998e-17') self.assertEqual( mujoco.optional.get_attribute_xml_string('float_array', precision=5), '3.1416 2 1e-16') self.assertEqual( mujoco.optional.get_attribute_xml_string( 'float_array', precision=5, zero_threshold=1e-10), '3.1416 2 0') self.assertCanBeCleared(mujoco.optional, 'float_array') def testFormatVeryLargeArray(self): mujoco = self._mujoco array = np.arange(2000, dtype=np.double) mujoco.optional.huge_float_array = array xml_string = mujoco.optional.get_attribute_xml_string('huge_float_array') self.assertNotIn('...', xml_string) # Check that array <--> string conversion is a round trip. mujoco.optional.huge_float_array = None self.assertIsNone(mujoco.optional.huge_float_array) mujoco.optional.huge_float_array = xml_string np.testing.assert_array_equal(mujoco.optional.huge_float_array, array) def testIntArray(self): mujoco = self._mujoco mujoco.optional.int_array = [2, 2] np.testing.assert_array_equal(mujoco.optional.int_array, [2, 2]) self.assertEqual(mujoco.optional.int_array.dtype, int) with self.assertRaisesRegex(ValueError, 'no more than 2 entries'): mujoco.optional.int_array = [0, 0, 10] # failed assignment should not change the value np.testing.assert_array_equal(mujoco.optional.int_array, [2, 2]) self.assertXMLStringEqual(mujoco.optional, 'int_array', '2 2') self.assertCanBeCleared(mujoco.optional, 'int_array') def testKeyword(self): mujoco = self._mujoco valid_values = ['Alpha', 'Beta', 'Gamma'] for value in valid_values: mujoco.optional.keyword = value.lower() self.assertEqual(mujoco.optional.keyword, value) self.assertXMLStringEqual(mujoco.optional, 'keyword', value) mujoco.optional.keyword = value.upper() self.assertEqual(mujoco.optional.keyword, value) self.assertXMLStringEqual(mujoco.optional, 'keyword', value) with self.assertRaisesRegex(ValueError, str(valid_values)): mujoco.optional.keyword = 'delta' # failed assignment should not change the value self.assertXMLStringEqual(mujoco.optional, 'keyword', valid_values[-1]) self.assertCanBeCleared(mujoco.optional, 'keyword') def testKeywordFalseTrueAuto(self): mujoco = self._mujoco for value in ('false', 'False', False): mujoco.optional.fta = value self.assertEqual(mujoco.optional.fta, 'false') self.assertXMLStringEqual(mujoco.optional, 'fta', 'false') for value in ('true', 'True', True): mujoco.optional.fta = value self.assertEqual(mujoco.optional.fta, 'true') self.assertXMLStringEqual(mujoco.optional, 'fta', 'true') for value in ('auto', 'AUTO'): mujoco.optional.fta = value self.assertEqual(mujoco.optional.fta, 'auto') self.assertXMLStringEqual(mujoco.optional, 'fta', 'auto') for value in (None, ''): mujoco.optional.fta = value self.assertIsNone(mujoco.optional.fta) self.assertXMLStringEqual(mujoco.optional, 'fta', None) def testIdentifier(self): mujoco = self._mujoco entity = mujoco.worldentity.add('entity') subentity_1 = entity.add('subentity', name='foo') subentity_2 = entity.add('subentity_alias', name='bar') self.assertIsNone(entity.name) self.assertElementIsIdentifiedByName(subentity_1, 'foo') self.assertElementIsIdentifiedByName(subentity_2, 'bar') self.assertXMLStringIsCorrectlyScoped(subentity_1, 'name', 'foo') self.assertXMLStringIsCorrectlyScoped(subentity_2, 'name', 'bar') with self.assertRaisesRegex(ValueError, 'Expect a string value'): subentity_2.name = subentity_1 with self.assertRaisesRegex(ValueError, 'reserved for scoping'): subentity_2.name = 'foo/bar' with self.assertRaisesRegex(ValueError, 'Duplicated identifier'): subentity_2.name = 'foo' # failed assignment should not change the value self.assertElementIsIdentifiedByName(subentity_2, 'bar') with self.assertRaisesRegex(ValueError, 'cannot be named \'world\''): mujoco.worldentity.add('body', name='world') subentity_1.name = 'baz' self.assertElementIsIdentifiedByName(subentity_1, 'baz') self.assertIsNone(mujoco.find('subentity', 'foo')) # 'foo' is now unused, so we should be allowed to use it subentity_2.name = 'foo' self.assertElementIsIdentifiedByName(subentity_2, 'foo') # duplicate name should be allowed when in different namespaces entity.name = 'foo' self.assertElementIsIdentifiedByName(entity, 'foo') self.assertCanBeCleared(entity, 'name') def testStringReference(self): mujoco = self._mujoco mujoco.optional.reference = 'foo' self.assertEqual(mujoco.optional.reference, 'foo') self.assertXMLStringIsCorrectlyScoped(mujoco.optional, 'reference', 'foo') self.assertCanBeCleared(mujoco.optional, 'reference') def testElementReferenceWithFixedNamespace(self): mujoco = self._mujoco # `mujoco.optional.fixed_type_ref` must be an element in the 'optional' # namespace. 'identified' elements are part of the 'optional' namespace. bar = mujoco.add('identified', identifier='bar') mujoco.optional.fixed_type_ref = bar self.assertXMLStringIsCorrectlyScoped( mujoco.optional, 'fixed_type_ref', 'bar') # Removing the referenced entity should cause the `fixed_type_ref` to be set # to None. bar.remove() self.assertIsNone(mujoco.optional.fixed_type_ref) def testElementReferenceWithVariableNamespace(self): mujoco = self._mujoco # `mujoco.optional.reference` can be an element in either the 'entity' or # or 'optional' namespaces. First we assign an 'identified' element to the # reference attribute. These are part of the 'optional' namespace. bar = mujoco.add('identified', identifier='bar') mujoco.optional.reftype = 'optional' mujoco.optional.reference = bar self.assertXMLStringIsCorrectlyScoped(mujoco.optional, 'reference', 'bar') # Assigning to `mujoco.optional.reference` should also change the value of # `mujoco.optional.reftype` to match the namespace of the element that was # assigned to `mujoco.optional.reference` self.assertXMLStringEqual(mujoco.optional, 'reftype', 'optional') # Now assign an 'entity' element to the reference attribute. These are part # of the 'entity' namespace. baz = mujoco.worldentity.add('entity', name='baz') mujoco.optional.reftype = 'entity' mujoco.optional.reference = baz self.assertXMLStringIsCorrectlyScoped(mujoco.optional, 'reference', 'baz') # The `reftype` should change to 'entity' accordingly. self.assertXMLStringEqual(mujoco.optional, 'reftype', 'entity') # Removing the referenced entity should cause the `reference` and `reftype` # to be set to None. baz.remove() self.assertIsNone(mujoco.optional.reference) self.assertIsNone(mujoco.optional.reftype) def testInvalidReference(self): mujoco = self._mujoco bar = mujoco.worldentity.add('entity', name='bar') baz = bar.add('subentity', name='baz') mujoco.optional.reftype = 'entity' with self.assertRaisesWithLiteralMatch( ValueError, attribute._INVALID_REFERENCE_TYPE.format( valid_type='entity', actual_type='subentity')): mujoco.optional.reference = baz with self.assertRaisesWithLiteralMatch( ValueError, attribute._INVALID_REFERENCE_TYPE.format( valid_type='optional', actual_type='subentity')): mujoco.optional.fixed_type_ref = baz def testDefaults(self): mujoco = self._mujoco # Unnamed global defaults class should become a properly named and scoped # class with a trailing slash self.assertIsNone(mujoco.default.dclass) self.assertCorrectXMLStringForDefaultsClass(mujoco.default, 'class', '') # An element without an explicit dclass should be assigned to the properly # scoped global defaults class entity = mujoco.worldentity.add('entity') subentity = entity.add('subentity') self.assertIsNone(subentity.dclass) self.assertCorrectXMLStringForDefaultsClass(subentity, 'class', '') # Named global defaults class should gain scoping prefix mujoco.default.dclass = 'main' self.assertEqual(mujoco.default.dclass, 'main') self.assertCorrectXMLStringForDefaultsClass(mujoco.default, 'class', 'main') self.assertCorrectXMLStringForDefaultsClass(subentity, 'class', 'main') # Named subordinate defaults class should gain scoping prefix sub_default = mujoco.default.add('default', dclass='sub') self.assertEqual(sub_default.dclass, 'sub') self.assertCorrectXMLStringForDefaultsClass(sub_default, 'class', 'sub') # An element without an explicit dclass but belongs to a childclassed # parent should be left alone entity.childclass = 'sub' self.assertEqual(entity.childclass, 'sub') self.assertCorrectXMLStringForDefaultsClass(entity, 'childclass', 'sub') self.assertXMLStringIsNone(subentity, 'class') # An element WITH an explicit dclass should be left alone have it properly # scoped regardless of whether it belongs to a childclassed parent or not. subentity.dclass = 'main' self.assertCorrectXMLStringForDefaultsClass(subentity, 'class', 'main') @parameterized.named_parameters( ('NoBasepath', '', os.path.join(ASSETS_DIR, FAKE_SCHEMA_FILENAME)), ('WithBasepath', ASSETS_DIR, FAKE_SCHEMA_FILENAME)) def testFileFromPath(self, basepath, value): mujoco = self._mujoco full_path = os.path.join(basepath, value) with open(full_path, 'rb') as f: contents = f.read() _, basename = os.path.split(value) prefix, extension = os.path.splitext(basename) expected_xml = prefix + '-' + hashlib.sha1(contents).hexdigest() + extension mujoco.files.text_path = basepath text_file = mujoco.files.add('text', file=value) expected_value = attribute.Asset( contents=contents, extension=extension, prefix=prefix) self.assertEqual(text_file.file, expected_value) self.assertXMLStringEqual(text_file, 'file', expected_xml) self.assertCanBeCleared(text_file, 'file') self.assertCanBeCleared(mujoco.files, 'text_path') def testFileFromPlaceholder(self): mujoco = self._mujoco contents = b'Fake contents' extension = '.whatever' expected_xml = hashlib.sha1(contents).hexdigest() + extension placeholder = attribute.Asset(contents=contents, extension=extension) text_file = mujoco.files.add('text', file=placeholder) self.assertEqual(text_file.file, placeholder) self.assertXMLStringEqual(text_file, 'file', expected_xml) self.assertCanBeCleared(text_file, 'file') def testFileFromAssetsDict(self): prefix = 'fake_filename' extension = '.whatever' path = 'invalid/path/' + prefix + extension contents = 'Fake contents' assets = {path: contents} mujoco = element.RootElement(assets=assets) text_file = mujoco.files.add('text', file=path) expected_value = attribute.Asset( contents=contents, extension=extension, prefix=prefix) self.assertEqual(text_file.file, expected_value) def testFileExceptions(self): mujoco = self._mujoco text_file = mujoco.files.add('text') with self.assertRaisesRegex(ValueError, 'Expect either a string or `Asset` value'): text_file.file = mujoco.optional def testBasePathExceptions(self): mujoco = self._mujoco with self.assertRaisesRegex(ValueError, 'Expect a string value'): mujoco.files.text_path = mujoco.optional def testRequiredAttributes(self): mujoco = self._mujoco attributes = ( ('float', 1.0), ('int', 2), ('string', 'foobar'), ('float_array', [1.5, 2.5, 3.5]), ('int_array', [4, 5]), ('keyword', 'alpha'), ('identifier', 'thing'), ('reference', 'other_thing'), ('basepath', ASSETS_DIR), ('file', FAKE_SCHEMA_FILENAME) ) # Removing any one of the required attributes should cause initialization # of a new element to fail for name, _ in attributes: attributes_dict = {key: value for key, value in attributes if key != name} with self.assertRaisesRegex(AttributeError, name + '.+ is required'): mujoco.add('required', **attributes_dict) attributes_dict = {key: value for key, value in attributes} mujoco.add('required', **attributes_dict) # Should not be allowed to clear each required attribute after the fact for name, _ in attributes: self.assertCanNotBeCleared(mujoco.required, name) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/mjcf/attribute_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 dm_control.mjcf.skin.""" import os from absl.testing import absltest from dm_control.mjcf import skin from dm_control.utils import io as resources ASSETS_DIR = os.path.join(os.path.dirname(__file__), 'test_assets') SKIN_FILE_PATH = os.path.join(ASSETS_DIR, 'skins/test_skin.skn') class FakeMJCFBody: def __init__(self, full_identifier): self.full_identifier = full_identifier class SkinTest(absltest.TestCase): def test_can_parse_and_write_back(self): contents = resources.GetResource(SKIN_FILE_PATH, mode='rb') parsed = skin.parse(contents, body_getter=FakeMJCFBody) reconstructed = skin.serialize(parsed) self.assertEqual(reconstructed, contents) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/mjcf/skin_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 `dm_control.mjcf.export_with_assets`.""" import os from absl import flags from absl.testing import absltest from absl.testing import parameterized from dm_control import mjcf from dm_control.mujoco import wrapper from dm_control.mujoco.wrapper import util FLAGS = flags.FLAGS _ASSETS_DIR = os.path.join(os.path.dirname(__file__), 'test_assets') _TEST_MODEL_WITH_ASSETS = os.path.join(_ASSETS_DIR, 'model_with_assets.xml') _TEST_MODEL_WITHOUT_ASSETS = os.path.join(_ASSETS_DIR, 'lego_brick.xml') def setUpModule(): # Flags are not parsed when this test is invoked by `nosetests`, so we fall # back on using the default value for ``--test_tmpdir`. if not FLAGS.is_parsed(): FLAGS.test_tmpdir = absltest.get_default_test_tmpdir() FLAGS.mark_as_parsed() class ExportWithAssetsTest(parameterized.TestCase): @parameterized.named_parameters( ('with_assets', _TEST_MODEL_WITH_ASSETS, 'mujoco_with_assets.xml'), ('without_assets', _TEST_MODEL_WITHOUT_ASSETS, 'mujoco.xml'),) def test_export_model(self, xml_path, out_xml_name): """Save processed MJCF model.""" out_dir = self.create_tempdir().full_path mjcf_model = mjcf.from_path(xml_path) mjcf.export_with_assets( mjcf_model, out_dir=out_dir, out_file_name=out_xml_name) # Read the files in the output directory and put their contents in a dict. out_dir_contents = {} for filename in os.listdir(out_dir): with open(os.path.join(out_dir, filename), 'rb') as f: out_dir_contents[filename] = f.read() # Check that the output directory contains an XML file of the correct name. self.assertIn(out_xml_name, out_dir_contents) # Check that its contents match the output of `mjcf_model.to_xml_string()`. xml_contents = util.to_native_string(out_dir_contents.pop(out_xml_name)) expected_xml_contents = mjcf_model.to_xml_string() self.assertEqual(xml_contents, expected_xml_contents) # Check that the other files in the directory match the contents of the # model's `assets` dict. assets = mjcf_model.get_assets() self.assertDictEqual(out_dir_contents, assets) # Check that we can construct an MjModel instance using the path to the # output file. from_exported = wrapper.MjModel.from_xml_path( os.path.join(out_dir, out_xml_name)) # Check that this model is identical to one constructed directly from # `mjcf_model`. from_mjcf = wrapper.MjModel.from_xml_string( expected_xml_contents, assets=assets) self.assertEqual(from_exported.to_bytes(), from_mjcf.to_bytes()) def test_default_model_filename(self): out_dir = self.create_tempdir().full_path mjcf_model = mjcf.from_path(_TEST_MODEL_WITH_ASSETS) mjcf.export_with_assets(mjcf_model, out_dir, out_file_name=None) expected_name = mjcf_model.model + '.xml' self.assertTrue(os.path.isfile(os.path.join(out_dir, expected_name))) def test_exceptions(self): out_dir = self.create_tempdir().full_path mjcf_model = mjcf.from_path(_TEST_MODEL_WITH_ASSETS) with self.assertRaisesRegex(ValueError, 'must end with \'.xml\''): mjcf.export_with_assets(mjcf_model, out_dir, out_file_name='invalid_extension.png') if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/mjcf/export_with_assets_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. # ============================================================================ """Saves Mujoco models with relevant assets.""" import os from dm_control.mjcf import constants from dm_control.mujoco.wrapper import util def export_with_assets(mjcf_model, out_dir, out_file_name=None, *, precision=constants.XML_DEFAULT_PRECISION, zero_threshold=0): """Saves mjcf.model in the given directory in MJCF (XML) format. Creates an MJCF XML file named `out_file_name` in the specified `out_dir`, and writes all of its assets into the same directory. Args: mjcf_model: `mjcf.RootElement` instance to export. out_dir: Directory to save the model and assets. Will be created if it does not already exist. out_file_name: (Optional) Name of the XML file to create. Defaults to the model name (`mjcf_model.model`) suffixed with '.xml'. precision: (optional) Number of digits to output for floating point quantities. zero_threshold: (optional) When outputting XML, floating point quantities whose absolute value falls below this threshold will be treated as zero. Raises: ValueError: If `out_file_name` is a string that does not end with '.xml'. """ if out_file_name is None: out_file_name = mjcf_model.model + '.xml' elif not out_file_name.lower().endswith('.xml'): raise ValueError('If `out_file_name` is specified it must end with ' '\'.xml\': got {}'.format(out_file_name)) assets = mjcf_model.get_assets() # This should never happen because `mjcf` does not support `.xml` assets. assert out_file_name not in assets assets[out_file_name] = mjcf_model.to_xml_string( precision=precision, zero_threshold=zero_threshold) if not os.path.exists(out_dir): os.makedirs(out_dir) for filename, contents in assets.items(): with open(os.path.join(out_dir, filename), 'wb') as f: f.write(util.to_binary_string(contents))
dm_control-main
dm_control/mjcf/export_with_assets.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. # ============================================================================ """Constructs models for debugging_test.py. The purpose of this file is to provide "golden" source line numbers for test cases in debugging_test.py. When this module is loaded, it inspects its own source code to look for lines that begin with `# !!LINE_REF`, and stores the following line number in a dict. This allows test cases to look up the line number by name, rather than brittly hard-coding in the line number. """ import collections import os import re from dm_control import mjcf SourceLine = collections.namedtuple( 'SourceLine', ('line_number', 'text')) LINE_REF = {} def make_valid_model(): # !!LINE_REF make_valid_model.mjcf_model mjcf_model = mjcf.RootElement() # !!LINE_REF make_valid_model.my_body my_body = mjcf_model.worldbody.add('body', name='my_body') my_body.add('inertial', mass=1, pos=[0, 0, 0], diaginertia=[1, 1, 1]) # !!LINE_REF make_valid_model.my_joint my_joint = my_body.add('joint', name='my_joint', type='hinge') # !!LINE_REF make_valid_model.my_actuator mjcf_model.actuator.add('velocity', name='my_actuator', joint=my_joint) return mjcf_model def make_broken_model(): # !!LINE_REF make_broken_model.mjcf_model mjcf_model = mjcf.RootElement() # !!LINE_REF make_broken_model.my_body my_body = mjcf_model.worldbody.add('body', name='my_body') my_body.add('inertial', mass=1, pos=[0, 0, 0], diaginertia=[1, 1, 1]) # !!LINE_REF make_broken_model.my_joint my_body.add('joint', name='my_joint', type='hinge') # !!LINE_REF make_broken_model.my_actuator mjcf_model.actuator.add('velocity', name='my_actuator', joint='invalid_joint') return mjcf_model def break_valid_model(mjcf_model): # !!LINE_REF break_valid_model.my_actuator.joint mjcf_model.find('actuator', 'my_actuator').joint = 'invalid_joint' return mjcf_model def _parse_line_refs(): line_ref_pattern = re.compile(r'\s*# !!LINE_REF\s*([^\s]+)') filename, _ = os.path.splitext(__file__) # __file__ can be `.pyc`. with open(filename + '.py') as f: src = f.read() src_lines = src.split('\n') for line_number, line in enumerate(src_lines): match = line_ref_pattern.match(line) if match: LINE_REF[match.group(1)] = SourceLine( line_number + 2, src_lines[line_number + 1].strip()) _parse_line_refs()
dm_control-main
dm_control/mjcf/code_for_debugging_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. # ============================================================================ """Base class for all MJCF elements in the object model.""" import abc from dm_control.mjcf import constants class Element(metaclass=abc.ABCMeta): """Abstract base class for an MJCF element. This class is provided so that `isinstance(foo, Element)` is `True` for all Element-like objects. We do not implement the actual element here because the actual object returned from traversing the object hierarchy is a weakproxy-like proxy to an actual element. This is because we do not allow orphaned non-root elements, so when a particular element is removed from the tree, all references held automatically become invalid. """ __slots__ = [] @abc.abstractmethod def get_init_stack(self): """Gets the stack trace where this element was first initialized.""" @abc.abstractmethod def get_last_modified_stacks_for_all_attributes(self): """Gets a dict of stack traces where each attribute was last modified.""" @abc.abstractmethod def is_same_as(self, other): """Checks whether another element is semantically equivalent to this one. Two elements are considered equivalent if they have the same specification (i.e. same tag appearing in the same context), the same attribute values, and all of their children are equivalent. The ordering of non-repeated children is not important for this comparison, while the ordering of repeated children are important only amongst the same type* of children. In other words, for two bodies to be considered equivalent, their child sites must appear in the same order, and their child geoms must appear in the same order, but permutations between sites and geoms are disregarded. (The only exception is in tendon definition, where strict ordering of all children is necessary for equivalence.) *Note that the notion of "same type" in this function is very loose: for example different actuator element subtypes are treated as separate types when children ordering is considered. Therefore, two <actuator> elements might be considered equivalent even though they result in different orderings of `mjData.ctrl` when compiled. As it stands, this function is designed primarily as a testing aid and should not be used to guarantee that models are actually identical. Args: other: An `mjcf.Element` Returns: `True` if `other` element is semantically equivalent to this one. """ @property @abc.abstractmethod def tag(self): pass @property @abc.abstractmethod def spec(self): pass @property @abc.abstractmethod def parent(self): pass @property @abc.abstractmethod def namescope(self): pass @property @abc.abstractmethod def root(self): pass @abc.abstractmethod def prefixed_identifier(self, prefix_root): pass @property @abc.abstractmethod def full_identifier(self): """Fully-qualified identifier used for this element in the generated XML.""" @abc.abstractmethod def find(self, namespace, identifier): """Finds an element with a particular identifier. This function allows the direct access to an arbitrarily deeply nested child element by name, without the need to manually traverse through the object tree. The `namespace` argument specifies the kind of element to find. In most cases, this corresponds to the element's XML tag name. However, if an element has multiple specialized tags, then the namespace corresponds to the tag name of the most general element of that kind. For example, `namespace='joint'` would search for `<joint>` and `<freejoint>`, while `namespace='actuator'` would search for `<general>`, `<motor>`, `<position>`, `<velocity>`, and `<cylinder>`. Args: namespace: A string specifying the namespace being searched. See the docstring above for explanation. identifier: The identifier string of the desired element. Returns: An `mjcf.Element` object, or `None` if an element with the specified identifier is not found. Raises: ValueError: if either `namespace` or `identifier` is not a string, or if `namespace` is not a valid namespace. """ @abc.abstractmethod def find_all(self, namespace, immediate_children_only=False, exclude_attachments=False): """Finds all elements of a particular kind. The `namespace` argument specifies the kind of element to find. In most cases, this corresponds to the element's XML tag name. However, if an element has multiple specialized tags, then the namespace corresponds to the tag name of the most general element of that kind. For example, `namespace='joint'` would search for `<joint>` and `<freejoint>`, while `namespace='actuator'` would search for `<general>`, `<motor>`, `<position>`, `<velocity>`, and `<cylinder>`. Args: namespace: A string specifying the namespace being searched. See the docstring above for explanation. immediate_children_only: (optional) A boolean, if `True` then only the immediate children of this element are returned. exclude_attachments: (optional) A boolean, if `True` then elements belonging to attached models are excluded. Returns: A list of `mjcf.Element`. Raises: ValueError: if `namespace` is not a valid namespace. """ @abc.abstractmethod def enter_scope(self, scope_identifier): """Finds the root element of the given scope and returns it. This function allows the access to a nested scope that is a child of this element. The `scope_identifier` argument specifies the path to the child scope element. Args: scope_identifier: The path of the desired scope element. Returns: An `mjcf.Element` object, or `None` if a scope element with the specified path is not found. """ @abc.abstractmethod def get_attribute_xml_string(self, attribute_name, prefix_root=None): pass @abc.abstractmethod def get_attributes(self): pass @abc.abstractmethod def set_attributes(self, **kwargs): pass @abc.abstractmethod def get_children(self, element_name): pass @abc.abstractmethod def add(self, element_name, **kwargs): """Add a new child element to this element. Args: element_name: The tag of the element to add. **kwargs: Attributes of the new element being created. Raises: ValueError: If the 'element_name' is not a valid child, or if an invalid attribute is specified in `kwargs`. Returns: An `mjcf.Element` corresponding to the newly created child element. """ @abc.abstractmethod def remove(self, affect_attachments=False): """Removes this element from the model.""" @property @abc.abstractmethod def is_removed(self): pass @abc.abstractmethod def all_children(self): pass @abc.abstractmethod def to_xml(self, prefix_root=None, debug_context=None, *, precision=constants.XML_DEFAULT_PRECISION, zero_threshold=0): """Generates an etree._Element corresponding to this MJCF element. Args: prefix_root: (optional) A `NameScope` object to be treated as root for the purpose of calculating the prefix. If `None` then no prefix is included. debug_context: (optional) A `debugging.DebugContext` object to which the debugging information associated with the generated XML is written. This is intended for internal use within PyMJCF; users should never need manually pass this argument. precision: (optional) Number of digits to output for floating point quantities. zero_threshold: (optional) When outputting XML, floating point quantities whose absolute value falls below this threshold will be treated as zero. Returns: An etree._Element object. """ @abc.abstractmethod def to_xml_string(self, prefix_root=None, self_only=False, pretty_print=True, debug_context=None, *, precision=constants.XML_DEFAULT_PRECISION, zero_threshold=0): """Generates an XML string corresponding to this MJCF element. Args: prefix_root: (optional) A `NameScope` object to be treated as root for the purpose of calculating the prefix. If `None` then no prefix is included. self_only: (optional) A boolean, whether to generate an XML corresponding only to this element without any children. pretty_print: (optional) A boolean, whether to the XML string should be properly indented. debug_context: (optional) A `debugging.DebugContext` object to which the debugging information associated with the generated XML is written. This is intended for internal use within PyMJCF; users should never need manually pass this argument. precision: (optional) Number of digits to output for floating point quantities. zero_threshold: (optional) When outputting XML, floating point quantities whose absolute value falls below this threshold will be treated as zero. Returns: A string. """ @abc.abstractmethod def resolve_references(self): pass
dm_control-main
dm_control/mjcf/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. # ============================================================================ """Helper object for keeping track of new elements created when copying MJCF.""" from dm_control.mjcf import constants class Copier: """Helper for keeping track of new elements created when copying MJCF.""" def __init__(self, source): if source._attachments: # pylint: disable=protected-access raise NotImplementedError('Cannot copy from elements with attachments') self._source = source def copy_into(self, destination, override_attributes=False): """Copies this copier's element into a destination MJCF element.""" newly_created_elements = {} destination._check_valid_attachment(self._source) # pylint: disable=protected-access if override_attributes: destination.set_attributes(**self._source.get_attributes()) else: destination._sync_attributes(self._source, copying=True) # pylint: disable=protected-access for source_child in self._source.all_children(): dest_child = None # First, if source_child has an identifier, we look for an existing child # element of self with the same identifier to override. if source_child.spec.identifier and override_attributes: identifier_attr = source_child.spec.identifier if identifier_attr == constants.CLASS: identifier_attr = constants.DCLASS identifier = getattr(source_child, identifier_attr) if identifier: dest_child = destination.find(source_child.spec.namespace, identifier) if dest_child is not None and dest_child.parent is not destination: raise ValueError( '<{}> with identifier {!r} is already a child of another element' .format(source_child.spec.namespace, identifier)) # Next, we cover the case where either the child is not a repeated element # or if source_child has an identifier attribute but it isn't set. if not source_child.spec.repeated and dest_child is None: dest_child = destination.get_children(source_child.tag) # Add a new element if dest_child doesn't exist, either because it is # supposed to be a repeated child, or because it's an uncreated on-demand. if dest_child is None: dest_child = destination.add( source_child.tag, **source_child.get_attributes()) newly_created_elements[source_child] = dest_child override_child_attributes = True else: override_child_attributes = override_attributes # Finally, copy attributes into dest_child. child_copier = Copier(source_child) newly_created_elements.update( child_copier.copy_into(dest_child, override_child_attributes)) return newly_created_elements
dm_control-main
dm_control/mjcf/copier.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 to manage the scoping of identifiers in MJCF models.""" import collections from dm_control.mjcf import constants class NameScope: """A name scoping context for an MJCF model. This object maintains the uniqueness of identifiers within each MJCF namespace. Examples of MJCF namespaces include 'body', 'joint', and 'geom'. Each namescope also carries a name, and can have a parent namescope. When MJCF models are merged, all identifiers gain a hierarchical prefix separated by '/', which is the concatenation of all scope names up to the root namescope. """ def __init__(self, name, mjcf_model, model_dir='', assets=None): """Initializes a scope with the given name. Args: name: The scope's name mjcf_model: The RootElement of the MJCF model associated with this scope. model_dir: (optional) Path to the directory containing the model XML file. This is used to prefix the paths of all asset files. assets: (optional) A dictionary of pre-loaded assets, of the form `{filename: bytestring}`. If present, PyMJCF will search for assets in this dictionary before attempting to load them from the filesystem. """ self._parent = None self._name = name self._mjcf_model = mjcf_model self._namespaces = collections.defaultdict(dict) self._model_dir = model_dir self._files = set() self._assets = assets or {} self._revision = 0 @property def revision(self): return self._revision def increment_revision(self): self._revision += 1 for namescope in self._namespaces['namescope'].values(): namescope.increment_revision() @property def name(self): """This scope's name.""" return self._name @property def files(self): """A set containing the `File` attributes registered in this scope.""" return self._files @property def assets(self): """A dictionary containing pre-loaded assets.""" return self._assets @property def model_dir(self): """Path to the directory containing the model XML file.""" return self._model_dir @name.setter def name(self, new_name): if self._parent: self._parent.add('namescope', new_name, self) self._parent.remove('namescope', self._name) self._name = new_name self.increment_revision() @property def mjcf_model(self): return self._mjcf_model @property def parent(self): """This parent `NameScope`, or `None` if this is a root scope.""" return self._parent @parent.setter def parent(self, new_parent): if self._parent: self._parent.remove('namescope', self._name) self._parent = new_parent if self._parent: self._parent.add('namescope', self._name, self) self.increment_revision() @property def root(self): if self._parent is None: return self else: return self._parent.root def full_prefix(self, prefix_root=None, as_list=False): """The prefix for identifiers belonging to this scope. Args: prefix_root: (optional) A `NameScope` object to be treated as root for the purpose of calculating the prefix. If `None` then no prefix is produced. as_list: (optional) A boolean, if `True` return the list of prefix components. If `False`, return the full prefix string separated by `mjcf.constants.PREFIX_SEPARATOR`. Returns: The prefix string. """ prefix_root = prefix_root or self if prefix_root != self and self._parent: prefix_list = self._parent.full_prefix(prefix_root, as_list=True) prefix_list.append(self._name) else: prefix_list = [] if as_list: return prefix_list else: if prefix_list: prefix_list.append('') return constants.PREFIX_SEPARATOR.join(prefix_list) def _assign(self, namespace, identifier, obj): """Checks a proposed identifier's validity before assigning to an object.""" namespace_dict = self._namespaces[namespace] if not isinstance(identifier, str): raise ValueError( 'Identifier must be a string: got {}'.format(type(identifier))) elif constants.PREFIX_SEPARATOR in identifier: raise ValueError( 'Identifier cannot contain {!r}: got {}' .format(constants.PREFIX_SEPARATOR, identifier)) else: namespace_dict[identifier] = obj def add(self, namespace, identifier, obj): """Add an identifier to this name scope. Args: namespace: A string specifying the namespace to which the identifier belongs. identifier: The identifier string. obj: The object referred to by the identifier. Raises: ValueError: If `identifier` not valid. """ namespace_dict = self._namespaces[namespace] if identifier in namespace_dict: raise ValueError('Duplicated identifier {!r} in namespace <{}>' .format(identifier, namespace)) else: self._assign(namespace, identifier, obj) self.increment_revision() def replace(self, namespace, identifier, obj): """Reassociates an identifier with a different object. Args: namespace: A string specifying the namespace to which the identifier belongs. identifier: The identifier string. obj: The object referred to by the identifier. Raises: ValueError: If `identifier` not valid. """ self._assign(namespace, identifier, obj) self.increment_revision() def remove(self, namespace, identifier): """Removes an identifier from this name scope. Args: namespace: A string specifying the namespace to which the identifier belongs. identifier: The identifier string. Raises: KeyError: If `identifier` does not exist in this scope. """ del self._namespaces[namespace][identifier] self.increment_revision() def rename(self, namespace, old_identifier, new_identifier): obj = self.get(namespace, old_identifier) self.add(namespace, new_identifier, obj) self.remove(namespace, old_identifier) def get(self, namespace, identifier): return self._namespaces[namespace][identifier] def has_identifier(self, namespace, identifier): return identifier in self._namespaces[namespace]
dm_control-main
dm_control/mjcf/namescope.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 Python object representation of Mujoco's MJCF schema. The root schema is provided as a module-level constant `schema.MUJOCO`. """ import collections import copy import os from dm_control.mjcf import attribute from lxml import etree from dm_control.utils import io as resources _SCHEMA_XML_PATH = os.path.join(os.path.dirname(__file__), 'schema.xml') _ARRAY_DTYPE_MAP = { 'int': int, 'float': float, 'string': str } _SCALAR_TYPE_MAP = { 'int': attribute.Integer, 'float': attribute.Float, 'string': attribute.String } ElementSpec = collections.namedtuple( 'ElementSpec', ('name', 'repeated', 'on_demand', 'identifier', 'namespace', 'attributes', 'children')) AttributeSpec = collections.namedtuple( 'AttributeSpec', ('name', 'type', 'required', 'conflict_allowed', 'conflict_behavior', 'other_kwargs')) # Additional namespaces that are not present in the MJCF schema but can # be used in `find` and `find_all`. _ADDITIONAL_FINDABLE_NAMESPACES = frozenset(['attachment_frame']) def _str2bool(string): """Converts either 'true' or 'false' (not case-sensitively) into a boolean.""" if string is None: return False else: string = string.lower() if string == 'true': return True elif string == 'false': return False else: raise ValueError( 'String should either be `true` or `false`: got {}'.format(string)) def parse_schema(schema_path): """Parses the schema XML. Args: schema_path: Path to the schema XML file. Returns: An `ElementSpec` for the root element in the schema. """ with resources.GetResourceAsFile(schema_path) as file_handle: schema_xml = etree.parse(file_handle).getroot() return _parse_element(schema_xml) def _parse_element(element_xml): """Parses an <element> element in the schema.""" name = element_xml.get('name') if not name: raise ValueError('Element must always have a name') repeated = _str2bool(element_xml.get('repeated')) on_demand = _str2bool(element_xml.get('on_demand')) attributes = collections.OrderedDict() attributes_xml = element_xml.find('attributes') if attributes_xml is not None: for attribute_xml in attributes_xml.findall('attribute'): attributes[attribute_xml.get('name')] = _parse_attribute(attribute_xml) identifier = None namespace = None for attribute_spec in attributes.values(): if attribute_spec.type == attribute.Identifier: identifier = attribute_spec.name namespace = element_xml.get('namespace') or name children = collections.OrderedDict() children_xml = element_xml.find('children') if children_xml is not None: for child_xml in children_xml.findall('element'): children[child_xml.get('name')] = _parse_element(child_xml) element_spec = ElementSpec( name, repeated, on_demand, identifier, namespace, attributes, children) recursive = _str2bool(element_xml.get('recursive')) if recursive: element_spec.children[name] = element_spec common_keys = set(element_spec.attributes).intersection(element_spec.children) if common_keys: raise RuntimeError( 'Element \'{}\' contains the following attributes and children with ' 'the same name: \'{}\'. This violates the design assumptions of ' 'this library. Please file a bug report. Thank you.' .format(name, sorted(common_keys))) return element_spec def _parse_attribute(attribute_xml): """Parses an <attribute> element in the schema.""" name = attribute_xml.get('name') required = _str2bool(attribute_xml.get('required')) conflict_allowed = _str2bool(attribute_xml.get('conflict_allowed')) conflict_behavior = attribute_xml.get('conflict_behavior', 'replace') attribute_type = attribute_xml.get('type') other_kwargs = {} if attribute_type == 'keyword': attribute_callable = attribute.Keyword other_kwargs['valid_values'] = attribute_xml.get('valid_values').split(' ') elif attribute_type == 'array': array_size_str = attribute_xml.get('array_size') attribute_callable = attribute.Array other_kwargs['length'] = int(array_size_str) if array_size_str else None other_kwargs['dtype'] = _ARRAY_DTYPE_MAP[attribute_xml.get('array_type')] elif attribute_type == 'identifier': attribute_callable = attribute.Identifier elif attribute_type == 'reference': attribute_callable = attribute.Reference other_kwargs['reference_namespace'] = ( attribute_xml.get('reference_namespace') or name) elif attribute_type == 'basepath': attribute_callable = attribute.BasePath other_kwargs['path_namespace'] = attribute_xml.get('path_namespace') elif attribute_type == 'file': attribute_callable = attribute.File other_kwargs['path_namespace'] = attribute_xml.get('path_namespace') else: try: attribute_callable = _SCALAR_TYPE_MAP[attribute_type] except KeyError: raise ValueError('Invalid attribute type: {}'.format(attribute_type)) return AttributeSpec( name=name, type=attribute_callable, required=required, conflict_allowed=conflict_allowed, conflict_behavior=conflict_behavior, other_kwargs=other_kwargs) def collect_namespaces(root_spec): """Constructs a set of namespaces in a given ElementSpec. Args: root_spec: An `ElementSpec` for the root element in the schema. Returns: A set of strings specifying the names of all the namespaces that are present in the spec. """ findable_namespaces = set() def update_namespaces_from_spec(spec): findable_namespaces.add(spec.namespace) for child_spec in spec.children.values(): if child_spec is not spec: update_namespaces_from_spec(child_spec) update_namespaces_from_spec(root_spec) return findable_namespaces MUJOCO = parse_schema(_SCHEMA_XML_PATH) FINDABLE_NAMESPACES = frozenset( collect_namespaces(MUJOCO).union(_ADDITIONAL_FINDABLE_NAMESPACES)) def _attachment_frame_spec(is_world_attachment): """Create specs for attachment frames. Attachment frames are specialized <body> without an identifier. The only allowed children are joints which also don't have identifiers. Args: is_world_attachment: Whether we are creating a spec for attachments to worldbody. If `True`, allow <freejoint> as child. Returns: An `ElementSpec`. """ frame_spec = ElementSpec( 'body', repeated=True, on_demand=False, identifier=None, namespace='body', attributes=collections.OrderedDict(), children=collections.OrderedDict()) body_spec = MUJOCO.children['worldbody'].children['body'] # 'name' and 'childclass' attributes are excluded. for attrib_name in ( 'mocap', 'pos', 'quat', 'axisangle', 'xyaxes', 'zaxis', 'euler'): frame_spec.attributes[attrib_name] = copy.deepcopy( body_spec.attributes[attrib_name]) inertial_spec = body_spec.children['inertial'] frame_spec.children['inertial'] = copy.deepcopy(inertial_spec) joint_spec = body_spec.children['joint'] frame_spec.children['joint'] = ElementSpec( 'joint', repeated=True, on_demand=False, identifier=None, namespace='joint', attributes=copy.deepcopy(joint_spec.attributes), children=collections.OrderedDict()) if is_world_attachment: freejoint_spec = (MUJOCO.children['worldbody'] .children['body'].children['freejoint']) frame_spec.children['freejoint'] = ElementSpec( 'freejoint', repeated=False, on_demand=True, identifier=None, namespace='joint', attributes=copy.deepcopy(freejoint_spec.attributes), children=collections.OrderedDict()) return frame_spec ATTACHMENT_FRAME = _attachment_frame_spec(is_world_attachment=False) WORLD_ATTACHMENT_FRAME = _attachment_frame_spec(is_world_attachment=True) def override_schema(schema_xml_path): """Override the schema with a custom xml. This method updates several global variables and care should be taken not to call it if the pre-update values have already been used. Args: schema_xml_path: Path to schema xml file. """ global MUJOCO global FINDABLE_NAMESPACES MUJOCO = parse_schema(schema_xml_path) FINDABLE_NAMESPACES = frozenset( collect_namespaces(MUJOCO).union(_ADDITIONAL_FINDABLE_NAMESPACES))
dm_control-main
dm_control/mjcf/schema.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. # ============================================================================ """Utilities for parsing and writing MuJoCo skin files. The file format is described at http://mujoco.org/book/XMLreference.html#skin. """ import collections import io import struct import numpy as np MAX_BODY_NAME_LENGTH = 40 Skin = collections.namedtuple( 'Skin', ('vertices', 'texcoords', 'faces', 'bones')) Bone = collections.namedtuple( 'Bone', ('body', 'bindpos', 'bindquat', 'vertex_ids', 'vertex_weights')) def parse(contents, body_getter): """Parses the contents of a MuJoCo skin file. Args: contents: a bytes-like object containing the contents of a skin file. body_getter: a callable that takes a string and returns the `mjcf.Element` instance of a MuJoCo body of the specified name. Returns: A `Skin` named tuple. """ f = io.BytesIO(contents) nvertex, ntexcoord, nface, nbone = struct.unpack('<iiii', f.read(4*4)) vertices = np.frombuffer(f.read(4*(3*nvertex)), dtype='<f4').reshape(-1, 3) texcoords = np.frombuffer(f.read(4*(2*ntexcoord)), dtype='<f4').reshape(-1, 2) faces = np.frombuffer(f.read(4*(3*nface)), dtype='<i4').reshape(-1, 3) bones = [] for _ in range(nbone): body_name = f.read(MAX_BODY_NAME_LENGTH).decode().split('\0')[0] body = lambda body_name=body_name: body_getter(body_name) bindpos = np.asarray(struct.unpack('<fff', f.read(4*3)), dtype=float) bindquat = np.asarray(struct.unpack('<ffff', f.read(4*4)), dtype=float) vertex_count = struct.unpack('<i', f.read(4))[0] vertex_ids = np.frombuffer(f.read(4*vertex_count), dtype='<i4') vertex_weights = np.frombuffer(f.read(4*vertex_count), dtype='<f4') bones.append(Bone(body=body, bindpos=bindpos, bindquat=bindquat, vertex_ids=vertex_ids, vertex_weights=vertex_weights)) return Skin(vertices=vertices, texcoords=texcoords, faces=faces, bones=bones) def serialize(skin): """Serializes a `Skin` named tuple into the contents of a MuJoCo skin file. Args: skin: a `Skin` named tuple. Returns: A `bytes` object representing the content of a MuJoCo skin file. """ out = io.BytesIO() nvertex = len(skin.vertices) ntexcoord = len(skin.texcoords) nface = len(skin.faces) nbone = len(skin.bones) out.write(struct.pack('<iiii', nvertex, ntexcoord, nface, nbone)) out.write(skin.vertices.astype('<f4').tobytes()) out.write(skin.texcoords.astype('<f4').tobytes()) out.write(skin.faces.astype('<i4').tobytes()) for bone in skin.bones: body_bytes = bone.body().full_identifier.encode('utf-8') if len(body_bytes) > MAX_BODY_NAME_LENGTH: raise ValueError( 'body name is longer than permitted by the skin file format ' '(maximum 40): {:r}'.format(body_bytes)) out.write(body_bytes) out.write(b'\0'*(MAX_BODY_NAME_LENGTH - len(body_bytes))) out.write(bone.bindpos.astype('<f4').tobytes()) out.write(bone.bindquat.astype('<f4').tobytes()) assert len(bone.vertex_ids) == len(bone.vertex_weights) out.write(struct.pack('<i', len(bone.vertex_ids))) out.write(bone.vertex_ids.astype('<i4').tobytes()) out.write(bone.vertex_weights.astype('<f4').tobytes()) return out.getvalue()
dm_control-main
dm_control/mjcf/skin.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. # ============================================================================ """A task where the goal is to move the hand close to a target prop or site.""" import collections from dm_control import composer from dm_control.composer import initializers from dm_control.composer.observation import observable from dm_control.composer.variation import distributions from dm_control.entities import props from dm_control.manipulation.shared import arenas from dm_control.manipulation.shared import cameras from dm_control.manipulation.shared import constants from dm_control.manipulation.shared import observations from dm_control.manipulation.shared import registry from dm_control.manipulation.shared import robots from dm_control.manipulation.shared import tags from dm_control.manipulation.shared import workspaces from dm_control.utils import rewards import numpy as np _ReachWorkspace = collections.namedtuple( '_ReachWorkspace', ['target_bbox', 'tcp_bbox', 'arm_offset']) # Ensures that the props are not touching the table before settling. _PROP_Z_OFFSET = 0.001 _DUPLO_WORKSPACE = _ReachWorkspace( target_bbox=workspaces.BoundingBox( lower=(-0.1, -0.1, _PROP_Z_OFFSET), upper=(0.1, 0.1, _PROP_Z_OFFSET)), tcp_bbox=workspaces.BoundingBox( lower=(-0.1, -0.1, 0.2), upper=(0.1, 0.1, 0.4)), arm_offset=robots.ARM_OFFSET) _SITE_WORKSPACE = _ReachWorkspace( target_bbox=workspaces.BoundingBox( lower=(-0.2, -0.2, 0.02), upper=(0.2, 0.2, 0.4)), tcp_bbox=workspaces.BoundingBox( lower=(-0.2, -0.2, 0.02), upper=(0.2, 0.2, 0.4)), arm_offset=robots.ARM_OFFSET) _TARGET_RADIUS = 0.05 class Reach(composer.Task): """Bring the hand close to a target prop or site.""" def __init__( self, arena, arm, hand, prop, obs_settings, workspace, control_timestep): """Initializes a new `Reach` task. Args: arena: `composer.Entity` instance. arm: `robot_base.RobotArm` instance. hand: `robot_base.RobotHand` instance. prop: `composer.Entity` instance specifying the prop to reach to, or None in which case the target is a fixed site whose position is specified by the workspace. obs_settings: `observations.ObservationSettings` instance. workspace: `_ReachWorkspace` specifying the placement of the prop and TCP. control_timestep: Float specifying the control timestep in seconds. """ self._arena = arena self._arm = arm self._hand = hand self._arm.attach(self._hand) self._arena.attach_offset(self._arm, offset=workspace.arm_offset) self.control_timestep = control_timestep self._tcp_initializer = initializers.ToolCenterPointInitializer( self._hand, self._arm, position=distributions.Uniform(*workspace.tcp_bbox), quaternion=workspaces.DOWN_QUATERNION) # Add custom camera observable. self._task_observables = cameras.add_camera_observables( arena, obs_settings, cameras.FRONT_CLOSE) target_pos_distribution = distributions.Uniform(*workspace.target_bbox) self._prop = prop if prop: # The prop itself is used to visualize the target location. self._make_target_site(parent_entity=prop, visible=False) self._target = self._arena.add_free_entity(prop) self._prop_placer = initializers.PropPlacer( props=[prop], position=target_pos_distribution, quaternion=workspaces.uniform_z_rotation, settle_physics=True) else: self._target = self._make_target_site(parent_entity=arena, visible=True) self._target_placer = target_pos_distribution obs = observable.MJCFFeature('pos', self._target) obs.configure(**obs_settings.prop_pose._asdict()) self._task_observables['target_position'] = obs # Add sites for visualizing the prop and target bounding boxes. workspaces.add_bbox_site( body=self.root_entity.mjcf_model.worldbody, lower=workspace.tcp_bbox.lower, upper=workspace.tcp_bbox.upper, rgba=constants.GREEN, name='tcp_spawn_area') workspaces.add_bbox_site( body=self.root_entity.mjcf_model.worldbody, lower=workspace.target_bbox.lower, upper=workspace.target_bbox.upper, rgba=constants.BLUE, name='target_spawn_area') def _make_target_site(self, parent_entity, visible): return workspaces.add_target_site( body=parent_entity.mjcf_model.worldbody, radius=_TARGET_RADIUS, visible=visible, rgba=constants.RED, name='target_site') @property def root_entity(self): return self._arena @property def arm(self): return self._arm @property def hand(self): return self._hand @property def task_observables(self): return self._task_observables def get_reward(self, physics): hand_pos = physics.bind(self._hand.tool_center_point).xpos target_pos = physics.bind(self._target).xpos distance = np.linalg.norm(hand_pos - target_pos) return rewards.tolerance( distance, bounds=(0, _TARGET_RADIUS), margin=_TARGET_RADIUS) def initialize_episode(self, physics, random_state): self._hand.set_grasp(physics, close_factors=random_state.uniform()) self._tcp_initializer(physics, random_state) if self._prop: self._prop_placer(physics, random_state) else: physics.bind(self._target).pos = ( self._target_placer(random_state=random_state)) def _reach(obs_settings, use_site): """Configure and instantiate a `Reach` task. Args: obs_settings: An `observations.ObservationSettings` instance. use_site: Boolean, if True then the target will be a fixed site, otherwise it will be a moveable Duplo brick. Returns: An instance of `reach.Reach`. """ arena = arenas.Standard() arm = robots.make_arm(obs_settings=obs_settings) hand = robots.make_hand(obs_settings=obs_settings) if use_site: workspace = _SITE_WORKSPACE prop = None else: workspace = _DUPLO_WORKSPACE prop = props.Duplo(observable_options=observations.make_options( obs_settings, observations.FREEPROP_OBSERVABLES)) task = Reach(arena=arena, arm=arm, hand=hand, prop=prop, obs_settings=obs_settings, workspace=workspace, control_timestep=constants.CONTROL_TIMESTEP) return task @registry.add(tags.FEATURES, tags.EASY) def reach_duplo_features(): return _reach(obs_settings=observations.PERFECT_FEATURES, use_site=False) @registry.add(tags.VISION, tags.EASY) def reach_duplo_vision(): return _reach(obs_settings=observations.VISION, use_site=False) @registry.add(tags.FEATURES, tags.EASY) def reach_site_features(): return _reach(obs_settings=observations.PERFECT_FEATURES, use_site=True) @registry.add(tags.VISION, tags.EASY) def reach_site_vision(): return _reach(obs_settings=observations.VISION, use_site=True)
dm_control-main
dm_control/manipulation/reach.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. # ============================================================================ """A task where the goal is to place a movable prop on top of a fixed prop.""" import collections from dm_control import composer from dm_control import mjcf from dm_control.composer import define from dm_control.composer import initializers from dm_control.composer.observation import observable from dm_control.composer.variation import distributions from dm_control.entities import props from dm_control.manipulation.shared import arenas from dm_control.manipulation.shared import cameras from dm_control.manipulation.shared import constants from dm_control.manipulation.shared import observations from dm_control.manipulation.shared import registry from dm_control.manipulation.shared import robots from dm_control.manipulation.shared import tags from dm_control.manipulation.shared import workspaces from dm_control.utils import rewards import numpy as np _PlaceWorkspace = collections.namedtuple( '_PlaceWorkspace', ['prop_bbox', 'target_bbox', 'tcp_bbox', 'arm_offset']) _TARGET_RADIUS = 0.05 _PEDESTAL_RADIUS = 0.07 # Ensures that the prop does not collide with the table during initialization. _PROP_Z_OFFSET = 1e-6 _WORKSPACE = _PlaceWorkspace( prop_bbox=workspaces.BoundingBox( lower=(-0.1, -0.1, _PROP_Z_OFFSET), upper=(0.1, 0.1, _PROP_Z_OFFSET)), tcp_bbox=workspaces.BoundingBox( lower=(-0.1, -0.1, _PEDESTAL_RADIUS + 0.1), upper=(0.1, 0.1, 0.4)), target_bbox=workspaces.BoundingBox( lower=(-0.1, -0.1, _PEDESTAL_RADIUS), upper=(0.1, 0.1, _PEDESTAL_RADIUS + 0.1)), arm_offset=robots.ARM_OFFSET) class SphereCradle(composer.Entity): """A concave shape for easy placement.""" _SPHERE_COUNT = 3 def _build(self): self._mjcf_root = mjcf.element.RootElement(model='cradle') sphere_radius = _PEDESTAL_RADIUS * 0.7 for ang in np.linspace(0, 2*np.pi, num=self._SPHERE_COUNT, endpoint=False): pos = 0.7 * sphere_radius * np.array([np.sin(ang), np.cos(ang), -1]) self._mjcf_root.worldbody.add( 'geom', type='sphere', size=[sphere_radius], condim=6, pos=pos) @property def mjcf_model(self): return self._mjcf_root class Pedestal(composer.Entity): """A narrow pillar to elevate the target.""" _HEIGHT = 0.2 def _build(self, cradle, target_radius): self._mjcf_root = mjcf.element.RootElement(model='pedestal') self._mjcf_root.worldbody.add( 'geom', type='capsule', size=[_PEDESTAL_RADIUS], fromto=[0, 0, -_PEDESTAL_RADIUS, 0, 0, -(self._HEIGHT + _PEDESTAL_RADIUS)]) attachment_site = self._mjcf_root.worldbody.add( 'site', type='sphere', size=(0.003,), group=constants.TASK_SITE_GROUP) self.attach(cradle, attachment_site) self._target_site = workspaces.add_target_site( body=self.mjcf_model.worldbody, radius=target_radius, rgba=constants.RED) @property def mjcf_model(self): return self._mjcf_root @property def target_site(self): return self._target_site def _build_observables(self): return PedestalObservables(self) class PedestalObservables(composer.Observables): """Observables for the `Pedestal` prop.""" @define.observable def position(self): return observable.MJCFFeature('xpos', self._entity.target_site) class Place(composer.Task): """Place the prop on top of another fixed prop held up by a pedestal.""" def __init__(self, arena, arm, hand, prop, obs_settings, workspace, control_timestep, cradle): """Initializes a new `Place` task. Args: arena: `composer.Entity` instance. arm: `robot_base.RobotArm` instance. hand: `robot_base.RobotHand` instance. prop: `composer.Entity` instance. obs_settings: `observations.ObservationSettings` instance. workspace: A `_PlaceWorkspace` instance. control_timestep: Float specifying the control timestep in seconds. cradle: `composer.Entity` onto which the `prop` must be placed. """ self._arena = arena self._arm = arm self._hand = hand self._arm.attach(self._hand) self._arena.attach_offset(self._arm, offset=workspace.arm_offset) self.control_timestep = control_timestep # Add custom camera observable. self._task_observables = cameras.add_camera_observables( arena, obs_settings, cameras.FRONT_CLOSE) self._tcp_initializer = initializers.ToolCenterPointInitializer( self._hand, self._arm, position=distributions.Uniform(*workspace.tcp_bbox), quaternion=workspaces.DOWN_QUATERNION) self._prop = prop self._prop_frame = self._arena.add_free_entity(prop) self._pedestal = Pedestal(cradle=cradle, target_radius=_TARGET_RADIUS) self._arena.attach(self._pedestal) for obs in self._pedestal.observables.as_dict().values(): obs.configure(**obs_settings.prop_pose._asdict()) self._prop_placer = initializers.PropPlacer( props=[prop], position=distributions.Uniform(*workspace.prop_bbox), quaternion=workspaces.uniform_z_rotation, settle_physics=True, max_attempts_per_prop=50) self._pedestal_placer = initializers.PropPlacer( props=[self._pedestal], position=distributions.Uniform(*workspace.target_bbox), settle_physics=False) # Add sites for visual debugging. workspaces.add_bbox_site( body=self.root_entity.mjcf_model.worldbody, lower=workspace.tcp_bbox.lower, upper=workspace.tcp_bbox.upper, rgba=constants.GREEN, name='tcp_spawn_area') workspaces.add_bbox_site( body=self.root_entity.mjcf_model.worldbody, lower=workspace.prop_bbox.lower, upper=workspace.prop_bbox.upper, rgba=constants.BLUE, name='prop_spawn_area') workspaces.add_bbox_site( body=self.root_entity.mjcf_model.worldbody, lower=workspace.target_bbox.lower, upper=workspace.target_bbox.upper, rgba=constants.CYAN, name='pedestal_spawn_area') @property def root_entity(self): return self._arena @property def arm(self): return self._arm @property def hand(self): return self._hand @property def task_observables(self): return self._task_observables def initialize_episode(self, physics, random_state): self._pedestal_placer(physics, random_state, ignore_contacts_with_entities=[self._prop]) self._hand.set_grasp(physics, close_factors=random_state.uniform()) self._tcp_initializer(physics, random_state) self._prop_placer(physics, random_state) def get_reward(self, physics): target = physics.bind(self._pedestal.target_site).xpos obj = physics.bind(self._prop_frame).xpos tcp = physics.bind(self._hand.tool_center_point).xpos tcp_to_obj = np.linalg.norm(obj - tcp) grasp = rewards.tolerance(tcp_to_obj, bounds=(0, _TARGET_RADIUS), margin=_TARGET_RADIUS, sigmoid='long_tail') obj_to_target = np.linalg.norm(obj - target) in_place = rewards.tolerance(obj_to_target, bounds=(0, _TARGET_RADIUS), margin=_TARGET_RADIUS, sigmoid='long_tail') tcp_to_target = np.linalg.norm(tcp - target) hand_away = rewards.tolerance(tcp_to_target, bounds=(4*_TARGET_RADIUS, np.inf), margin=3*_TARGET_RADIUS, sigmoid='long_tail') in_place_weight = 10. grasp_or_hand_away = grasp * (1 - in_place) + hand_away * in_place return ( grasp_or_hand_away + in_place_weight * in_place) / (1 + in_place_weight) def _place(obs_settings, cradle_prop_name): """Configure and instantiate a Place task. Args: obs_settings: `observations.ObservationSettings` instance. cradle_prop_name: The name of the prop onto which the Duplo brick must be placed. Must be either 'duplo' or 'cradle'. Returns: An instance of `Place`. Raises: ValueError: If `prop_name` is neither 'duplo' nor 'cradle'. """ arena = arenas.Standard() arm = robots.make_arm(obs_settings=obs_settings) hand = robots.make_hand(obs_settings=obs_settings) prop = props.Duplo( observable_options=observations.make_options( obs_settings, observations.FREEPROP_OBSERVABLES)) if cradle_prop_name == 'duplo': cradle = props.Duplo() elif cradle_prop_name == 'cradle': cradle = SphereCradle() else: raise ValueError( '`cradle_prop_name` must be either \'duplo\' or \'cradle\'.') task = Place(arena=arena, arm=arm, hand=hand, prop=prop, obs_settings=obs_settings, workspace=_WORKSPACE, control_timestep=constants.CONTROL_TIMESTEP, cradle=cradle) return task @registry.add(tags.FEATURES) def place_brick_features(): return _place(obs_settings=observations.PERFECT_FEATURES, cradle_prop_name='duplo') @registry.add(tags.VISION) def place_brick_vision(): return _place(obs_settings=observations.VISION, cradle_prop_name='duplo') @registry.add(tags.FEATURES) def place_cradle_features(): return _place(obs_settings=observations.PERFECT_FEATURES, cradle_prop_name='cradle') @registry.add(tags.VISION) def place_cradle_vision(): return _place(obs_settings=observations.VISION, cradle_prop_name='cradle')
dm_control-main
dm_control/manipulation/place.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. # ============================================================================ """Tasks where the goal is to elevate a prop.""" import collections import itertools from dm_control import composer from dm_control.composer import initializers from dm_control.composer.variation import distributions from dm_control.entities import props from dm_control.manipulation.shared import arenas from dm_control.manipulation.shared import cameras from dm_control.manipulation.shared import constants from dm_control.manipulation.shared import observations from dm_control.manipulation.shared import registry from dm_control.manipulation.shared import robots from dm_control.manipulation.shared import tags from dm_control.manipulation.shared import workspaces from dm_control.utils import rewards import numpy as np _LiftWorkspace = collections.namedtuple( '_LiftWorkspace', ['prop_bbox', 'tcp_bbox', 'arm_offset']) _DUPLO_WORKSPACE = _LiftWorkspace( prop_bbox=workspaces.BoundingBox( lower=(-0.1, -0.1, 0.0), upper=(0.1, 0.1, 0.0)), tcp_bbox=workspaces.BoundingBox( lower=(-0.1, -0.1, 0.2), upper=(0.1, 0.1, 0.4)), arm_offset=robots.ARM_OFFSET) _BOX_SIZE = 0.09 _BOX_MASS = 1.3 _BOX_WORKSPACE = _LiftWorkspace( prop_bbox=workspaces.BoundingBox( lower=(-0.1, -0.1, _BOX_SIZE), upper=(0.1, 0.1, _BOX_SIZE)), tcp_bbox=workspaces.BoundingBox( lower=(-0.1, -0.1, 0.2), upper=(0.1, 0.1, 0.4)), arm_offset=robots.ARM_OFFSET) _DISTANCE_TO_LIFT = 0.3 class _VertexSitesMixin: """Mixin class that adds sites corresponding to the vertices of a box.""" def _add_vertex_sites(self, box_geom_or_site): """Add sites corresponding to the vertices of a box geom or site.""" offsets = ( (-half_length, half_length) for half_length in box_geom_or_site.size) site_positions = np.vstack(list(itertools.product(*offsets))) if box_geom_or_site.pos is not None: site_positions += box_geom_or_site.pos self._vertices = [] for i, pos in enumerate(site_positions): site = box_geom_or_site.parent.add( 'site', name='vertex_' + str(i), pos=pos, type='sphere', size=[0.002], rgba=constants.RED, group=constants.TASK_SITE_GROUP) self._vertices.append(site) @property def vertices(self): return self._vertices class _BoxWithVertexSites(props.Primitive, _VertexSitesMixin): """Subclass of `Box` with sites marking the vertices of the box geom.""" def _build(self, *args, **kwargs): super()._build(*args, geom_type='box', **kwargs) self._add_vertex_sites(self.geom) class _DuploWithVertexSites(props.Duplo, _VertexSitesMixin): """Subclass of `Duplo` with sites marking the vertices of its sensor site.""" def _build(self, *args, **kwargs): super()._build(*args, **kwargs) self._add_vertex_sites(self.mjcf_model.find('site', 'bounding_box')) class Lift(composer.Task): """A task where the goal is to elevate a prop.""" def __init__( self, arena, arm, hand, prop, obs_settings, workspace, control_timestep): """Initializes a new `Lift` task. Args: arena: `composer.Entity` instance. arm: `robot_base.RobotArm` instance. hand: `robot_base.RobotHand` instance. prop: `composer.Entity` instance. obs_settings: `observations.ObservationSettings` instance. workspace: `_LiftWorkspace` specifying the placement of the prop and TCP. control_timestep: Float specifying the control timestep in seconds. """ self._arena = arena self._arm = arm self._hand = hand self._arm.attach(self._hand) self._arena.attach_offset(self._arm, offset=workspace.arm_offset) self.control_timestep = control_timestep # Add custom camera observable. self._task_observables = cameras.add_camera_observables( arena, obs_settings, cameras.FRONT_CLOSE) self._tcp_initializer = initializers.ToolCenterPointInitializer( self._hand, self._arm, position=distributions.Uniform(*workspace.tcp_bbox), quaternion=workspaces.DOWN_QUATERNION) self._prop = prop self._arena.add_free_entity(prop) self._prop_placer = initializers.PropPlacer( props=[prop], position=distributions.Uniform(*workspace.prop_bbox), quaternion=workspaces.uniform_z_rotation, ignore_collisions=True, settle_physics=True) # Add sites for visualizing bounding boxes and target height. self._target_height_site = workspaces.add_bbox_site( body=self.root_entity.mjcf_model.worldbody, lower=(-1, -1, 0), upper=(1, 1, 0), rgba=constants.RED, name='target_height') workspaces.add_bbox_site( body=self.root_entity.mjcf_model.worldbody, lower=workspace.tcp_bbox.lower, upper=workspace.tcp_bbox.upper, rgba=constants.GREEN, name='tcp_spawn_area') workspaces.add_bbox_site( body=self.root_entity.mjcf_model.worldbody, lower=workspace.prop_bbox.lower, upper=workspace.prop_bbox.upper, rgba=constants.BLUE, name='prop_spawn_area') @property def root_entity(self): return self._arena @property def arm(self): return self._arm @property def hand(self): return self._hand @property def task_observables(self): return self._task_observables def _get_height_of_lowest_vertex(self, physics): return min(physics.bind(self._prop.vertices).xpos[:, 2]) def get_reward(self, physics): prop_height = self._get_height_of_lowest_vertex(physics) return rewards.tolerance(prop_height, bounds=(self._target_height, np.inf), margin=_DISTANCE_TO_LIFT, value_at_margin=0, sigmoid='linear') def initialize_episode(self, physics, random_state): self._hand.set_grasp(physics, close_factors=random_state.uniform()) self._prop_placer(physics, random_state) self._tcp_initializer(physics, random_state) # Compute the target height based on the initial height of the prop's # center of mass after settling. initial_prop_height = self._get_height_of_lowest_vertex(physics) self._target_height = _DISTANCE_TO_LIFT + initial_prop_height physics.bind(self._target_height_site).pos[2] = self._target_height def _lift(obs_settings, prop_name): """Configure and instantiate a Lift task. Args: obs_settings: `observations.ObservationSettings` instance. prop_name: The name of the prop to be lifted. Must be either 'duplo' or 'box'. Returns: An instance of `lift.Lift`. Raises: ValueError: If `prop_name` is neither 'duplo' nor 'box'. """ arena = arenas.Standard() arm = robots.make_arm(obs_settings=obs_settings) hand = robots.make_hand(obs_settings=obs_settings) if prop_name == 'duplo': workspace = _DUPLO_WORKSPACE prop = _DuploWithVertexSites( observable_options=observations.make_options( obs_settings, observations.FREEPROP_OBSERVABLES)) elif prop_name == 'box': workspace = _BOX_WORKSPACE # NB: The box is intentionally too large to pick up with a pinch grip. prop = _BoxWithVertexSites( size=[_BOX_SIZE] * 3, observable_options=observations.make_options( obs_settings, observations.FREEPROP_OBSERVABLES)) prop.geom.mass = _BOX_MASS else: raise ValueError('`prop_name` must be either \'duplo\' or \'box\'.') task = Lift(arena=arena, arm=arm, hand=hand, prop=prop, workspace=workspace, obs_settings=obs_settings, control_timestep=constants.CONTROL_TIMESTEP) return task @registry.add(tags.FEATURES) def lift_brick_features(): return _lift(obs_settings=observations.PERFECT_FEATURES, prop_name='duplo') @registry.add(tags.VISION) def lift_brick_vision(): return _lift(obs_settings=observations.VISION, prop_name='duplo') @registry.add(tags.FEATURES) def lift_large_box_features(): return _lift(obs_settings=observations.PERFECT_FEATURES, prop_name='box') @registry.add(tags.VISION) def lift_large_box_vision(): return _lift(obs_settings=observations.VISION, prop_name='box')
dm_control-main
dm_control/manipulation/lift.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 `dm_control.manipulation_suite`.""" from absl import flags from absl.testing import absltest from absl.testing import parameterized from dm_control import manipulation import numpy as np flags.DEFINE_boolean( 'fix_seed', True, 'Whether to fix the seed for the environment\'s random number generator. ' 'This the default since it prevents non-deterministic failures, but it may ' 'be useful to allow the seed to vary in some cases, for example when ' 'repeating a test many times in order to detect rare failure events.') FLAGS = flags.FLAGS _FIX_SEED = None _NUM_EPISODES = 5 _NUM_STEPS_PER_EPISODE = 10 def _get_fix_seed(): global _FIX_SEED if _FIX_SEED is None: if FLAGS.is_parsed(): _FIX_SEED = FLAGS.fix_seed else: _FIX_SEED = FLAGS['fix_seed'].default return _FIX_SEED class ManipulationTest(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.parameters(*manipulation.ALL) def test_task_runs(self, task_name): """Tests that the environment runs and is coherent with its specs.""" seed = 99 if _get_fix_seed() else None env = manipulation.load(task_name, seed=seed) random_state = np.random.RandomState(seed) 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/manipulation/manipulation_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. # ============================================================================ """A structured set of manipulation tasks with a single entry point.""" from absl import flags from dm_control import composer as _composer from dm_control.manipulation import bricks as _bricks from dm_control.manipulation import lift as _lift from dm_control.manipulation import place as _place from dm_control.manipulation import reach as _reach from dm_control.manipulation.shared import registry as _registry _registry.done_importing_tasks() _TIME_LIMIT = 10. _TIMEOUT = None ALL = tuple(_registry.get_all_names()) TAGS = tuple(_registry.get_tags()) flags.DEFINE_bool('timeout', True, 'Whether episodes should have a time limit.') FLAGS = flags.FLAGS def _get_timeout(): global _TIMEOUT if _TIMEOUT is None: if FLAGS.is_parsed(): _TIMEOUT = FLAGS.timeout else: _TIMEOUT = FLAGS['timeout'].default return _TIMEOUT def get_environments_by_tag(tag): """Returns the names of all environments matching a given tag. Args: tag: A string from `TAGS`. Returns: A tuple of environment names. """ return tuple(_registry.get_names_by_tag(tag)) def load(environment_name, seed=None): """Loads a manipulation environment. Args: environment_name: String, the name of the environment to load. Must be in `ALL`. seed: An optional integer used to seed the task's random number generator. If None (default), the random number generator will self-seed from a platform-dependent source of entropy. Returns: An instance of `composer.Environment`. """ task = _registry.get_constructor(environment_name)() time_limit = _TIME_LIMIT if _get_timeout() else float('inf') return _composer.Environment(task, time_limit=time_limit, random_state=seed)
dm_control-main
dm_control/manipulation/__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. # ============================================================================ """Tasks involving assembly and/or disassembly of bricks.""" import collections from absl import logging from dm_control import composer from dm_control.composer import initializers from dm_control.composer import variation from dm_control.composer.observation import observable from dm_control.composer.variation import distributions from dm_control.entities import props from dm_control.manipulation.shared import arenas from dm_control.manipulation.shared import cameras from dm_control.manipulation.shared import constants from dm_control.manipulation.shared import observations from dm_control.manipulation.shared import registry from dm_control.manipulation.shared import robots from dm_control.manipulation.shared import tags from dm_control.manipulation.shared import workspaces from dm_control.mujoco.wrapper import mjbindings from dm_control.utils import rewards import numpy as np mjlib = mjbindings.mjlib _BrickWorkspace = collections.namedtuple( '_BrickWorkspace', ['prop_bbox', 'tcp_bbox', 'goal_hint_pos', 'goal_hint_quat', 'arm_offset']) # Ensures that the prop does not collide with the table during initialization. _PROP_Z_OFFSET = 1e-6 _WORKSPACE = _BrickWorkspace( prop_bbox=workspaces.BoundingBox( lower=(-0.1, -0.1, _PROP_Z_OFFSET), upper=(0.1, 0.1, _PROP_Z_OFFSET)), tcp_bbox=workspaces.BoundingBox( lower=(-0.1, -0.1, 0.15), upper=(0.1, 0.1, 0.4)), goal_hint_pos=(0.2, 0.1, 0.), goal_hint_quat=(-0.38268343, 0., 0., 0.92387953), arm_offset=robots.ARM_OFFSET) # Alpha value of the visual goal hint representing the goal state for each task. _HINT_ALPHA = 0.75 # Distance thresholds for the shaping rewards for getting the top brick close # to the bottom brick, and for 'clicking' them together. _CLOSE_THRESHOLD = 0.01 _CLICK_THRESHOLD = 0.001 # Sequence of colors for the brick(s). _COLOR_VALUES, _COLOR_NAMES = list( zip( ((1., 0., 0.), 'red'), ((0., 1., 0.), 'green'), ((0., 0., 1.), 'blue'), ((0., 1., 1.), 'cyan'), ((1., 0., 1.), 'magenta'), ((1., 1., 0.), 'yellow'), )) class _Common(composer.Task): """Common components of brick tasks.""" def __init__(self, arena, arm, hand, num_bricks, obs_settings, workspace, control_timestep): if not 2 <= num_bricks <= 6: raise ValueError('`num_bricks` must be between 2 and 6, got {}.' .format(num_bricks)) if num_bricks > 3: # The default values computed by MuJoCo's compiler are too small if there # are more than three stacked bricks, since each stacked pair generates # a large number of contacts. The values below are sufficient for up to # 6 stacked bricks. # TODO(b/78331644): It may be useful to log the size of `physics.model` # and `physics.data` after compilation to gauge the # impact of these changes on MuJoCo's memory footprint. arena.mjcf_model.size.nconmax = 400 arena.mjcf_model.size.njmax = 1200 self._arena = arena self._arm = arm self._hand = hand self._arm.attach(self._hand) self._arena.attach_offset(self._arm, offset=workspace.arm_offset) self.control_timestep = control_timestep # Add custom camera observable. self._task_observables = cameras.add_camera_observables( arena, obs_settings, cameras.FRONT_CLOSE) color_sequence = iter(_COLOR_VALUES) brick_obs_options = observations.make_options( obs_settings, observations.FREEPROP_OBSERVABLES) bricks = [] brick_frames = [] goal_hint_bricks = [] for _ in range(num_bricks): color = next(color_sequence) brick = props.Duplo(color=color, observable_options=brick_obs_options) brick_frames.append(arena.add_free_entity(brick)) bricks.append(brick) # Translucent, contactless brick with no observables. These are used to # provide a visual hint representing the goal state for each task. hint_brick = props.Duplo(color=color) _hintify(hint_brick, alpha=_HINT_ALPHA) arena.attach(hint_brick) goal_hint_bricks.append(hint_brick) self._bricks = bricks self._brick_frames = brick_frames self._goal_hint_bricks = goal_hint_bricks # Position and quaternion for the goal hint. self._goal_hint_pos = workspace.goal_hint_pos self._goal_hint_quat = workspace.goal_hint_quat self._tcp_initializer = initializers.ToolCenterPointInitializer( self._hand, self._arm, position=distributions.Uniform(*workspace.tcp_bbox), quaternion=workspaces.DOWN_QUATERNION) # Add sites for visual debugging. workspaces.add_bbox_site( body=self.root_entity.mjcf_model.worldbody, lower=workspace.tcp_bbox.lower, upper=workspace.tcp_bbox.upper, rgba=constants.GREEN, name='tcp_spawn_area') workspaces.add_bbox_site( body=self.root_entity.mjcf_model.worldbody, lower=workspace.prop_bbox.lower, upper=workspace.prop_bbox.upper, rgba=constants.BLUE, name='prop_spawn_area') @property def task_observables(self): return self._task_observables @property def root_entity(self): return self._arena @property def arm(self): return self._arm @property def hand(self): return self._hand class Stack(_Common): """Build a stack of Duplo bricks.""" def __init__(self, arena, arm, hand, num_bricks, target_height, moveable_base, randomize_order, obs_settings, workspace, control_timestep): """Initializes a new `Stack` task. Args: arena: `composer.Entity` instance. arm: `robot_base.RobotArm` instance. hand: `robot_base.RobotHand` instance. num_bricks: The total number of bricks; must be between 2 and 6. target_height: The target number of bricks in the stack in order to get maximum reward. Must be between 2 and `num_bricks`. moveable_base: Boolean specifying whether or not the bottom brick should be moveable. randomize_order: Boolean specifying whether to randomize the desired order of bricks in the stack at the start of each episode. obs_settings: `observations.ObservationSettings` instance. workspace: A `_BrickWorkspace` instance. control_timestep: Float specifying the control timestep in seconds. Raises: ValueError: If `num_bricks` is not between 2 and 6, or if `target_height` is not between 2 and `num_bricks - 1`. """ if not 2 <= target_height <= num_bricks: raise ValueError('`target_height` must be between 2 and {}, got {}.' .format(num_bricks, target_height)) super().__init__( arena=arena, arm=arm, hand=hand, num_bricks=num_bricks, obs_settings=obs_settings, workspace=workspace, control_timestep=control_timestep) self._moveable_base = moveable_base self._randomize_order = randomize_order self._target_height = target_height self._prop_bbox = workspace.prop_bbox # Shuffled at the start of each episode if `randomize_order` is True. self._desired_order = np.arange(target_height) # In the random order case, create a `prop_pose` observable that informs the # agent of the desired order. if randomize_order: desired_order_observable = observable.Generic(self._get_desired_order) desired_order_observable.configure(**obs_settings.prop_pose._asdict()) self._task_observables['desired_order'] = desired_order_observable def _get_desired_order(self, physics): del physics # Unused return self._desired_order.astype(np.double) def initialize_episode_mjcf(self, random_state): if self._randomize_order: self._desired_order = random_state.choice( len(self._bricks), size=self._target_height, replace=False) logging.info('Desired stack order (from bottom to top): [%s]', ' '.join(_COLOR_NAMES[i] for i in self._desired_order)) # If the base of the stack should be fixed, remove the freejoint for the # first brick (and ensure that all the others have freejoints). fixed_indices = [] if self._moveable_base else [self._desired_order[0]] _add_or_remove_freejoints(attachment_frames=self._brick_frames, fixed_indices=fixed_indices) # We need to define the prop initializer for the bricks here rather than in # the `__init__`, since `PropPlacer` looks for freejoints on instantiation. self._brick_placer = initializers.PropPlacer( props=self._bricks, position=distributions.Uniform(*self._prop_bbox), quaternion=workspaces.uniform_z_rotation, settle_physics=True) def initialize_episode(self, physics, random_state): self._brick_placer(physics, random_state) self._hand.set_grasp(physics, close_factors=random_state.uniform()) self._tcp_initializer(physics, random_state) # Arrange the goal hint bricks in the desired stack order. _build_stack(physics, bricks=self._goal_hint_bricks, base_pos=self._goal_hint_pos, base_quat=self._goal_hint_quat, order=self._desired_order, random_state=random_state) def get_reward(self, physics): pairs = list(zip(self._desired_order[:-1], self._desired_order[1:])) pairwise_rewards = _get_pairwise_stacking_rewards( physics=physics, bricks=self._bricks, pairs=pairs) # The final reward is an average over the pairwise rewards. return np.mean(pairwise_rewards) class Reassemble(_Common): """Disassemble a stack of Duplo bricks and reassemble it in another order.""" def __init__(self, arena, arm, hand, num_bricks, randomize_initial_order, randomize_desired_order, obs_settings, workspace, control_timestep): """Initializes a new `Reassemble` task. Args: arena: `composer.Entity` instance. arm: `robot_base.RobotArm` instance. hand: `robot_base.RobotHand` instance. num_bricks: The total number of bricks; must be between 2 and 6. randomize_initial_order: Boolean specifying whether to randomize the initial order of bricks in the stack at the start of each episode. randomize_desired_order: Boolean specifying whether to independently randomize the desired order of bricks in the stack at the start of each episode. By default the desired order will be the reverse of the initial order, with the exception of the base brick which is always the same as in the initial order since it is welded in place. obs_settings: `observations.ObservationSettings` instance. workspace: A `_BrickWorkspace` instance. control_timestep: Float specifying the control timestep in seconds. Raises: ValueError: If `num_bricks` is not between 2 and 6. """ super().__init__( arena=arena, arm=arm, hand=hand, num_bricks=num_bricks, obs_settings=obs_settings, workspace=workspace, control_timestep=control_timestep) self._randomize_initial_order = randomize_initial_order self._randomize_desired_order = randomize_desired_order # Randomized at the start of each episode if `randomize_initial_order` is # True. self._initial_order = np.arange(num_bricks) # Randomized at the start of each episode if `randomize_desired_order` is # True. self._desired_order = self._initial_order.copy() self._desired_order[1:] = self._desired_order[-1:0:-1] # In the random order case, create a `prop_pose` observable that informs the # agent of the desired order. if randomize_desired_order: desired_order_observable = observable.Generic(self._get_desired_order) desired_order_observable.configure(**obs_settings.prop_pose._asdict()) self._task_observables['desired_order'] = desired_order_observable # Distributions of positions and orientations for the base of the stack. self._base_pos = distributions.Uniform(*workspace.prop_bbox) self._base_quat = workspaces.uniform_z_rotation def _get_desired_order(self, physics): del physics # Unused return self._desired_order.astype(np.double) def initialize_episode_mjcf(self, random_state): if self._randomize_initial_order: random_state.shuffle(self._initial_order) # The bottom brick will be fixed to the table, so it must be the same in # both the initial and desired order. self._desired_order[0] = self._initial_order[0] # By default the desired order of the other bricks is the opposite of their # initial order. self._desired_order[1:] = self._initial_order[-1:0:-1] if self._randomize_desired_order: random_state.shuffle(self._desired_order[1:]) logging.info('Desired stack order (from bottom to top): [%s]', ' '.join(_COLOR_NAMES[i] for i in self._desired_order)) # Remove the freejoint from the bottom brick in the stack. _add_or_remove_freejoints(attachment_frames=self._brick_frames, fixed_indices=[self._initial_order[0]]) def initialize_episode(self, physics, random_state): # Build the initial stack. _build_stack(physics, bricks=self._bricks, base_pos=self._base_pos, base_quat=self._base_quat, order=self._initial_order, random_state=random_state) # Arrange the goal hint bricks into a stack with the desired order. _build_stack(physics, bricks=self._goal_hint_bricks, base_pos=self._goal_hint_pos, base_quat=self._goal_hint_quat, order=self._desired_order, random_state=random_state) self._hand.set_grasp(physics, close_factors=random_state.uniform()) self._tcp_initializer(physics, random_state) def get_reward(self, physics): pairs = list(zip(self._desired_order[:-1], self._desired_order[1:])) # We set `close_coef=0.` because the coarse shaping reward causes problems # for this task (it means there is a strong disincentive to break up the # initial stack). pairwise_rewards = _get_pairwise_stacking_rewards( physics=physics, bricks=self._bricks, pairs=pairs, close_coef=0.) # The final reward is an average over the pairwise rewards. return np.mean(pairwise_rewards) def _distance(pos1, pos2): diff = pos1 - pos2 return sum(np.sqrt((diff * diff).sum(1))) def _min_stud_to_hole_distance(physics, bottom_brick, top_brick): # Positions of the top left and bottom right studs on the `bottom_brick` and # the top left and bottom right holes on the `top_brick`. stud_pos = physics.bind(bottom_brick.studs[[0, -1], [0, -1]]).xpos hole_pos = physics.bind(top_brick.holes[[0, -1], [0, -1]]).xpos # Bricks are rotationally symmetric, so we compute top left -> top left and # top left -> bottom right distances and return whichever of these is smaller. dist1 = _distance(stud_pos, hole_pos) dist2 = _distance(stud_pos[::-1], hole_pos) return min(dist1, dist2) def _get_pairwise_stacking_rewards(physics, bricks, pairs, close_coef=0.1): """Returns a vector of shaping reward components based on pairwise distances. Args: physics: An `mjcf.Physics` instance. bricks: A list of `composer.Entity` instances corresponding to bricks. pairs: A list of `(bottom_idx, top_idx)` tuples specifying which pairs of bricks should be measured. close_coef: Float specfying the relative weight given to the coarse- tolerance shaping component for getting the bricks close to one another (as opposed to the fine-tolerance component for clicking them together). Returns: A numpy array of size `len(pairs)` containing values in (0, 1], where 1 corresponds to a stacked pair of bricks. """ distances = [] for bottom_idx, top_idx in pairs: bottom_brick = bricks[bottom_idx] top_brick = bricks[top_idx] distances.append( _min_stud_to_hole_distance(physics, bottom_brick, top_brick)) distances = np.hstack(distances) # Coarse-tolerance component for bringing the holes close to the studs. close = rewards.tolerance( distances, bounds=(0, _CLOSE_THRESHOLD), margin=(_CLOSE_THRESHOLD * 10)) # Fine-tolerance component for clicking the bricks together. clicked = rewards.tolerance( distances, bounds=(0, _CLICK_THRESHOLD), margin=_CLICK_THRESHOLD) # Weighted average of coarse and fine components for each pair of bricks. return np.average([close, clicked], weights=[close_coef, 1.], axis=0) def _build_stack(physics, bricks, base_pos, base_quat, order, random_state): """Builds a stack of bricks. Args: physics: Instance of `mjcf.Physics`. bricks: Sequence of `composer.Entity` instances corresponding to bricks. base_pos: Position of the base brick in the stack; either a (3,) numpy array or a `variation.Variation` that yields such arrays. base_quat: Quaternion of the base brick in the stack; either a (4,) numpy array or a `variation.Variation` that yields such arrays. order: Sequence of indices specifying the order in which to stack the bricks. random_state: An `np.random.RandomState` instance. """ base_pos = variation.evaluate(base_pos, random_state=random_state) base_quat = variation.evaluate(base_quat, random_state=random_state) bricks[order[0]].set_pose(physics, position=base_pos, quaternion=base_quat) for bottom_idx, top_idx in zip(order[:-1], order[1:]): bottom = bricks[bottom_idx] top = bricks[top_idx] stud_pos = physics.bind(bottom.studs[0, 0]).xpos _, quat = bottom.get_pose(physics) # The reward function treats top left -> top left and top left -> bottom # right configurations as identical, so the orientations of the bricks are # randomized so that 50% of the time the top brick is rotated 180 degrees # relative to the brick below. if random_state.rand() < 0.5: quat = quat.copy() axis = np.array([0., 0., 1.]) angle = np.pi mjlib.mju_quatIntegrate(quat, axis, angle) hole_idx = (-1, -1) else: hole_idx = (0, 0) top.set_pose(physics, quaternion=quat) # Set the position of the top brick so that its holes line up with the studs # of the brick below. offset = physics.bind(top.holes[hole_idx]).xpos top_pos = stud_pos - offset top.set_pose(physics, position=top_pos) def _add_or_remove_freejoints(attachment_frames, fixed_indices): """Adds or removes freejoints from props. Args: attachment_frames: A list of `mjcf.Elements` corresponding to attachment frames. fixed_indices: A list of indices of attachment frames that should be fixed to the world (i.e. have their freejoints removed). Freejoints will be added to all other elements in `attachment_frames` if they do not already possess them. """ for i, frame in enumerate(attachment_frames): if i in fixed_indices: if frame.freejoint: frame.freejoint.remove() elif not frame.freejoint: frame.add('freejoint') def _replace_alpha(rgba, alpha=0.3): new_rgba = rgba.copy() new_rgba[3] = alpha return new_rgba def _hintify(entity, alpha=None): """Modifies an entity for use as a 'visual hint'. Contacts will be disabled for all geoms within the entity, and its bodies will be converted to "mocap" bodies (which are viewed as fixed from the perspective of the dynamics). The geom alpha values may also be overridden to render the geoms as translucent. Args: entity: A `composer.Entity`, modified in place. alpha: Optional float between 0 and 1, used to override the alpha values for all of the geoms in this entity. """ for subentity in entity.iter_entities(): # TODO(b/112084359): This assumes that all geoms either define explicit RGBA # values, or inherit from the top-level default. It will # not correctly handle more complicated hierarchies of # default classes. if (alpha is not None and subentity.mjcf_model.default.geom is not None and subentity.mjcf_model.default.geom.rgba is not None): subentity.mjcf_model.default.geom.rgba = _replace_alpha( subentity.mjcf_model.default.geom.rgba, alpha=alpha) for body in subentity.mjcf_model.find_all('body'): body.mocap = 'true' for geom in subentity.mjcf_model.find_all('geom'): if alpha is not None and geom.rgba is not None: geom.rgba = _replace_alpha(geom.rgba, alpha=alpha) geom.contype = 0 geom.conaffinity = 0 def _stack(obs_settings, num_bricks, moveable_base, randomize_order, target_height=None): """Configure and instantiate a Stack task. Args: obs_settings: `observations.ObservationSettings` instance. num_bricks: The total number of bricks; must be between 2 and 6. moveable_base: Boolean specifying whether or not the bottom brick should be moveable. randomize_order: Boolean specifying whether to randomize the desired order of bricks in the stack at the start of each episode. target_height: The target number of bricks in the stack in order to get maximum reward. Must be between 2 and `num_bricks`. Defaults to `num_bricks`. Returns: An instance of `Stack`. """ if target_height is None: target_height = num_bricks arena = arenas.Standard() arm = robots.make_arm(obs_settings=obs_settings) hand = robots.make_hand(obs_settings=obs_settings) return Stack(arena=arena, arm=arm, hand=hand, num_bricks=num_bricks, target_height=target_height, moveable_base=moveable_base, randomize_order=randomize_order, obs_settings=obs_settings, workspace=_WORKSPACE, control_timestep=constants.CONTROL_TIMESTEP) @registry.add(tags.FEATURES) def stack_2_bricks_features(): return _stack(obs_settings=observations.PERFECT_FEATURES, num_bricks=2, moveable_base=False, randomize_order=False) @registry.add(tags.VISION) def stack_2_bricks_vision(): return _stack(obs_settings=observations.VISION, num_bricks=2, moveable_base=False, randomize_order=False) @registry.add(tags.FEATURES) def stack_2_bricks_moveable_base_features(): return _stack(obs_settings=observations.PERFECT_FEATURES, num_bricks=2, moveable_base=True, randomize_order=False) @registry.add(tags.VISION) def stack_2_bricks_moveable_base_vision(): return _stack(obs_settings=observations.VISION, num_bricks=2, moveable_base=True, randomize_order=False) @registry.add(tags.FEATURES) def stack_3_bricks_features(): return _stack(obs_settings=observations.PERFECT_FEATURES, num_bricks=3, moveable_base=False, randomize_order=False) @registry.add(tags.VISION) def stack_3_bricks_vision(): return _stack(obs_settings=observations.VISION, num_bricks=3, moveable_base=False, randomize_order=False) @registry.add(tags.FEATURES) def stack_3_bricks_random_order_features(): return _stack(obs_settings=observations.PERFECT_FEATURES, num_bricks=3, moveable_base=False, randomize_order=True) @registry.add(tags.FEATURES) def stack_2_of_3_bricks_random_order_features(): return _stack(obs_settings=observations.PERFECT_FEATURES, num_bricks=3, moveable_base=False, randomize_order=True, target_height=2) @registry.add(tags.VISION) def stack_2_of_3_bricks_random_order_vision(): return _stack(obs_settings=observations.VISION, num_bricks=3, moveable_base=False, randomize_order=True, target_height=2) def _reassemble(obs_settings, num_bricks, randomize_initial_order, randomize_desired_order): """Configure and instantiate a `Reassemble` task. Args: obs_settings: `observations.ObservationSettings` instance. num_bricks: The total number of bricks; must be between 2 and 6. randomize_initial_order: Boolean specifying whether to randomize the initial order of bricks in the stack at the start of each episode. randomize_desired_order: Boolean specifying whether to independently randomize the desired order of bricks in the stack at the start of each episode. By default the desired order will be the reverse of the initial order, with the exception of the base brick which is always the same as in the initial order since it is welded in place. Returns: An instance of `Reassemble`. """ arena = arenas.Standard() arm = robots.make_arm(obs_settings=obs_settings) hand = robots.make_hand(obs_settings=obs_settings) return Reassemble(arena=arena, arm=arm, hand=hand, num_bricks=num_bricks, randomize_initial_order=randomize_initial_order, randomize_desired_order=randomize_desired_order, obs_settings=obs_settings, workspace=_WORKSPACE, control_timestep=constants.CONTROL_TIMESTEP) @registry.add(tags.FEATURES) def reassemble_3_bricks_fixed_order_features(): return _reassemble(obs_settings=observations.PERFECT_FEATURES, num_bricks=3, randomize_initial_order=False, randomize_desired_order=False) @registry.add(tags.VISION) def reassemble_3_bricks_fixed_order_vision(): return _reassemble(obs_settings=observations.VISION, num_bricks=3, randomize_initial_order=False, randomize_desired_order=False) @registry.add(tags.FEATURES) def reassemble_5_bricks_random_order_features(): return _reassemble(obs_settings=observations.PERFECT_FEATURES, num_bricks=5, randomize_initial_order=True, randomize_desired_order=True) @registry.add(tags.VISION) def reassemble_5_bricks_random_order_vision(): return _reassemble(obs_settings=observations.VISION, num_bricks=5, randomize_initial_order=True, randomize_desired_order=True)
dm_control-main
dm_control/manipulation/bricks.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 standalone application for visualizing manipulation tasks.""" import functools from absl import app from absl import flags from dm_control import manipulation from dm_control import viewer flags.DEFINE_enum( 'environment_name', None, manipulation.ALL, 'Optional name of an environment to load. If unspecified ' 'a prompt will appear to select one.') FLAGS = flags.FLAGS # TODO(b/121187817): Consolidate with dm_control/suite/explore.py def prompt_environment_name(prompt, values): environment_name = None while not environment_name: environment_name = input(prompt) if not environment_name or values.index(environment_name) < 0: print('"%s" is not a valid environment name.' % environment_name) environment_name = None return environment_name def main(argv): del argv environment_name = FLAGS.environment_name all_names = list(manipulation.ALL) if environment_name is None: print('\n '.join(['Available environments:'] + all_names)) environment_name = prompt_environment_name( 'Please select an environment name: ', all_names) loader = functools.partial( manipulation.load, environment_name=environment_name) viewer.launch(loader) if __name__ == '__main__': app.run(main)
dm_control-main
dm_control/manipulation/explore.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. # ============================================================================ """Props for manipulation tasks.""" from dm_control.manipulation.props.primitive import Box from dm_control.manipulation.props.primitive import BoxWithSites from dm_control.manipulation.props.primitive import Capsule from dm_control.manipulation.props.primitive import Cylinder from dm_control.manipulation.props.primitive import Ellipsoid from dm_control.manipulation.props.primitive import Primitive from dm_control.manipulation.props.primitive import Sphere
dm_control-main
dm_control/manipulation/props/__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. # ============================================================================ """Props made of a single primitive MuJoCo geom.""" import itertools from dm_control import composer from dm_control import mjcf from dm_control.composer import define from dm_control.composer.observation import observable import numpy as np _DEFAULT_HALF_LENGTHS = [0.05, 0.1, 0.15] class Primitive(composer.Entity): """A primitive MuJoCo geom prop.""" def _build(self, geom_type, size, mass=None, name=None): """Initializes this prop. Args: geom_type: a string, one of the types supported by MuJoCo. size: a list or numpy array of up to 3 numbers, depending on the type. mass: The mass for the primitive geom. name: (optional) A string, the name of this prop. """ size = np.reshape(np.asarray(size), -1) self._mjcf_root = mjcf.element.RootElement(model=name) self._geom = self._mjcf_root.worldbody.add( 'geom', name='body_geom', type=geom_type, size=size, mass=mass) touch_sensor = self._mjcf_root.worldbody.add( 'site', type=geom_type, name='touch_sensor', size=size*1.05, rgba=[1, 1, 1, 0.1], # touch sensor site is almost transparent group=composer.SENSOR_SITES_GROUP) self._touch = self._mjcf_root.sensor.add( 'touch', site=touch_sensor) 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) self._linear_velocity = self._mjcf_root.sensor.add( 'framelinvel', name='linear_velocity', objtype='geom', objname=self.geom) self._angular_velocity = self._mjcf_root.sensor.add( 'frameangvel', name='angular_velocity', objtype='geom', objname=self.geom) self._name = name def _build_observables(self): return PrimitiveObservables(self) @property def geom(self): """Returns the primitive's geom, e.g., to change color or friction.""" return self._geom @property def touch(self): """Exposing the touch sensor for observations and reward.""" return self._touch @property def position(self): """Ground truth pos sensor.""" return self._position @property def orientation(self): """Ground truth angular position sensor.""" return self._orientation @property def linear_velocity(self): """Ground truth velocity sensor.""" return self._linear_velocity @property def angular_velocity(self): """Ground truth angular velocity sensor.""" return self._angular_velocity @property def mjcf_model(self): return self._mjcf_root @property def name(self): return self._name class PrimitiveObservables(composer.Observables, composer.FreePropObservableMixin): """Primitive entity's 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) @define.observable def linear_velocity(self): return observable.MJCFFeature('sensordata', self._entity.linear_velocity) @define.observable def angular_velocity(self): return observable.MJCFFeature('sensordata', self._entity.angular_velocity) @define.observable def touch(self): return observable.MJCFFeature('sensordata', self._entity.touch) class Sphere(Primitive): """A class representing a sphere prop.""" def _build(self, radius=0.05, mass=None, name='sphere'): super(Sphere, self)._build( geom_type='sphere', size=radius, mass=mass, name=name) class Box(Primitive): """A class representing a box prop.""" def _build(self, half_lengths=None, mass=None, name='box'): half_lengths = half_lengths or _DEFAULT_HALF_LENGTHS super(Box, self)._build(geom_type='box', size=half_lengths, mass=mass, name=name) class BoxWithSites(Box): """A class representing a box prop with sites on the corners.""" def _build(self, half_lengths=None, mass=None, name='box'): half_lengths = half_lengths or _DEFAULT_HALF_LENGTHS super(BoxWithSites, self)._build(half_lengths=half_lengths, mass=mass, name=name) corner_positions = itertools.product([half_lengths[0], -half_lengths[0]], [half_lengths[1], -half_lengths[1]], [half_lengths[2], -half_lengths[2]]) corner_sites = [] for i, corner_pos in enumerate(corner_positions): corner_sites.append( self._mjcf_root.worldbody.add( 'site', type='sphere', name='corner_{}'.format(i), size=[0.1], pos=corner_pos, rgba=[1, 0, 0, 1.0], group=composer.SENSOR_SITES_GROUP)) self._corner_sites = tuple(corner_sites) @property def corner_sites(self): return self._corner_sites class Ellipsoid(Primitive): """A class representing an ellipsoid prop.""" def _build(self, radii=None, mass=None, name='ellipsoid'): radii = radii or _DEFAULT_HALF_LENGTHS super(Ellipsoid, self)._build(geom_type='ellipsoid', size=radii, mass=mass, name=name) class Cylinder(Primitive): """A class representing a cylinder prop.""" def _build(self, radius=0.05, half_length=0.15, mass=None, name='cylinder'): super(Cylinder, self)._build(geom_type='cylinder', size=[radius, half_length], mass=mass, name=name) class Capsule(Primitive): """A class representing a capsule prop.""" def _build(self, radius=0.05, half_length=0.15, mass=None, name='capsule'): super(Capsule, self)._build(geom_type='capsule', size=[radius, half_length], mass=mass, name=name)
dm_control-main
dm_control/manipulation/props/primitive.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. # ============================================================================ """String constants used to annotate task constructors.""" FEATURES = 'features' VISION = 'vision' EASY = 'easy'
dm_control-main
dm_control/manipulation/shared/tags.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 global registry of constructors for manipulation environments.""" from dm_control.utils import containers _ALL_CONSTRUCTORS = containers.TaggedTasks(allow_overriding_keys=False) add = _ALL_CONSTRUCTORS.add get_constructor = _ALL_CONSTRUCTORS.__getitem__ get_all_names = _ALL_CONSTRUCTORS.keys get_tags = _ALL_CONSTRUCTORS.tags get_names_by_tag = _ALL_CONSTRUCTORS.tagged # This disables the check that prevents the same task constructor name from # being added to the container more than once. This is done in order to allow # individual task modules to be reloaded without also reloading `registry.py` # first (e.g. when "hot-reloading" environments using IPython's `autoreload` # extension). def done_importing_tasks(): _ALL_CONSTRUCTORS.allow_overriding_keys = True
dm_control-main
dm_control/manipulation/shared/registry.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. # ============================================================================ """Shared configuration options for observations.""" import collections import numpy as np class ObservableSpec(collections.namedtuple( 'ObservableSpec', ['enabled', 'update_interval', 'buffer_size', 'delay', 'aggregator', 'corruptor'])): """Configuration options for generic observables.""" __slots__ = () class CameraObservableSpec(collections.namedtuple( 'CameraObservableSpec', ('height', 'width') + ObservableSpec._fields)): """Configuration options for camera observables.""" __slots__ = () class ObservationSettings(collections.namedtuple( 'ObservationSettings', ['proprio', 'ftt', 'prop_pose', 'camera'])): """Container of `ObservableSpecs` grouped by category.""" __slots__ = () class ObservableNames(collections.namedtuple( 'ObservableNames', ['proprio', 'ftt', 'prop_pose', 'camera'])): """Container that groups the names of observables by category.""" __slots__ = () def __new__(cls, proprio=(), ftt=(), prop_pose=(), camera=()): return super(ObservableNames, cls).__new__( cls, proprio=proprio, ftt=ftt, prop_pose=prop_pose, camera=camera) # Global defaults for "feature" observables (i.e. anything that isn't a camera). _DISABLED_FEATURE = ObservableSpec( enabled=False, update_interval=1, buffer_size=1, delay=0, aggregator=None, corruptor=None) _ENABLED_FEATURE = _DISABLED_FEATURE._replace(enabled=True) # Force, torque and touch-sensor readings are scaled using a symmetric # logarithmic transformation that handles 0 and negative values. _symlog1p = lambda x, random_state: np.sign(x) * np.log1p(abs(x)) _DISABLED_FTT = _DISABLED_FEATURE._replace(corruptor=_symlog1p) _ENABLED_FTT = _ENABLED_FEATURE._replace(corruptor=_symlog1p) # Global defaults for camera observables. _DISABLED_CAMERA = CameraObservableSpec( height=84, width=84, enabled=False, update_interval=1, buffer_size=1, delay=0, aggregator=None, corruptor=None) _ENABLED_CAMERA = _DISABLED_CAMERA._replace(enabled=True) # Predefined sets of configurations options to apply to each category of # observable. PERFECT_FEATURES = ObservationSettings( proprio=_ENABLED_FEATURE, ftt=_ENABLED_FTT, prop_pose=_ENABLED_FEATURE, camera=_DISABLED_CAMERA) VISION = ObservationSettings( proprio=_ENABLED_FEATURE, ftt=_ENABLED_FTT, prop_pose=_DISABLED_FEATURE, camera=_ENABLED_CAMERA) JACO_ARM_OBSERVABLES = ObservableNames( proprio=['joints_pos', 'joints_vel'], ftt=['joints_torque']) JACO_HAND_OBSERVABLES = ObservableNames( proprio=['joints_pos', 'joints_vel', 'pinch_site_pos', 'pinch_site_rmat']) FREEPROP_OBSERVABLES = ObservableNames( prop_pose=['position', 'orientation', 'linear_velocity', 'angular_velocity']) def make_options(obs_settings, obs_names): """Constructs a dict of configuration options for a set of named observables. Args: obs_settings: An `ObservationSettings` instance. obs_names: An `ObservableNames` instance. Returns: A nested dict containing `{observable_name: {option_name: value}}`. """ observable_options = {} for category, spec in obs_settings._asdict().items(): for observable_name in getattr(obs_names, category): observable_options[observable_name] = spec._asdict() return observable_options
dm_control-main
dm_control/manipulation/shared/observations.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. # ============================================================================ """Global constants used in manipulation tasks.""" CONTROL_TIMESTEP = 0.04 # Interval between agent actions, in seconds. # Predefined RGBA values RED = (1., 0., 0., 0.3) GREEN = (0., 1., 0., 0.3) BLUE = (0., 0., 1., 0.3) CYAN = (0., 1., 1., 0.3) MAGENTA = (1., 0., 1., 0.3) YELLOW = (1., 1., 0., 0.3) TASK_SITE_GROUP = 3 # Invisible group for task-related sites.
dm_control-main
dm_control/manipulation/shared/constants.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. # ============================================================================
dm_control-main
dm_control/manipulation/shared/__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. # ============================================================================ """Tools for adding custom cameras to the arena.""" import collections from dm_control.composer.observation import observable CameraSpec = collections.namedtuple('CameraSpec', ['name', 'pos', 'xyaxes']) # Custom cameras that may be added to the arena for particular tasks. FRONT_CLOSE = CameraSpec( name='front_close', pos=(0., -0.6, 0.75), xyaxes=(1., 0., 0., 0., 0.7, 0.75) ) FRONT_FAR = CameraSpec( name='front_far', pos=(0., -0.8, 1.), xyaxes=(1., 0., 0., 0., 0.7, 0.75) ) TOP_DOWN = CameraSpec( name='top_down', pos=(0., 0., 2.5), xyaxes=(1., 0., 0., 0., 1., 0.) ) LEFT_CLOSE = CameraSpec( name='left_close', pos=(-0.6, 0., 0.75), xyaxes=(0., -1., 0., 0.7, 0., 0.75) ) RIGHT_CLOSE = CameraSpec( name='right_close', pos=(0.6, 0., 0.75), xyaxes=(0., 1., 0., -0.7, 0., 0.75) ) def add_camera_observables(entity, obs_settings, *camera_specs): """Adds cameras to an entity's worldbody and configures observables for them. Args: entity: A `composer.Entity`. obs_settings: An `observations.ObservationSettings` instance. *camera_specs: Instances of `CameraSpec`. Returns: A `collections.OrderedDict` keyed on camera names, containing pre-configured `observable.MJCFCamera` instances. """ obs_dict = collections.OrderedDict() for spec in camera_specs: camera = entity.mjcf_model.worldbody.add('camera', **spec._asdict()) obs = observable.MJCFCamera(camera) obs.configure(**obs_settings.camera._asdict()) obs_dict[spec.name] = obs return obs_dict
dm_control-main
dm_control/manipulation/shared/cameras.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. # ============================================================================ """Custom robot constructors with manipulation-specific defaults.""" from dm_control.entities.manipulators import kinova from dm_control.manipulation.shared import observations # The default position of the base of the arm relative to the origin. ARM_OFFSET = (0., 0.4, 0.) def make_arm(obs_settings): """Constructs a robot arm with manipulation-specific defaults. Args: obs_settings: `observations.ObservationSettings` instance. Returns: An instance of `manipulators.base.RobotArm`. """ return kinova.JacoArm( observable_options=observations.make_options( obs_settings, observations.JACO_ARM_OBSERVABLES)) def make_hand(obs_settings): """Constructs a robot hand with manipulation-specific defaults. Args: obs_settings: `observations.ObservationSettings` instance. Returns: An instance of `manipulators.base.RobotHand`. """ return kinova.JacoHand( use_pinch_site_as_tcp=True, observable_options=observations.make_options( obs_settings, observations.JACO_HAND_OBSERVABLES))
dm_control-main
dm_control/manipulation/shared/robots.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. # ============================================================================ """Suite-specific arena class.""" from dm_control import composer class Standard(composer.Arena): """Suite-specific subclass of the standard Composer arena.""" def _build(self, name=None): """Initializes this arena. Args: name: (optional) A string, the name of this arena. If `None`, use the model name defined in the MJCF file. """ super()._build(name=name) # Add visual assets. self.mjcf_model.asset.add( 'texture', type='skybox', builtin='gradient', rgb1=(0.4, 0.6, 0.8), rgb2=(0., 0., 0.), width=100, height=100) groundplane_texture = self.mjcf_model.asset.add( 'texture', name='groundplane', type='2d', builtin='checker', rgb1=(0.2, 0.3, 0.4), rgb2=(0.1, 0.2, 0.3), width=300, height=300, mark='edge', markrgb=(.8, .8, .8)) groundplane_material = self.mjcf_model.asset.add( 'material', name='groundplane', texture=groundplane_texture, texrepeat=(5, 5), texuniform='true', reflectance=0.2) # Add ground plane. self.mjcf_model.worldbody.add( 'geom', name='ground', type='plane', material=groundplane_material, size=(1, 1, 0.1), friction=(0.4,), solimp=(0.95, 0.99, 0.001), solref=(0.002, 1)) # Add lighting self.mjcf_model.worldbody.add( 'light', pos=(0, 0, 1.5), dir=(0, 0, -1), diffuse=(0.7, 0.7, 0.7), specular=(.3, .3, .3), directional='false', castshadow='true') # Always initialize the free camera so that it points at the origin. self.mjcf_model.statistic.center = (0., 0., 0.) def attach_offset(self, entity, offset, attach_site=None): """Attaches another entity at a position offset from the attachment site. Args: entity: The `Entity` to attach. offset: A length 3 array-like object representing the XYZ offset. 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. """ frame = self.attach(entity, attach_site=attach_site) frame.pos = offset return frame
dm_control-main
dm_control/manipulation/shared/arenas.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. # ============================================================================ """Tools for defining and visualizing workspaces for manipulation tasks. Workspaces define distributions from which the initial positions and/or orientations of the hand and prop(s) are sampled, plus other task-specific spatial parameters such as target sizes. """ import collections from dm_control.composer.variation import distributions from dm_control.composer.variation import rotations from dm_control.entities.manipulators import base from dm_control.manipulation.shared import constants import numpy as np _MIN_SITE_DIMENSION = 1e-6 # Ensures that all site dimensions are positive. _VISIBLE_GROUP = 0 _INVISIBLE_GROUP = 3 # Invisible sensor sites live in group 4 by convention. DOWN_QUATERNION = base.DOWN_QUATERNION BoundingBox = collections.namedtuple('BoundingBox', ['lower', 'upper']) uniform_z_rotation = rotations.QuaternionFromAxisAngle( axis=(0., 0., 1.), # NB: We must specify `single_sample=True` here otherwise we will sample a # length-4 array of angles rather than a scalar. This happens because # `PropPlacer` passes in the previous quaternion as `initial_value`, # and by default `distributions.Distribution` assumes that the shape # of the output array should be the same as that of `initial_value`. angle=distributions.Uniform(-np.pi, np.pi, single_sample=True)) def add_bbox_site(body, lower, upper, visible=False, **kwargs): """Adds a site for visualizing a bounding box to an MJCF model. Args: body: An `mjcf.Element`, the (world)body to which the site should be added. lower: A sequence of lower x,y,z bounds. upper: A sequence of upper x,y,z bounds. visible: Whether the site should be visible by default. **kwargs: Keyword arguments used to set other attributes of the newly created site. Returns: An `mjcf.Element` representing the newly created site. """ upper = np.array(upper) lower = np.array(lower) pos = (upper + lower) / 2. size = np.maximum((upper - lower) / 2., _MIN_SITE_DIMENSION) group = None if visible else constants.TASK_SITE_GROUP return body.add( 'site', type='box', pos=pos, size=size, group=group, **kwargs) def add_target_site(body, radius, visible=False, **kwargs): """Adds a site for visualizing a target location. Args: body: An `mjcf.Element`, the (world)body to which the site should be added. radius: The radius of the target. visible: Whether the site should be visible by default. **kwargs: Keyword arguments used to set other attributes of the newly created site. Returns: An `mjcf.Element` representing the newly created site. """ group = None if visible else constants.TASK_SITE_GROUP return body.add( 'site', type='sphere', size=[radius], group=group, **kwargs)
dm_control-main
dm_control/manipulation/shared/workspaces.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. # ============================================================================
dm_control-main
dm_control/locomotion/__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. # ============================================================================ """A (visuomotor) task consisting of reaching to targets for reward.""" import collections import enum import itertools from dm_control import composer from dm_control.composer.observation import observable as dm_observable import numpy as np DEFAULT_ALIVE_THRESHOLD = -1.0 DEFAULT_PHYSICS_TIMESTEP = 0.005 DEFAULT_CONTROL_TIMESTEP = 0.03 class TwoTouchState(enum.IntEnum): PRE_TOUCH = 0 TOUCHED_ONCE = 1 TOUCHED_TWICE = 2 # at appropriate time TOUCHED_TOO_SOON = 3 NO_SECOND_TOUCH = 4 class TwoTouch(composer.Task): """Task with target to tap with short delay (for Rat).""" def __init__(self, walker, arena, target_builders, target_type_rewards, shuffle_target_builders=False, randomize_spawn_position=False, randomize_spawn_rotation=True, rotation_bias_factor=0, aliveness_reward=0.0, touch_interval=0.8, interval_tolerance=0.1, # consider making a curriculum failure_timeout=1.2, reset_delay=0., z_height=.14, # 5.5" in real experiments target_area=(), physics_timestep=DEFAULT_PHYSICS_TIMESTEP, control_timestep=DEFAULT_CONTROL_TIMESTEP): self._walker = walker self._arena = arena self._walker.create_root_joints(self._arena.attach(self._walker)) if 'CMUHumanoid' in str(type(self._walker)): self._lhand_body = walker.mjcf_model.find('body', 'lhand') self._rhand_body = walker.mjcf_model.find('body', 'rhand') elif 'Rat' in str(type(self._walker)): self._lhand_body = walker.mjcf_model.find('body', 'hand_L') self._rhand_body = walker.mjcf_model.find('body', 'hand_R') else: raise ValueError('Expects Rat or CMUHumanoid.') self._lhand_geoms = self._lhand_body.find_all('geom') self._rhand_geoms = self._rhand_body.find_all('geom') self._targets = [] self._target_builders = target_builders self._target_type_rewards = tuple(target_type_rewards) self._shuffle_target_builders = shuffle_target_builders self._randomize_spawn_position = randomize_spawn_position self._spawn_position = [0.0, 0.0] # x, y self._randomize_spawn_rotation = randomize_spawn_rotation self._rotation_bias_factor = rotation_bias_factor self._aliveness_reward = aliveness_reward self._discount = 1.0 self._touch_interval = touch_interval self._interval_tolerance = interval_tolerance self._failure_timeout = failure_timeout self._reset_delay = reset_delay self._target_positions = [] self._state_logic = TwoTouchState.PRE_TOUCH self._z_height = z_height arena_size = self._arena.size if target_area: self._target_area = target_area else: self._target_area = [1/2*arena_size[0], 1/2*arena_size[1]] target_x = 1. target_y = 1. self._target_positions.append((target_x, target_y, self._z_height)) self.set_timesteps( physics_timestep=physics_timestep, control_timestep=control_timestep) self._task_observables = collections.OrderedDict() def task_state(physics): del physics return np.array([self._state_logic]) self._task_observables['task_logic'] = dm_observable.Generic(task_state) self._walker.observables.egocentric_camera.height = 64 self._walker.observables.egocentric_camera.width = 64 for observable in (self._walker.observables.proprioception + self._walker.observables.kinematic_sensors + self._walker.observables.dynamic_sensors + list(self._task_observables.values())): observable.enabled = True self._walker.observables.egocentric_camera.enabled = True def _get_targets(self, total_target_count, random_state): # Multiply total target count by the fraction for each type, rounded down. target_numbers = np.array([1, len(self._target_positions)-1]) if self._shuffle_target_builders: random_state.shuffle(self._target_builders) all_targets = [] for target_type, num in enumerate(target_numbers): targets = [] if num < 1: break target_builder = self._target_builders[target_type] for i in range(num): target = target_builder(name='target_{}_{}'.format(target_type, i)) targets.append(target) all_targets.append(targets) return all_targets @property def name(self): return 'two_touch' @property def task_observables(self): return self._task_observables @property def root_entity(self): return self._arena def _randomize_targets(self, physics, random_state=np.random): for ii in range(len(self._target_positions)): target_x = self._target_area[0]*random_state.uniform(-1., 1.) target_y = self._target_area[1]*random_state.uniform(-1., 1.) self._target_positions[ii] = (target_x, target_y, self._z_height) target_positions = np.copy(self._target_positions) random_state.shuffle(target_positions) all_targets = self._targets for pos, target in zip(target_positions, itertools.chain(*all_targets)): target.reset(physics) physics.bind(target.geom).pos = pos self._targets = all_targets self._target_rewarded_once = [ [False] * len(targets) for targets in all_targets] self._target_rewarded_twice = [ [False] * len(targets) for targets in all_targets] self._first_touch_time = None self._second_touch_time = None self._do_time_out = False self._state_logic = TwoTouchState.PRE_TOUCH def initialize_episode_mjcf(self, random_state): self._arena.regenerate(random_state) for target in itertools.chain(*self._targets): target.detach() target_positions = np.copy(self._target_positions) random_state.shuffle(target_positions) all_targets = self._get_targets(len(self._target_positions), random_state) for pos, target in zip(target_positions, itertools.chain(*all_targets)): self._arena.attach(target) target.geom.pos = pos target.initialize_episode_mjcf(random_state) self._targets = all_targets def _respawn_walker(self, physics, random_state): self._walker.reinitialize_pose(physics, random_state) if self._randomize_spawn_position: self._spawn_position = self._arena.spawn_positions[ random_state.randint(0, len(self._arena.spawn_positions))] if self._randomize_spawn_rotation: rotation = 2*np.pi*np.random.uniform() quat = [np.cos(rotation / 2), 0, 0, np.sin(rotation / 2)] self._walker.shift_pose( physics, [self._spawn_position[0], self._spawn_position[1], 0.0], quat, rotate_velocity=True) def initialize_episode(self, physics, random_state): super().initialize_episode(physics, random_state) self._respawn_walker(physics, random_state) self._state_logic = TwoTouchState.PRE_TOUCH self._discount = 1.0 self._lhand_geomids = set(physics.bind(self._lhand_geoms).element_id) self._rhand_geomids = set(physics.bind(self._rhand_geoms).element_id) self._hand_geomids = self._lhand_geomids | self._rhand_geomids self._randomize_targets(physics) self._must_randomize_targets = False for target in itertools.chain(*self._targets): target._specific_collision_geom_ids = self._hand_geomids # pylint: disable=protected-access def before_step(self, physics, action, random_state): super().before_step(physics, action, random_state) if self._must_randomize_targets: self._randomize_targets(physics) self._must_randomize_targets = False def should_terminate_episode(self, physics): failure_termination = False if failure_termination: self._discount = 0.0 return True else: return False def get_reward(self, physics): reward = self._aliveness_reward lhand_pos = physics.bind(self._lhand_body).xpos rhand_pos = physics.bind(self._rhand_body).xpos target_pos = physics.bind(self._targets[0][0].geom).xpos lhand_rew = np.exp(-3.*sum(np.abs(lhand_pos-target_pos))) rhand_rew = np.exp(-3.*sum(np.abs(rhand_pos-target_pos))) closeness_reward = np.maximum(lhand_rew, rhand_rew) reward += .01*closeness_reward*self._target_type_rewards[0] if self._state_logic == TwoTouchState.PRE_TOUCH: # touch the first time for target_type, targets in enumerate(self._targets): for i, target in enumerate(targets): if (target.activated[0] and not self._target_rewarded_once[target_type][i]): self._first_touch_time = physics.time() self._state_logic = TwoTouchState.TOUCHED_ONCE self._target_rewarded_once[target_type][i] = True reward += self._target_type_rewards[target_type] elif self._state_logic == TwoTouchState.TOUCHED_ONCE: for target_type, targets in enumerate(self._targets): for i, target in enumerate(targets): if (target.activated[1] and not self._target_rewarded_twice[target_type][i]): self._second_touch_time = physics.time() self._state_logic = TwoTouchState.TOUCHED_TWICE self._target_rewarded_twice[target_type][i] = True # check if touched too soon if ((self._second_touch_time - self._first_touch_time) < (self._touch_interval - self._interval_tolerance)): self._do_time_out = True self._state_logic = TwoTouchState.TOUCHED_TOO_SOON # check if touched at correct time elif ((self._second_touch_time - self._first_touch_time) <= (self._touch_interval + self._interval_tolerance)): reward += self._target_type_rewards[target_type] # check if no second touch within time interval if ((physics.time() - self._first_touch_time) > (self._touch_interval + self._interval_tolerance)): self._do_time_out = True self._state_logic = TwoTouchState.NO_SECOND_TOUCH self._second_touch_time = physics.time() elif (self._state_logic == TwoTouchState.TOUCHED_TWICE or self._state_logic == TwoTouchState.TOUCHED_TOO_SOON or self._state_logic == TwoTouchState.NO_SECOND_TOUCH): # hold here due to timeout if self._do_time_out: if physics.time() > (self._second_touch_time + self._failure_timeout): self._do_time_out = False # reset/re-randomize elif physics.time() > (self._second_touch_time + self._reset_delay): self._must_randomize_targets = True return reward def get_discount(self, physics): del physics return self._discount
dm_control-main
dm_control/locomotion/tasks/reach.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. # ============================================================================ """Escape locomotion tasks.""" from dm_control import composer from dm_control import mjcf from dm_control.composer.observation import observable as base_observable from dm_control.rl import control from dm_control.utils import rewards import numpy as np # Constants related to terrain generation. _HEIGHTFIELD_ID = 0 class Escape(composer.Task): """A task solved by escaping a starting area (e.g. bowl-shaped terrain).""" def __init__(self, walker, arena, walker_spawn_position=(0, 0, 0), walker_spawn_rotation=None, physics_timestep=0.005, control_timestep=0.025): """Initializes this task. Args: walker: an instance of `locomotion.walkers.base.Walker`. arena: an instance of `locomotion.arenas`. walker_spawn_position: a sequence of 3 numbers, or a `composer.Variation` instance that generates such sequences, specifying the position at which the walker is spawned at the beginning of an episode. walker_spawn_rotation: a number, or a `composer.Variation` instance that generates a number, specifying the yaw angle offset (in radians) that is applied to the walker at the beginning of an episode. physics_timestep: a number specifying the timestep (in seconds) of the physics simulation. control_timestep: a number specifying the timestep (in seconds) at which the agent applies its control inputs (in seconds). """ self._arena = arena self._walker = walker self._walker.create_root_joints(self._arena.attach(self._walker)) self._walker_spawn_position = walker_spawn_position self._walker_spawn_rotation = walker_spawn_rotation enabled_observables = [] enabled_observables += self._walker.observables.proprioception enabled_observables += self._walker.observables.kinematic_sensors enabled_observables += self._walker.observables.dynamic_sensors enabled_observables.append(self._walker.observables.sensors_touch) enabled_observables.append(self._walker.observables.egocentric_camera) for observable in enabled_observables: observable.enabled = True if 'CMUHumanoid' in str(type(self._walker)): core_body = 'walker/root' self._reward_body = 'walker/root' elif 'Rat' in str(type(self._walker)): core_body = 'walker/torso' self._reward_body = 'walker/head' else: raise ValueError('Expects Rat or CMUHumanoid.') def _origin(physics): """Returns origin position in the torso frame.""" torso_frame = physics.named.data.xmat[core_body].reshape(3, 3) torso_pos = physics.named.data.xpos[core_body] return -torso_pos.dot(torso_frame) self._walker.observables.add_observable( 'origin', base_observable.Generic(_origin)) self.set_timesteps( physics_timestep=physics_timestep, control_timestep=control_timestep) @property def root_entity(self): return self._arena def initialize_episode_mjcf(self, random_state): if hasattr(self._arena, 'regenerate'): self._arena.regenerate(random_state) self._arena.mjcf_model.visual.map.znear = 0.00025 self._arena.mjcf_model.visual.map.zfar = 50. def initialize_episode(self, physics, random_state): super().initialize_episode(physics, random_state) # Initial configuration. orientation = random_state.randn(4) orientation /= np.linalg.norm(orientation) _find_non_contacting_height(physics, self._walker, orientation) def get_reward(self, physics): # Escape reward term. terrain_size = physics.model.hfield_size[_HEIGHTFIELD_ID, 0] escape_reward = rewards.tolerance( np.asarray(np.linalg.norm( physics.named.data.site_xpos[self._reward_body])), bounds=(terrain_size, float('inf')), margin=terrain_size, value_at_margin=0, sigmoid='linear') upright_reward = _upright_reward(physics, self._walker, deviation_angle=30) return upright_reward * escape_reward def get_discount(self, physics): return 1. def _find_non_contacting_height(physics, walker, orientation, x_pos=0.0, y_pos=0.0, maxiter=1000): """Find a height with no contacts given a body orientation. Args: physics: An instance of `Physics`. walker: the focal walker. orientation: A quaternion. x_pos: A float. Position along global x-axis. y_pos: A float. Position along global y-axis. maxiter: maximum number of iterations to try """ z_pos = 0.0 # Start embedded in the floor. num_contacts = 1 count = 1 # Move up in 1cm increments until no contacts. while num_contacts > 0: try: with physics.reset_context(): freejoint = mjcf.get_frame_freejoint(walker.mjcf_model) physics.bind(freejoint).qpos[:3] = x_pos, y_pos, z_pos physics.bind(freejoint).qpos[3:] = orientation except control.PhysicsError: # We may encounter a PhysicsError here due to filling the contact # buffer, in which case we simply increment the height and continue. pass num_contacts = physics.data.ncon z_pos += 0.01 count += 1 if count > maxiter: raise ValueError( 'maxiter reached: possibly contacts in null pose of body.' ) def _upright_reward(physics, walker, deviation_angle=0): """Returns a reward proportional to how upright the torso is. Args: physics: an instance of `Physics`. walker: the focal walker. deviation_angle: A float, in degrees. The reward is 0 when the torso is exactly upside-down and 1 when the torso's z-axis is less than `deviation_angle` away from the global z-axis. """ deviation = np.cos(np.deg2rad(deviation_angle)) upright_torso = physics.bind(walker.root_body).xmat[-1] if hasattr(walker, 'pelvis_body'): upright_pelvis = physics.bind(walker.pelvis_body).xmat[-1] upright_zz = np.stack([upright_torso, upright_pelvis]) else: upright_zz = upright_torso upright = rewards.tolerance(upright_zz, bounds=(deviation, float('inf')), sigmoid='linear', margin=1 + deviation, value_at_margin=0) return np.min(upright)
dm_control-main
dm_control/locomotion/tasks/escape.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.tasks.corridors.""" from absl.testing import absltest from absl.testing import parameterized from dm_control import composer from dm_control import mjcf from dm_control.composer.variation import deterministic from dm_control.composer.variation import rotations from dm_control.locomotion.arenas import corridors as corridor_arenas from dm_control.locomotion.tasks import corridors as corridor_tasks from dm_control.locomotion.walkers import cmu_humanoid import numpy as np class CorridorsTest(parameterized.TestCase): @parameterized.parameters( dict(position_offset=(0, 0, 0), rotate_180_degrees=False, use_variations=False), dict(position_offset=(1, 2, 3), rotate_180_degrees=True, use_variations=True)) def test_walker_is_correctly_reinitialized( self, position_offset, rotate_180_degrees, use_variations): walker_spawn_position = position_offset if not rotate_180_degrees: walker_spawn_rotation = None else: walker_spawn_rotation = np.pi if use_variations: walker_spawn_position = deterministic.Constant(position_offset) walker_spawn_rotation = deterministic.Constant(walker_spawn_rotation) walker = cmu_humanoid.CMUHumanoid() arena = corridor_arenas.EmptyCorridor() task = corridor_tasks.RunThroughCorridor( walker=walker, arena=arena, walker_spawn_position=walker_spawn_position, walker_spawn_rotation=walker_spawn_rotation) # Randomize the initial pose and joint positions in order to check that they # are set correctly by `initialize_episode`. random_state = np.random.RandomState(12345) task.initialize_episode_mjcf(random_state) physics = mjcf.Physics.from_mjcf_model(task.root_entity.mjcf_model) walker_joints = walker.mjcf_model.find_all('joint') physics.bind(walker_joints).qpos = random_state.uniform( size=len(walker_joints)) walker.set_pose(physics, position=random_state.uniform(size=3), quaternion=rotations.UniformQuaternion()(random_state)) task.initialize_episode(physics, random_state) physics.forward() with self.subTest('Correct joint positions'): walker_qpos = physics.bind(walker_joints).qpos if walker.upright_pose.qpos is not None: np.testing.assert_array_equal(walker_qpos, walker.upright_pose.qpos) else: walker_qpos0 = physics.bind(walker_joints).qpos0 np.testing.assert_array_equal(walker_qpos, walker_qpos0) walker_xpos, walker_xquat = walker.get_pose(physics) with self.subTest('Correct position'): expected_xpos = walker.upright_pose.xpos + np.array(position_offset) np.testing.assert_array_equal(walker_xpos, expected_xpos) with self.subTest('Correct orientation'): upright_xquat = walker.upright_pose.xquat.copy() upright_xquat /= np.linalg.norm(walker.upright_pose.xquat) if rotate_180_degrees: expected_xquat = (-upright_xquat[3], -upright_xquat[2], upright_xquat[1], upright_xquat[0]) else: expected_xquat = upright_xquat np.testing.assert_allclose(walker_xquat, expected_xquat) def test_termination_and_discount(self): walker = cmu_humanoid.CMUHumanoid() arena = corridor_arenas.EmptyCorridor() task = corridor_tasks.RunThroughCorridor(walker, arena) random_state = np.random.RandomState(12345) env = composer.Environment(task, random_state=random_state) env.reset() zero_action = np.zeros_like(env.physics.data.ctrl) # Walker starts in upright position. # Should not trigger failure termination in the first few steps. for _ in range(5): env.step(zero_action) self.assertFalse(task.should_terminate_episode(env.physics)) self.assertEqual(task.get_discount(env.physics), 1) # Rotate the walker upside down and run the physics until it makes contact. current_time = env.physics.data.time walker.shift_pose(env.physics, position=(0, 0, 10), quaternion=(0, 1, 0, 0)) env.physics.forward() while env.physics.data.ncon == 0: env.physics.step() env.physics.data.time = current_time # Should now trigger a failure termination. env.step(zero_action) self.assertTrue(task.should_terminate_episode(env.physics)) self.assertEqual(task.get_discount(env.physics), 0) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/tasks/corridors_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. # ============================================================================ """A task consisting of finding goals/targets in a random maze.""" import collections import itertools from dm_control import composer from dm_control import mjcf from dm_control.composer.observation import observable as observable_lib from dm_control.locomotion.props import target_sphere from dm_control.mujoco.wrapper import mjbindings import numpy as np _NUM_RAYS = 10 # Aliveness in [-1., 0.]. DEFAULT_ALIVE_THRESHOLD = -0.5 DEFAULT_PHYSICS_TIMESTEP = 0.001 DEFAULT_CONTROL_TIMESTEP = 0.025 class NullGoalMaze(composer.Task): """A base task for maze with goals.""" def __init__(self, walker, maze_arena, randomize_spawn_position=True, randomize_spawn_rotation=True, rotation_bias_factor=0, aliveness_reward=0.0, aliveness_threshold=DEFAULT_ALIVE_THRESHOLD, contact_termination=True, enable_global_task_observables=False, physics_timestep=DEFAULT_PHYSICS_TIMESTEP, control_timestep=DEFAULT_CONTROL_TIMESTEP): """Initializes goal-directed maze task. Args: walker: The body to navigate the maze. maze_arena: The physical maze arena object. randomize_spawn_position: Flag to randomize position of spawning. randomize_spawn_rotation: Flag to randomize orientation of spawning. rotation_bias_factor: A non-negative number that concentrates initial orientation away from walls. When set to zero, the initial orientation is uniformly random. The larger the value of this number, the more likely it is that the initial orientation would face the direction that is farthest away from a wall. aliveness_reward: Reward for being alive. aliveness_threshold: Threshold if should terminate based on walker aliveness feature. contact_termination: whether to terminate if a non-foot geom touches the ground. enable_global_task_observables: Flag to provide task observables that contain global information, including map layout. physics_timestep: timestep of simulation. control_timestep: timestep at which agent changes action. """ self._walker = walker self._maze_arena = maze_arena self._walker.create_root_joints(self._maze_arena.attach(self._walker)) self._randomize_spawn_position = randomize_spawn_position self._randomize_spawn_rotation = randomize_spawn_rotation self._rotation_bias_factor = rotation_bias_factor self._aliveness_reward = aliveness_reward self._aliveness_threshold = aliveness_threshold self._contact_termination = contact_termination self._discount = 1.0 self.set_timesteps( physics_timestep=physics_timestep, control_timestep=control_timestep) self._walker.observables.egocentric_camera.height = 64 self._walker.observables.egocentric_camera.width = 64 for observable in (self._walker.observables.proprioception + self._walker.observables.kinematic_sensors + self._walker.observables.dynamic_sensors): observable.enabled = True self._walker.observables.egocentric_camera.enabled = True if enable_global_task_observables: # Reveal maze text map as observable. maze_obs = observable_lib.Generic( lambda _: self._maze_arena.maze.entity_layer) maze_obs.enabled = True # absolute walker position def get_walker_pos(physics): walker_pos = physics.bind(self._walker.root_body).xpos return walker_pos absolute_position = observable_lib.Generic(get_walker_pos) absolute_position.enabled = True # absolute walker orientation def get_walker_ori(physics): walker_ori = np.reshape( physics.bind(self._walker.root_body).xmat, (3, 3)) return walker_ori absolute_orientation = observable_lib.Generic(get_walker_ori) absolute_orientation.enabled = True # grid element of player in maze cell: i,j cell in maze layout def get_walker_ij(physics): walker_xypos = physics.bind(self._walker.root_body).xpos[:-1] walker_rel_origin = ( (walker_xypos + np.sign(walker_xypos) * self._maze_arena.xy_scale / 2) / (self._maze_arena.xy_scale)).astype(int) x_offset = (self._maze_arena.maze.width - 1) / 2 y_offset = (self._maze_arena.maze.height - 1) / 2 walker_ij = walker_rel_origin + np.array([x_offset, y_offset]) return walker_ij absolute_position_discrete = observable_lib.Generic(get_walker_ij) absolute_position_discrete.enabled = True self._task_observables = collections.OrderedDict({ 'maze_layout': maze_obs, 'absolute_position': absolute_position, 'absolute_orientation': absolute_orientation, 'location_in_maze': absolute_position_discrete, # from bottom left }) else: self._task_observables = collections.OrderedDict({}) @property def task_observables(self): return self._task_observables @property def name(self): return 'goal_maze' @property def root_entity(self): return self._maze_arena def initialize_episode_mjcf(self, unused_random_state): self._maze_arena.regenerate() def _respawn(self, physics, random_state): self._walker.reinitialize_pose(physics, random_state) if self._randomize_spawn_position: self._spawn_position = self._maze_arena.spawn_positions[ random_state.randint(0, len(self._maze_arena.spawn_positions))] else: self._spawn_position = self._maze_arena.spawn_positions[0] if self._randomize_spawn_rotation: # Move walker up out of the way before raycasting. self._walker.shift_pose(physics, [0.0, 0.0, 100.0]) distances = [] geomid_out = np.array([-1], dtype=np.intc) for i in range(_NUM_RAYS): theta = 2 * np.pi * i / _NUM_RAYS pos = np.array([self._spawn_position[0], self._spawn_position[1], 0.1], dtype=np.float64) vec = np.array([np.cos(theta), np.sin(theta), 0], dtype=np.float64) dist = mjbindings.mjlib.mj_ray( physics.model.ptr, physics.data.ptr, pos, vec, None, 1, -1, geomid_out) distances.append(dist) def remap_with_bias(x): """Remaps values [-1, 1] -> [-1, 1] with bias.""" return np.tanh((1 + self._rotation_bias_factor) * np.arctanh(x)) max_theta = 2 * np.pi * np.argmax(distances) / _NUM_RAYS rotation = max_theta + np.pi * ( 1 + remap_with_bias(random_state.uniform(-1, 1))) quat = [np.cos(rotation / 2), 0, 0, np.sin(rotation / 2)] # Move walker back down. self._walker.shift_pose(physics, [0.0, 0.0, -100.0]) else: quat = None self._walker.shift_pose( physics, [self._spawn_position[0], self._spawn_position[1], 0.0], quat, rotate_velocity=True) def initialize_episode(self, physics, random_state): super().initialize_episode(physics, random_state) self._respawn(physics, random_state) self._discount = 1.0 walker_foot_geoms = set(self._walker.ground_contact_geoms) walker_nonfoot_geoms = [ geom for geom in self._walker.mjcf_model.find_all('geom') if geom not in walker_foot_geoms] self._walker_nonfoot_geomids = set( physics.bind(walker_nonfoot_geoms).element_id) self._ground_geomids = set( physics.bind(self._maze_arena.ground_geoms).element_id) def _is_disallowed_contact(self, contact): set1, set2 = self._walker_nonfoot_geomids, self._ground_geomids return ((contact.geom1 in set1 and contact.geom2 in set2) or (contact.geom1 in set2 and contact.geom2 in set1)) def after_step(self, physics, random_state): self._failure_termination = False if self._contact_termination: for c in physics.data.contact: if self._is_disallowed_contact(c): self._failure_termination = True break def should_terminate_episode(self, physics): if self._walker.aliveness(physics) < self._aliveness_threshold: self._failure_termination = True if self._failure_termination: self._discount = 0.0 return True else: return False def get_reward(self, physics): del physics return self._aliveness_reward def get_discount(self, physics): del physics return self._discount class RepeatSingleGoalMaze(NullGoalMaze): """Requires an agent to repeatedly find the same goal in a maze.""" def __init__(self, walker, maze_arena, target=None, target_reward_scale=1.0, randomize_spawn_position=True, randomize_spawn_rotation=True, rotation_bias_factor=0, aliveness_reward=0.0, aliveness_threshold=DEFAULT_ALIVE_THRESHOLD, contact_termination=True, max_repeats=0, enable_global_task_observables=False, physics_timestep=DEFAULT_PHYSICS_TIMESTEP, control_timestep=DEFAULT_CONTROL_TIMESTEP, regenerate_maze_on_repeat=False): super().__init__( walker=walker, maze_arena=maze_arena, randomize_spawn_position=randomize_spawn_position, randomize_spawn_rotation=randomize_spawn_rotation, rotation_bias_factor=rotation_bias_factor, aliveness_reward=aliveness_reward, aliveness_threshold=aliveness_threshold, contact_termination=contact_termination, enable_global_task_observables=enable_global_task_observables, physics_timestep=physics_timestep, control_timestep=control_timestep) if target is None: target = target_sphere.TargetSphere() self._target = target self._rewarded_this_step = False self._maze_arena.attach(target) self._target_reward_scale = target_reward_scale self._max_repeats = max_repeats self._targets_obtained = 0 self._regenerate_maze_on_repeat = regenerate_maze_on_repeat if enable_global_task_observables: xpos_origin_callable = lambda phys: phys.bind(walker.root_body).xpos def _target_pos(physics, target=target): return physics.bind(target.geom).xpos walker.observables.add_egocentric_vector( 'target_0', observable_lib.Generic(_target_pos), origin_callable=xpos_origin_callable) def initialize_episode_mjcf(self, random_state): super().initialize_episode_mjcf(random_state) self._target_position = self._maze_arena.target_positions[ random_state.randint(0, len(self._maze_arena.target_positions))] mjcf.get_attachment_frame( self._target.mjcf_model).pos = self._target_position def initialize_episode(self, physics, random_state): super().initialize_episode(physics, random_state) self._rewarded_this_step = False self._targets_obtained = 0 def after_step(self, physics, random_state): super().after_step(physics, random_state) if self._target.activated: self._rewarded_this_step = True self._targets_obtained += 1 if self._targets_obtained <= self._max_repeats: if self._regenerate_maze_on_repeat: self.initialize_episode_mjcf(random_state) self._target.set_pose(physics, self._target_position) self._respawn(physics, random_state) self._target.reset(physics) else: self._rewarded_this_step = False def should_terminate_episode(self, physics): if super().should_terminate_episode(physics): return True if self._targets_obtained > self._max_repeats: return True def get_reward(self, physics): del physics if self._rewarded_this_step: target_reward = self._target_reward_scale else: target_reward = 0.0 return target_reward + self._aliveness_reward class ManyHeterogeneousGoalsMaze(NullGoalMaze): """Requires an agent to find multiple goals with different rewards.""" def __init__(self, walker, maze_arena, target_builders, target_type_rewards, target_type_proportions, shuffle_target_builders=False, randomize_spawn_position=True, randomize_spawn_rotation=True, rotation_bias_factor=0, aliveness_reward=0.0, aliveness_threshold=DEFAULT_ALIVE_THRESHOLD, contact_termination=True, physics_timestep=DEFAULT_PHYSICS_TIMESTEP, control_timestep=DEFAULT_CONTROL_TIMESTEP): super().__init__( walker=walker, maze_arena=maze_arena, randomize_spawn_position=randomize_spawn_position, randomize_spawn_rotation=randomize_spawn_rotation, rotation_bias_factor=rotation_bias_factor, aliveness_reward=aliveness_reward, aliveness_threshold=aliveness_threshold, contact_termination=contact_termination, physics_timestep=physics_timestep, control_timestep=control_timestep) self._active_targets = [] self._target_builders = target_builders self._target_type_rewards = tuple(target_type_rewards) self._target_type_fractions = ( np.array(target_type_proportions, dtype=float) / np.sum(target_type_proportions)) self._shuffle_target_builders = shuffle_target_builders def _get_targets(self, total_target_count, random_state): # Multiply total target count by the fraction for each type, rounded down. target_numbers = np.array([int(frac * total_target_count) for frac in self._target_type_fractions]) # Calculate deviations from the ideal ratio incurred by rounding. errors = (self._target_type_fractions - target_numbers / float(total_target_count)) # Sort the target types by deviations from ideal ratios. target_types_sorted_by_errors = list(np.argsort(errors)) # Top up individual target classes until we reach the desired total, # starting from the class that is furthest away from the ideal ratio. current_total = np.sum(target_numbers) while current_total < total_target_count: target_numbers[target_types_sorted_by_errors.pop()] += 1 current_total += 1 if self._shuffle_target_builders: random_state.shuffle(self._target_builders) all_targets = [] for target_type, num in enumerate(target_numbers): targets = [] target_builder = self._target_builders[target_type] for i in range(num): target = target_builder(name='target_{}_{}'.format(target_type, i)) targets.append(target) all_targets.append(targets) return all_targets def initialize_episode_mjcf(self, random_state): super( ManyHeterogeneousGoalsMaze, self).initialize_episode_mjcf(random_state) for target in itertools.chain(*self._active_targets): target.detach() target_positions = list(self._maze_arena.target_positions) random_state.shuffle(target_positions) all_targets = self._get_targets(len(target_positions), random_state) for pos, target in zip(target_positions, itertools.chain(*all_targets)): self._maze_arena.attach(target) mjcf.get_attachment_frame(target.mjcf_model).pos = pos target.initialize_episode_mjcf(random_state) self._active_targets = all_targets self._target_rewarded = [[False] * len(targets) for targets in all_targets] def get_reward(self, physics): del physics reward = self._aliveness_reward for target_type, targets in enumerate(self._active_targets): for i, target in enumerate(targets): if target.activated and not self._target_rewarded[target_type][i]: reward += self._target_type_rewards[target_type] self._target_rewarded[target_type][i] = True return reward def should_terminate_episode(self, physics): if super(ManyHeterogeneousGoalsMaze, self).should_terminate_episode(physics): return True else: for target in itertools.chain(*self._active_targets): if not target.activated: return False # All targets have been activated: successful termination. return True class ManyGoalsMaze(ManyHeterogeneousGoalsMaze): """Requires an agent to find all goals in a random maze.""" def __init__(self, walker, maze_arena, target_builder, target_reward_scale=1.0, randomize_spawn_position=True, randomize_spawn_rotation=True, rotation_bias_factor=0, aliveness_reward=0.0, aliveness_threshold=DEFAULT_ALIVE_THRESHOLD, contact_termination=True, physics_timestep=DEFAULT_PHYSICS_TIMESTEP, control_timestep=DEFAULT_CONTROL_TIMESTEP): super().__init__( walker=walker, maze_arena=maze_arena, target_builders=[target_builder], target_type_rewards=[target_reward_scale], target_type_proportions=[1], randomize_spawn_position=randomize_spawn_position, randomize_spawn_rotation=randomize_spawn_rotation, rotation_bias_factor=rotation_bias_factor, aliveness_reward=aliveness_reward, aliveness_threshold=aliveness_threshold, contact_termination=contact_termination, physics_timestep=physics_timestep, control_timestep=control_timestep) class RepeatSingleGoalMazeAugmentedWithTargets(RepeatSingleGoalMaze): """Augments the single goal maze with many lower reward targets.""" def __init__(self, walker, main_target, maze_arena, num_subtargets=20, target_reward_scale=10.0, subtarget_reward_scale=1.0, subtarget_colors=((0, 0, 0.4), (0, 0, 0.7)), randomize_spawn_position=True, randomize_spawn_rotation=True, rotation_bias_factor=0, aliveness_reward=0.0, aliveness_threshold=DEFAULT_ALIVE_THRESHOLD, contact_termination=True, physics_timestep=DEFAULT_PHYSICS_TIMESTEP, control_timestep=DEFAULT_CONTROL_TIMESTEP): super().__init__( walker=walker, target=main_target, maze_arena=maze_arena, target_reward_scale=target_reward_scale, randomize_spawn_position=randomize_spawn_position, randomize_spawn_rotation=randomize_spawn_rotation, rotation_bias_factor=rotation_bias_factor, aliveness_reward=aliveness_reward, aliveness_threshold=aliveness_threshold, contact_termination=contact_termination, physics_timestep=physics_timestep, control_timestep=control_timestep) self._subtarget_reward_scale = subtarget_reward_scale self._subtargets = [] for i in range(num_subtargets): subtarget = target_sphere.TargetSphere( radius=0.4, rgb1=subtarget_colors[0], rgb2=subtarget_colors[1], name='subtarget_{}'.format(i) ) self._subtargets.append(subtarget) self._maze_arena.attach(subtarget) self._subtarget_rewarded = None def initialize_episode_mjcf(self, random_state): super(RepeatSingleGoalMazeAugmentedWithTargets, self).initialize_episode_mjcf(random_state) subtarget_positions = self._maze_arena.target_positions for pos, subtarget in zip(subtarget_positions, self._subtargets): mjcf.get_attachment_frame(subtarget.mjcf_model).pos = pos self._subtarget_rewarded = [False] * len(self._subtargets) def get_reward(self, physics): main_reward = super(RepeatSingleGoalMazeAugmentedWithTargets, self).get_reward(physics) subtarget_reward = 0 for i, subtarget in enumerate(self._subtargets): if subtarget.activated and not self._subtarget_rewarded[i]: subtarget_reward += 1 self._subtarget_rewarded[i] = True subtarget_reward *= self._subtarget_reward_scale return main_reward + subtarget_reward def should_terminate_episode(self, physics): if super(RepeatSingleGoalMazeAugmentedWithTargets, self).should_terminate_episode(physics): return True else: for subtarget in self._subtargets: if not subtarget.activated: return False # All subtargets have been activated. return True
dm_control-main
dm_control/locomotion/tasks/random_goal_maze.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 locomotion.tasks.reach.""" import functools from absl.testing import absltest from dm_control import composer from dm_control.locomotion.arenas import floors from dm_control.locomotion.props import target_sphere from dm_control.locomotion.tasks import reach from dm_control.locomotion.walkers import rodent import numpy as np _CONTROL_TIMESTEP = .02 _PHYSICS_TIMESTEP = 0.001 class ReachTest(absltest.TestCase): def test_observables(self): walker = rodent.Rat() arena = floors.Floor( size=(10., 10.), aesthetic='outdoor_natural') 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, ) random_state = np.random.RandomState(12345) env = composer.Environment(task, random_state=random_state) timestep = env.reset() self.assertIn('walker/joints_pos', timestep.observation) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/tasks/reach_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 locomotion.tasks.random_goal_maze.""" import functools from absl.testing import absltest from dm_control import composer 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 random_goal_maze from dm_control.locomotion.walkers import cmu_humanoid import numpy as np class RandomGoalMazeTest(absltest.TestCase): def test_observables(self): walker = cmu_humanoid.CMUHumanoid() # 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, ) 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)), control_timestep=.03, physics_timestep=.005, ) random_state = np.random.RandomState(12345) env = composer.Environment(task, random_state=random_state) timestep = env.reset() self.assertIn('walker/joints_pos', timestep.observation) def test_termination_and_discount(self): walker = cmu_humanoid.CMUHumanoid() # 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, ) 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)), control_timestep=.03, physics_timestep=.005, ) random_state = np.random.RandomState(12345) env = composer.Environment(task, random_state=random_state) env.reset() zero_action = np.zeros_like(env.physics.data.ctrl) # Walker starts in upright position. # Should not trigger failure termination in the first few steps. for _ in range(5): env.step(zero_action) self.assertFalse(task.should_terminate_episode(env.physics)) np.testing.assert_array_equal(task.get_discount(env.physics), 1) # Rotate the walker upside down and run the physics until it makes contact. current_time = env.physics.data.time walker.shift_pose(env.physics, position=(0, 0, 10), quaternion=(0, 1, 0, 0)) env.physics.forward() while env.physics.data.ncon == 0: env.physics.step() env.physics.data.time = current_time # Should now trigger a failure termination. env.step(zero_action) self.assertTrue(task.should_terminate_episode(env.physics)) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/tasks/random_goal_maze_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 locomotion.tasks.go_to_target.""" from absl.testing import absltest from dm_control import composer from dm_control.locomotion.arenas import floors from dm_control.locomotion.tasks import go_to_target from dm_control.locomotion.walkers import cmu_humanoid import numpy as np class GoToTargetTest(absltest.TestCase): def test_observables(self): walker = cmu_humanoid.CMUHumanoid() arena = floors.Floor() task = go_to_target.GoToTarget( walker=walker, arena=arena, moving_target=False) random_state = np.random.RandomState(12345) env = composer.Environment(task, random_state=random_state) timestep = env.reset() self.assertIn('walker/target', timestep.observation) def test_target_position_randomized_on_reset(self): walker = cmu_humanoid.CMUHumanoid() arena = floors.Floor() task = go_to_target.GoToTarget( walker=walker, arena=arena, moving_target=False) random_state = np.random.RandomState(12345) env = composer.Environment(task, random_state=random_state) env.reset() first_target_position = task.target_position(env.physics) env.reset() second_target_position = task.target_position(env.physics) self.assertFalse(np.all(first_target_position == second_target_position), 'Target positions are unexpectedly identical.') def test_reward_fixed_target(self): walker = cmu_humanoid.CMUHumanoid() arena = floors.Floor() task = go_to_target.GoToTarget( walker=walker, arena=arena, moving_target=False) random_state = np.random.RandomState(12345) env = composer.Environment(task, random_state=random_state) env.reset() target_position = task.target_position(env.physics) zero_action = np.zeros_like(env.physics.data.ctrl) for _ in range(2): timestep = env.step(zero_action) self.assertEqual(timestep.reward, 0) walker_pos = env.physics.bind(walker.root_body).xpos walker.set_pose( env.physics, position=[target_position[0], target_position[1], walker_pos[2]]) env.physics.forward() # Receive reward while the agent remains at that location. timestep = env.step(zero_action) self.assertEqual(timestep.reward, 1) # Target position should not change. np.testing.assert_array_equal(target_position, task.target_position(env.physics)) def test_reward_moving_target(self): walker = cmu_humanoid.CMUHumanoid() arena = floors.Floor() steps_before_moving_target = 2 task = go_to_target.GoToTarget( walker=walker, arena=arena, moving_target=True, steps_before_moving_target=steps_before_moving_target) random_state = np.random.RandomState(12345) env = composer.Environment(task, random_state=random_state) env.reset() target_position = task.target_position(env.physics) zero_action = np.zeros_like(env.physics.data.ctrl) for _ in range(2): timestep = env.step(zero_action) self.assertEqual(timestep.reward, 0) walker_pos = env.physics.bind(walker.root_body).xpos walker.set_pose( env.physics, position=[target_position[0], target_position[1], walker_pos[2]]) env.physics.forward() # Receive reward while the agent remains at that location. for _ in range(steps_before_moving_target): timestep = env.step(zero_action) self.assertEqual(timestep.reward, 1) np.testing.assert_array_equal(target_position, task.target_position(env.physics)) # After taking > steps_before_moving_target, the target should move and # reward should be 0. timestep = env.step(zero_action) self.assertEqual(timestep.reward, 0) def test_termination_and_discount(self): walker = cmu_humanoid.CMUHumanoid() arena = floors.Floor() task = go_to_target.GoToTarget(walker=walker, arena=arena) random_state = np.random.RandomState(12345) env = composer.Environment(task, random_state=random_state) env.reset() zero_action = np.zeros_like(env.physics.data.ctrl) # Walker starts in upright position. # Should not trigger failure termination in the first few steps. for _ in range(5): env.step(zero_action) self.assertFalse(task.should_terminate_episode(env.physics)) np.testing.assert_array_equal(task.get_discount(env.physics), 1) # Rotate the walker upside down and run the physics until it makes contact. current_time = env.physics.data.time walker.shift_pose(env.physics, position=(0, 0, 10), quaternion=(0, 1, 0, 0)) env.physics.forward() while env.physics.data.ncon == 0: env.physics.step() env.physics.data.time = current_time # Should now trigger a failure termination. env.step(zero_action) self.assertTrue(task.should_terminate_episode(env.physics)) np.testing.assert_array_equal(task.get_discount(env.physics), 0) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/tasks/go_to_target_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. # ============================================================================ """Task for a walker to move to a target.""" from dm_control import composer from dm_control.composer import variation from dm_control.composer.observation import observable from dm_control.composer.variation import distributions import numpy as np DEFAULT_DISTANCE_TOLERANCE_TO_TARGET = 1.0 class GoToTarget(composer.Task): """A task that requires a walker to move towards a target.""" def __init__(self, walker, arena, moving_target=False, target_relative=False, target_relative_dist=1.5, steps_before_moving_target=10, distance_tolerance=DEFAULT_DISTANCE_TOLERANCE_TO_TARGET, target_spawn_position=None, walker_spawn_position=None, walker_spawn_rotation=None, physics_timestep=0.005, control_timestep=0.025): """Initializes this task. Args: walker: an instance of `locomotion.walkers.base.Walker`. arena: an instance of `locomotion.arenas.floors.Floor`. moving_target: bool, Whether the target should move after receiving the walker reaches it. target_relative: bool, Whether the target be set relative to its current position. target_relative_dist: float, new target distance range if using target_relative. steps_before_moving_target: int, the number of steps before the target moves, if moving_target==True. distance_tolerance: Accepted to distance to the target position before providing reward. target_spawn_position: a sequence of 2 numbers, or a `composer.Variation` instance that generates such sequences, specifying the position at which the target is spawned at the beginning of an episode. If None, the entire arena is used to generate random target positions. walker_spawn_position: a sequence of 2 numbers, or a `composer.Variation` instance that generates such sequences, specifying the position at which the walker is spawned at the beginning of an episode. If None, the entire arena is used to generate random spawn positions. walker_spawn_rotation: a number, or a `composer.Variation` instance that generates a number, specifying the yaw angle offset (in radians) that is applied to the walker at the beginning of an episode. physics_timestep: a number specifying the timestep (in seconds) of the physics simulation. control_timestep: a number specifying the timestep (in seconds) at which the agent applies its control inputs (in seconds). """ self._arena = arena self._walker = walker self._walker.create_root_joints(self._arena.attach(self._walker)) arena_position = distributions.Uniform( low=-np.array(arena.size) / 2, high=np.array(arena.size) / 2) if target_spawn_position is not None: self._target_spawn_position = target_spawn_position else: self._target_spawn_position = arena_position if walker_spawn_position is not None: self._walker_spawn_position = walker_spawn_position else: self._walker_spawn_position = arena_position self._walker_spawn_rotation = walker_spawn_rotation self._distance_tolerance = distance_tolerance self._moving_target = moving_target self._target_relative = target_relative self._target_relative_dist = target_relative_dist self._steps_before_moving_target = steps_before_moving_target self._reward_step_counter = 0 self._target = self.root_entity.mjcf_model.worldbody.add( 'site', name='target', type='sphere', pos=(0., 0., 0.), size=(0.1,), rgba=(0.9, 0.6, 0.6, 1.0)) enabled_observables = [] enabled_observables += self._walker.observables.proprioception enabled_observables += self._walker.observables.kinematic_sensors enabled_observables += self._walker.observables.dynamic_sensors enabled_observables.append(self._walker.observables.sensors_touch) for obs in enabled_observables: obs.enabled = True walker.observables.add_egocentric_vector( 'target', observable.MJCFFeature('pos', self._target), origin_callable=lambda physics: physics.bind(walker.root_body).xpos) self.set_timesteps( physics_timestep=physics_timestep, control_timestep=control_timestep) @property def root_entity(self): return self._arena def target_position(self, physics): return np.array(physics.bind(self._target).pos) def initialize_episode_mjcf(self, random_state): self._arena.regenerate(random_state=random_state) target_x, target_y = variation.evaluate( self._target_spawn_position, random_state=random_state) self._target.pos = [target_x, target_y, 0.] def initialize_episode(self, physics, random_state): self._walker.reinitialize_pose(physics, random_state) if self._walker_spawn_rotation: rotation = variation.evaluate( self._walker_spawn_rotation, random_state=random_state) quat = [np.cos(rotation / 2), 0, 0, np.sin(rotation / 2)] else: quat = None walker_x, walker_y = variation.evaluate( self._walker_spawn_position, random_state=random_state) self._walker.shift_pose( physics, position=[walker_x, walker_y, 0.], quaternion=quat, rotate_velocity=True) self._failure_termination = False walker_foot_geoms = set(self._walker.ground_contact_geoms) walker_nonfoot_geoms = [ geom for geom in self._walker.mjcf_model.find_all('geom') if geom not in walker_foot_geoms] self._walker_nonfoot_geomids = set( physics.bind(walker_nonfoot_geoms).element_id) self._ground_geomids = set( physics.bind(self._arena.ground_geoms).element_id) self._ground_geomids.add(physics.bind(self._target).element_id) def _is_disallowed_contact(self, contact): set1, set2 = self._walker_nonfoot_geomids, self._ground_geomids return ((contact.geom1 in set1 and contact.geom2 in set2) or (contact.geom1 in set2 and contact.geom2 in set1)) def should_terminate_episode(self, physics): return self._failure_termination def get_discount(self, physics): if self._failure_termination: return 0. else: return 1. def get_reward(self, physics): reward = 0. distance = np.linalg.norm( physics.bind(self._target).pos[:2] - physics.bind(self._walker.root_body).xpos[:2]) if distance < self._distance_tolerance: reward = 1. if self._moving_target: self._reward_step_counter += 1 return reward def before_step(self, physics, action, random_state): self._walker.apply_action(physics, action, random_state) def after_step(self, physics, random_state): self._failure_termination = False for contact in physics.data.contact: if self._is_disallowed_contact(contact): self._failure_termination = True break if (self._moving_target and self._reward_step_counter >= self._steps_before_moving_target): # Reset the target position. if self._target_relative: walker_pos = physics.bind(self._walker.root_body).xpos[:2] target_x, target_y = random_state.uniform( -np.array([self._target_relative_dist, self._target_relative_dist]), np.array([self._target_relative_dist, self._target_relative_dist])) target_x += walker_pos[0] target_y += walker_pos[1] else: target_x, target_y = variation.evaluate( self._target_spawn_position, random_state=random_state) physics.bind(self._target).pos = [target_x, target_y, 0.] # Reset the number of steps at the target for the moving target. self._reward_step_counter = 0
dm_control-main
dm_control/locomotion/tasks/go_to_target.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. # ============================================================================ """Tasks in the Locomotion library.""" from dm_control.locomotion.tasks.corridors import RunThroughCorridor from dm_control.locomotion.tasks.escape import Escape # Import1 removed. # Import2 removed. from dm_control.locomotion.tasks.go_to_target import GoToTarget from dm_control.locomotion.tasks.random_goal_maze import ManyGoalsMaze from dm_control.locomotion.tasks.random_goal_maze import ManyHeterogeneousGoalsMaze from dm_control.locomotion.tasks.random_goal_maze import RepeatSingleGoalMaze from dm_control.locomotion.tasks.random_goal_maze import RepeatSingleGoalMazeAugmentedWithTargets from dm_control.locomotion.tasks.reach import TwoTouch
dm_control-main
dm_control/locomotion/tasks/__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. # ============================================================================ """Corridor-based locomotion tasks.""" from dm_control import composer from dm_control.composer import variation from dm_control.utils import rewards import numpy as np class RunThroughCorridor(composer.Task): """A task that requires a walker to run through a corridor. This task rewards an agent for controlling a walker to move at a specific target velocity along the corridor, and for minimising the magnitude of the control signals used to achieve this. """ def __init__(self, walker, arena, walker_spawn_position=(0, 0, 0), walker_spawn_rotation=None, target_velocity=3.0, contact_termination=True, terminate_at_height=-0.5, physics_timestep=0.005, control_timestep=0.025): """Initializes this task. Args: walker: an instance of `locomotion.walkers.base.Walker`. arena: an instance of `locomotion.arenas.corridors.Corridor`. walker_spawn_position: a sequence of 3 numbers, or a `composer.Variation` instance that generates such sequences, specifying the position at which the walker is spawned at the beginning of an episode. walker_spawn_rotation: a number, or a `composer.Variation` instance that generates a number, specifying the yaw angle offset (in radians) that is applied to the walker at the beginning of an episode. target_velocity: a number specifying the target velocity (in meters per second) for the walker. contact_termination: whether to terminate if a non-foot geom touches the ground. terminate_at_height: a number specifying the height of end effectors below which the episode terminates. physics_timestep: a number specifying the timestep (in seconds) of the physics simulation. control_timestep: a number specifying the timestep (in seconds) at which the agent applies its control inputs (in seconds). """ self._arena = arena self._walker = walker self._walker.create_root_joints(self._arena.attach(self._walker)) self._walker_spawn_position = walker_spawn_position self._walker_spawn_rotation = walker_spawn_rotation enabled_observables = [] enabled_observables += self._walker.observables.proprioception enabled_observables += self._walker.observables.kinematic_sensors enabled_observables += self._walker.observables.dynamic_sensors enabled_observables.append(self._walker.observables.sensors_touch) enabled_observables.append(self._walker.observables.egocentric_camera) for observable in enabled_observables: observable.enabled = True self._vel = target_velocity self._contact_termination = contact_termination self._terminate_at_height = terminate_at_height self.set_timesteps( physics_timestep=physics_timestep, control_timestep=control_timestep) @property def root_entity(self): return self._arena def initialize_episode_mjcf(self, random_state): self._arena.regenerate(random_state) self._arena.mjcf_model.visual.map.znear = 0.00025 self._arena.mjcf_model.visual.map.zfar = 4. def initialize_episode(self, physics, random_state): self._walker.reinitialize_pose(physics, random_state) if self._walker_spawn_rotation: rotation = variation.evaluate( self._walker_spawn_rotation, random_state=random_state) quat = [np.cos(rotation / 2), 0, 0, np.sin(rotation / 2)] else: quat = None self._walker.shift_pose( physics, position=variation.evaluate( self._walker_spawn_position, random_state=random_state), quaternion=quat, rotate_velocity=True) self._failure_termination = False walker_foot_geoms = set(self._walker.ground_contact_geoms) walker_nonfoot_geoms = [ geom for geom in self._walker.mjcf_model.find_all('geom') if geom not in walker_foot_geoms] self._walker_nonfoot_geomids = set( physics.bind(walker_nonfoot_geoms).element_id) self._ground_geomids = set( physics.bind(self._arena.ground_geoms).element_id) def _is_disallowed_contact(self, contact): set1, set2 = self._walker_nonfoot_geomids, self._ground_geomids return ((contact.geom1 in set1 and contact.geom2 in set2) or (contact.geom1 in set2 and contact.geom2 in set1)) def before_step(self, physics, action, random_state): self._walker.apply_action(physics, action, random_state) def after_step(self, physics, random_state): self._failure_termination = False if self._contact_termination: for c in physics.data.contact: if self._is_disallowed_contact(c): self._failure_termination = True break if self._terminate_at_height is not None: if any(physics.bind(self._walker.end_effectors).xpos[:, -1] < self._terminate_at_height): self._failure_termination = True def get_reward(self, physics): walker_xvel = physics.bind(self._walker.root_body).subtree_linvel[0] xvel_term = rewards.tolerance( walker_xvel, (self._vel, self._vel), margin=self._vel, sigmoid='linear', value_at_margin=0.0) return xvel_term def should_terminate_episode(self, physics): return self._failure_termination def get_discount(self, physics): if self._failure_termination: return 0. else: return 1.
dm_control-main
dm_control/locomotion/tasks/corridors.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 locomotion.tasks.escape.""" from absl.testing import absltest from dm_control import composer from dm_control.locomotion.arenas import bowl from dm_control.locomotion.tasks import escape from dm_control.locomotion.walkers import rodent import numpy as np _CONTROL_TIMESTEP = .02 _PHYSICS_TIMESTEP = 0.001 class EscapeTest(absltest.TestCase): def test_observables(self): walker = rodent.Rat() # Build a corridor-shaped arena that is obstructed by walls. arena = bowl.Bowl( size=(20., 20.), aesthetic='outdoor_natural') # Build a task that rewards the agent for running down the corridor at a # specific velocity. task = escape.Escape( walker=walker, arena=arena, physics_timestep=_PHYSICS_TIMESTEP, control_timestep=_CONTROL_TIMESTEP) random_state = np.random.RandomState(12345) env = composer.Environment(task, random_state=random_state) timestep = env.reset() self.assertIn('walker/joints_pos', timestep.observation) def test_contact(self): walker = rodent.Rat() # Build a corridor-shaped arena that is obstructed by walls. arena = bowl.Bowl( size=(20., 20.), aesthetic='outdoor_natural') # Build a task that rewards the agent for running down the corridor at a # specific velocity. task = escape.Escape( walker=walker, arena=arena, physics_timestep=_PHYSICS_TIMESTEP, control_timestep=_CONTROL_TIMESTEP) random_state = np.random.RandomState(12345) env = composer.Environment(task, random_state=random_state) env.reset() zero_action = np.zeros_like(env.physics.data.ctrl) # Walker starts in upright position. # Should not trigger failure termination in the first few steps. for _ in range(5): env.step(zero_action) self.assertFalse(task.should_terminate_episode(env.physics)) np.testing.assert_array_equal(task.get_discount(env.physics), 1) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/tasks/escape_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. # ============================================================================ """Simple script to visualize motion capture data.""" from absl import app from dm_control import composer from dm_control import viewer from dm_control.locomotion import arenas from dm_control.locomotion import walkers from dm_control.locomotion.mocap import cmu_mocap_data from dm_control.locomotion.tasks.reference_pose import tracking def mocap_playback_env(random_state=None): """Constructs mocap playback environment.""" # Use a position-controlled CMU humanoid walker. walker_type = walkers.CMUHumanoidPositionControlledV2020 # Build an empty arena. arena = arenas.Floor() # Build a task that rewards the agent for tracking motion capture reference # data. task = tracking.PlaybackTask( walker=walker_type, arena=arena, ref_path=cmu_mocap_data.get_path_for_cmu(version='2020'), dataset='run_jump_tiny', ) return composer.Environment(time_limit=30, task=task, random_state=random_state, strip_singleton_obs_buffer_dim=True) def main(unused_argv): # The viewer calls the environment_loader on episode resets. However the task # cycles through one clip per episode. To avoid replaying the first clip again # and again we construct the environment outside the viewer to make it # persistent across resets. env = mocap_playback_env() viewer.launch(environment_loader=lambda: env) if __name__ == '__main__': app.run(main)
dm_control-main
dm_control/locomotion/tasks/reference_pose/mocap_playback.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. # ============================================================================ """Datasets for reference pose tasks. """ from dm_control.locomotion.tasks.reference_pose import cmu_subsets DATASETS = dict() DATASETS.update(cmu_subsets.CMU_SUBSETS_DICT)
dm_control-main
dm_control/locomotion/tasks/reference_pose/datasets.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. # ============================================================================ """Reference pose tasks in the Locomotion library."""
dm_control-main
dm_control/locomotion/tasks/reference_pose/__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. # ============================================================================ """Types for reference pose tasks. """ from typing import Optional, Sequence, Text, Union import numpy as np class ClipCollection: """Dataclass representing a collection of mocap reference clips.""" def __init__(self, ids: Sequence[Text], start_steps: Optional[Sequence[int]] = None, end_steps: Optional[Sequence[int]] = None, weights: Optional[Sequence[Union[int, float]]] = None): """Instantiate a ClipCollection.""" self.ids = ids self.start_steps = start_steps self.end_steps = end_steps self.weights = weights num_clips = len(self.ids) try: if self.start_steps is None: # by default start at the beginning self.start_steps = (0,) * num_clips else: assert len(self.start_steps) == num_clips # without access to the actual clip we cannot specify an end_steps default if self.end_steps is not None: assert len(self.end_steps) == num_clips if self.weights is None: self.weights = (1.0,) * num_clips else: assert len(self.weights) == num_clips assert np.all(np.array(self.weights) >= 0.) except AssertionError as e: raise ValueError("ClipCollection validation failed. {}".format(e))
dm_control-main
dm_control/locomotion/tasks/reference_pose/types.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. # ============================================================================ """Utils for reference pose tasks.""" from dm_control import mjcf from dm_control.utils import transformations as tr import numpy as np def add_walker(walker_fn, arena, name='walker', ghost=False, visible=True, position=(0, 0, 0)): """Create a walker.""" walker = walker_fn(name=name) if ghost: # if the walker has a built-in tracking light remove it. light = walker.mjcf_model.find('light', 'tracking_light') if light: light.remove() # Remove the contacts. for geom in walker.mjcf_model.find_all('geom'): # alpha=0.999 ensures grey ghost reference. # for alpha=1.0 there is no visible difference between real walker and # ghost reference. alpha = 0.999 if geom.rgba is not None and geom.rgba[3] < alpha: alpha = geom.rgba[3] geom.set_attributes( contype=0, conaffinity=0, rgba=(0.5, 0.5, 0.5, alpha if visible else 0.0)) # We don't want ghost actuators to be controllable, so remove them. model = walker.mjcf_model elems = model.find_all('actuator') sensors = [x for x in model.find_all('sensor') if 'actuator' in x.tag] elems += sensors for elem in elems: elem.remove() skin = walker.mjcf_model.find('skin', 'skin') if skin: if visible: skin.set_attributes(rgba=(0.5, 0.5, 0.5, 0.999)) else: skin.set_attributes(rgba=(0.5, 0.5, 0.5, 0.)) if position == (0, 0, 0): walker.create_root_joints(arena.attach(walker)) else: spawn_site = arena.mjcf_model.worldbody.add('site', pos=position) walker.create_root_joints(arena.attach(walker, spawn_site)) spawn_site.remove() return walker def get_qpos_qvel_from_features(features): """Get qpos and qvel from logged features to set walker.""" full_qpos = np.hstack([ features['position'], features['quaternion'], features['joints'], ]) full_qvel = np.hstack([ features['velocity'], features['angular_velocity'], features['joints_velocity'], ]) return full_qpos, full_qvel def set_walker_from_features(physics, walker, features, offset=0): """Set the freejoint and walker's joints angles and velocities.""" qpos, qvel = get_qpos_qvel_from_features(features) set_walker(physics, walker, qpos, qvel, offset=offset) def set_walker(physics, walker, qpos, qvel, offset=0, null_xyz_and_yaw=False, position_shift=None, rotation_shift=None): """Set the freejoint and walker's joints angles and velocities.""" qpos = np.array(qpos) if null_xyz_and_yaw: qpos[:2] = 0. euler = tr.quat_to_euler(qpos[3:7], ordering='ZYX') euler[0] = 0. quat = tr.euler_to_quat(euler, ordering='ZYX') qpos[3:7] = quat qpos[:3] += offset freejoint = mjcf.get_attachment_frame(walker.mjcf_model).freejoint physics.bind(freejoint).qpos = qpos[:7] physics.bind(freejoint).qvel = qvel[:6] physics.bind(walker.mocap_joints).qpos = qpos[7:] physics.bind(walker.mocap_joints).qvel = qvel[6:] if position_shift is not None or rotation_shift is not None: walker.shift_pose(physics, position=position_shift, quaternion=rotation_shift, rotate_velocity=True) def set_props_from_features(physics, props, features, z_offset=0): positions = features['prop_positions'] quaternions = features['prop_quaternions'] if np.isscalar(z_offset): z_offset = np.array([0., 0., z_offset]) for prop, pos, quat in zip(props, positions, quaternions): prop.set_pose(physics, pos + z_offset, quat) def get_features(physics, walker, props=None): """Get walker features for reward functions.""" walker_bodies = walker.mocap_tracking_bodies walker_features = {} root_pos, root_quat = walker.get_pose(physics) walker_features['position'] = np.array(root_pos) walker_features['quaternion'] = np.array(root_quat) joints = np.array(physics.bind(walker.mocap_joints).qpos) walker_features['joints'] = joints freejoint_frame = mjcf.get_attachment_frame(walker.mjcf_model) com = np.array(physics.bind(freejoint_frame).subtree_com) walker_features['center_of_mass'] = com end_effectors = np.array( walker.observables.end_effectors_pos(physics)[:]).reshape(-1, 3) walker_features['end_effectors'] = end_effectors if hasattr(walker.observables, 'appendages_pos'): appendages = np.array( walker.observables.appendages_pos(physics)[:]).reshape(-1, 3) else: appendages = np.array(end_effectors) walker_features['appendages'] = appendages xpos = np.array(physics.bind(walker_bodies).xpos) walker_features['body_positions'] = xpos xquat = np.array(physics.bind(walker_bodies).xquat) walker_features['body_quaternions'] = xquat root_vel, root_angvel = walker.get_velocity(physics) walker_features['velocity'] = np.array(root_vel) walker_features['angular_velocity'] = np.array(root_angvel) joints_vel = np.array(physics.bind(walker.mocap_joints).qvel) walker_features['joints_velocity'] = joints_vel if props: positions = [] quaternions = [] for prop in props: pos, quat = prop.get_pose(physics) positions.append(pos) quaternions.append(quat) walker_features['prop_positions'] = np.array(positions) walker_features['prop_quaternions'] = np.array(quaternions) return walker_features
dm_control-main
dm_control/locomotion/tasks/reference_pose/utils.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. # ============================================================================ """Define reward function options for reference pose tasks.""" import collections import numpy as np RewardFnOutput = collections.namedtuple('RewardFnOutput', ['reward', 'debug', 'reward_terms']) def bounded_quat_dist(source: np.ndarray, target: np.ndarray) -> np.ndarray: """Computes a quaternion distance limiting the difference to a max of pi/2. This function supports an arbitrary number of batch dimensions, B. Args: source: a quaternion, shape (B, 4). target: another quaternion, shape (B, 4). Returns: Quaternion distance, shape (B, 1). """ source /= np.linalg.norm(source, axis=-1, keepdims=True) target /= np.linalg.norm(target, axis=-1, keepdims=True) # "Distance" in interval [-1, 1]. dist = 2 * np.einsum('...i,...i', source, target) ** 2 - 1 # Clip at 1 to avoid occasional machine epsilon leak beyond 1. dist = np.minimum(1., dist) # Divide by 2 and add an axis to ensure consistency with expected return # shape and magnitude. return 0.5 * np.arccos(dist)[..., np.newaxis] def sort_dict(d): return collections.OrderedDict(sorted(d.items())) def compute_squared_differences(walker_features, reference_features, exclude_keys=()): """Computes squared differences of features.""" squared_differences = {} for k in walker_features: if k not in exclude_keys: if 'quaternion' not in k: squared_differences[k] = np.sum( (walker_features[k] - reference_features[k])**2) elif 'quaternions' in k: quat_dists = bounded_quat_dist( walker_features[k], reference_features[k]) squared_differences[k] = np.sum(quat_dists**2) else: squared_differences[k] = bounded_quat_dist( walker_features[k], reference_features[k])**2 return squared_differences def termination_reward_fn(termination_error, termination_error_threshold, **unused_kwargs): """Termination error. This reward is intended to be used in conjunction with the termination error calculated in the task. Due to terminations if error > error_threshold this reward will be in [0, 1]. Args: termination_error: termination error computed in tracking task termination_error_threshold: task termination threshold unused_kwargs: unused_kwargs Returns: RewardFnOutput tuple containing reward, debug information and reward terms. """ debug_terms = { 'termination_error': termination_error, 'termination_error_threshold': termination_error_threshold } termination_reward = 1 - termination_error / termination_error_threshold return RewardFnOutput(reward=termination_reward, debug=debug_terms, reward_terms=sort_dict( {'termination': termination_reward})) def debug(reference_features, walker_features, **unused_kwargs): debug_terms = compute_squared_differences(walker_features, reference_features) return RewardFnOutput(reward=0.0, debug=debug_terms, reward_terms=None) def multi_term_pose_reward_fn(walker_features, reference_features, **unused_kwargs): """A reward based on com, body quaternions, joints velocities & appendages.""" differences = compute_squared_differences(walker_features, reference_features) com = .1 * np.exp(-10 * differences['center_of_mass']) joints_velocity = 1.0 * np.exp(-0.1 * differences['joints_velocity']) appendages = 0.15 * np.exp(-40. * differences['appendages']) body_quaternions = 0.65 * np.exp(-2 * differences['body_quaternions']) terms = { 'center_of_mass': com, 'joints_velocity': joints_velocity, 'appendages': appendages, 'body_quaternions': body_quaternions } reward = sum(terms.values()) return RewardFnOutput(reward=reward, debug=terms, reward_terms=sort_dict(terms)) def comic_reward_fn(termination_error, termination_error_threshold, walker_features, reference_features, **unused_kwargs): """A reward that mixes the termination_reward and multi_term_pose_reward. This reward function was used in Hasenclever et al., CoMic: Complementary Task Learning & Mimicry for Reusable Skills, International Conference on Machine Learning, 2020. [https://proceedings.icml.cc/static/paper_files/icml/2020/5013-Paper.pdf] Args: termination_error: termination error as described termination_error_threshold: threshold to determine whether to terminate episodes. The threshold is used to construct a reward between [0, 1] based on the termination error. walker_features: Current features of the walker reference_features: features of the current reference pose unused_kwargs: unused addtional keyword arguments. Returns: RewardFnOutput tuple containing reward, debug terms and reward terms. """ termination_reward, debug_terms, termination_reward_terms = ( termination_reward_fn(termination_error, termination_error_threshold)) mt_reward, mt_debug_terms, mt_reward_terms = multi_term_pose_reward_fn( walker_features, reference_features) debug_terms.update(mt_debug_terms) reward_terms = {k: 0.5 * v for k, v in termination_reward_terms.items()} reward_terms.update( {k: 0.5 * v for k, v in mt_reward_terms.items()}) return RewardFnOutput( reward=0.5 * termination_reward + 0.5 * mt_reward, debug=debug_terms, reward_terms=sort_dict(reward_terms)) _REWARD_FN = { 'termination_reward': termination_reward_fn, 'multi_term_pose_reward': multi_term_pose_reward_fn, 'comic': comic_reward_fn, } _REWARD_CHANNELS = { 'termination_reward': ('termination',), 'multi_term_pose_reward': ('appendages', 'body_quaternions', 'center_of_mass', 'joints_velocity'), 'comic': ('appendages', 'body_quaternions', 'center_of_mass', 'termination', 'joints_velocity'), } def get_reward(reward_key): if reward_key not in _REWARD_FN: raise ValueError('Requested loss %s, which is not a valid option.' % reward_key) return _REWARD_FN[reward_key] def get_reward_channels(reward_key): if reward_key not in _REWARD_CHANNELS: raise ValueError('Requested loss %s, which is not a valid option.' % reward_key) return _REWARD_CHANNELS[reward_key]
dm_control-main
dm_control/locomotion/tasks/reference_pose/rewards.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. # ============================================================================ """Tests for dm_control.locomotion.tasks.reference_pose.rewards.""" from absl.testing import absltest from dm_control.locomotion.tasks.reference_pose import rewards import numpy as np WALKER_FEATURES = { 'scalar': 0., 'vector': np.ones(3), 'match': 0.1, } REFERENCE_FEATURES = { 'scalar': 1.5, 'vector': np.full(3, 2), 'match': 0.1, } QUATERNION_FEATURES = { 'unmatched_quaternion': (1., 0., 0., 0.), 'matched_quaternions': [(1., 0., 1., 0.), (0.707, 0.707, 0., 0.)], } REFERENCE_QUATERNION_FEATURES = { 'unmatched_quaternion': (0., 0., 0., 1.), 'matched_quaternions': [(1., 0., 1., 0.), (0.707, 0.707, 0., 0.)], } EXPECTED_DIFFERENCES = { 'scalar': 2.25, 'vector': 3., 'match': 0., 'unmatched_quaternion': np.sum(rewards.bounded_quat_dist( QUATERNION_FEATURES['unmatched_quaternion'], REFERENCE_QUATERNION_FEATURES['unmatched_quaternion']))**2, 'matched_quaternions': 0., } EXCLUDE_KEYS = ('scalar', 'match') class RewardsTest(absltest.TestCase): def test_compute_squared_differences(self): """Basic usage.""" differences = rewards.compute_squared_differences( WALKER_FEATURES, REFERENCE_FEATURES) for key, difference in differences.items(): self.assertEqual(difference, EXPECTED_DIFFERENCES[key]) def test_compute_squared_differences_exclude_keys(self): """Test excluding some keys from squared difference computation.""" differences = rewards.compute_squared_differences( WALKER_FEATURES, REFERENCE_FEATURES, exclude_keys=EXCLUDE_KEYS) for key in EXCLUDE_KEYS: self.assertNotIn(key, differences) def test_compute_squared_differences_quaternion(self): """Test that quaternions use a different distance computation.""" differences = rewards.compute_squared_differences( QUATERNION_FEATURES, REFERENCE_QUATERNION_FEATURES) for key, difference in differences.items(): self.assertAlmostEqual(difference, EXPECTED_DIFFERENCES[key]) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/tasks/reference_pose/rewards_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. # ============================================================================ """Subsets of the CMU mocap database.""" from dm_control.locomotion.tasks.reference_pose import types ClipCollection = types.ClipCollection # get up GET_UP = ClipCollection( ids=('CMU_139_16', 'CMU_139_17', 'CMU_139_18', 'CMU_140_01', 'CMU_140_02', 'CMU_140_08', 'CMU_140_09') ) # Subset of about 40 minutes of varied locomotion behaviors. LOCOMOTION_SMALL = ClipCollection( ids=('CMU_001_01', 'CMU_002_03', 'CMU_002_04', 'CMU_009_01', 'CMU_009_02', 'CMU_009_03', 'CMU_009_04', 'CMU_009_05', 'CMU_009_06', 'CMU_009_07', 'CMU_009_08', 'CMU_009_09', 'CMU_009_10', 'CMU_009_11', 'CMU_013_11', 'CMU_013_13', 'CMU_013_19', 'CMU_013_32', 'CMU_013_39', 'CMU_013_40', 'CMU_013_41', 'CMU_013_42', 'CMU_014_07', 'CMU_014_08', 'CMU_014_09', 'CMU_016_01', 'CMU_016_02', 'CMU_016_03', 'CMU_016_04', 'CMU_016_05', 'CMU_016_06', 'CMU_016_07', 'CMU_016_08', 'CMU_016_09', 'CMU_016_10', 'CMU_016_17', 'CMU_016_18', 'CMU_016_19', 'CMU_016_20', 'CMU_016_27', 'CMU_016_28', 'CMU_016_29', 'CMU_016_30', 'CMU_016_35', 'CMU_016_36', 'CMU_016_37', 'CMU_016_38', 'CMU_016_39', 'CMU_016_40', 'CMU_016_41', 'CMU_016_42', 'CMU_016_43', 'CMU_016_44', 'CMU_016_45', 'CMU_016_46', 'CMU_016_48', 'CMU_016_49', 'CMU_016_50', 'CMU_016_51', 'CMU_016_52', 'CMU_016_53', 'CMU_016_54', 'CMU_016_55', 'CMU_016_56', 'CMU_016_57', 'CMU_035_17', 'CMU_035_18', 'CMU_035_19', 'CMU_035_20', 'CMU_035_21', 'CMU_035_22', 'CMU_035_23', 'CMU_035_24', 'CMU_035_25', 'CMU_035_26', 'CMU_036_02', 'CMU_036_03', 'CMU_036_09', 'CMU_038_03', 'CMU_038_04', 'CMU_039_11', 'CMU_047_01', 'CMU_049_02', 'CMU_049_03', 'CMU_049_04', 'CMU_049_05', 'CMU_069_06', 'CMU_069_07', 'CMU_069_08', 'CMU_069_09', 'CMU_069_10', 'CMU_069_11', 'CMU_069_12', 'CMU_069_13', 'CMU_069_14', 'CMU_069_15', 'CMU_069_16', 'CMU_069_17', 'CMU_069_18', 'CMU_069_19', 'CMU_069_20', 'CMU_069_21', 'CMU_069_22', 'CMU_069_23', 'CMU_069_24', 'CMU_069_25', 'CMU_069_26', 'CMU_069_27', 'CMU_069_28', 'CMU_069_29', 'CMU_069_30', 'CMU_069_31', 'CMU_069_32', 'CMU_069_33', 'CMU_069_42', 'CMU_069_43', 'CMU_069_44', 'CMU_069_45', 'CMU_069_46', 'CMU_069_47', 'CMU_069_48', 'CMU_069_49', 'CMU_069_56', 'CMU_069_57', 'CMU_069_58', 'CMU_069_59', 'CMU_069_60', 'CMU_069_61', 'CMU_069_62', 'CMU_069_63', 'CMU_069_64', 'CMU_069_65', 'CMU_069_66', 'CMU_069_67', 'CMU_075_01', 'CMU_075_02', 'CMU_075_03', 'CMU_075_04', 'CMU_075_05', 'CMU_075_06', 'CMU_075_07', 'CMU_075_08', 'CMU_075_09', 'CMU_075_10', 'CMU_075_11', 'CMU_075_12', 'CMU_075_13', 'CMU_075_14', 'CMU_075_15', 'CMU_076_10', 'CMU_077_10', 'CMU_077_11', 'CMU_077_12', 'CMU_077_13', 'CMU_078_01', 'CMU_078_02', 'CMU_078_03', 'CMU_078_07', 'CMU_078_09', 'CMU_078_10', 'CMU_082_15', 'CMU_083_36', 'CMU_083_37', 'CMU_083_38', 'CMU_083_39', 'CMU_083_40', 'CMU_083_41', 'CMU_083_42', 'CMU_083_43', 'CMU_083_45', 'CMU_083_46', 'CMU_083_48', 'CMU_083_49', 'CMU_083_51', 'CMU_083_52', 'CMU_083_53', 'CMU_083_54', 'CMU_083_56', 'CMU_083_57', 'CMU_083_58', 'CMU_083_59', 'CMU_083_60', 'CMU_083_61', 'CMU_083_62', 'CMU_083_64', 'CMU_083_65', 'CMU_086_01', 'CMU_086_11', 'CMU_090_06', 'CMU_090_07', 'CMU_091_39', 'CMU_091_40', 'CMU_091_41', 'CMU_091_42', 'CMU_091_43', 'CMU_091_44', 'CMU_091_45', 'CMU_091_46', 'CMU_091_47', 'CMU_091_48', 'CMU_091_49', 'CMU_091_50', 'CMU_091_51', 'CMU_091_52', 'CMU_091_53', 'CMU_104_53', 'CMU_104_54', 'CMU_104_55', 'CMU_104_56', 'CMU_104_57', 'CMU_105_39', 'CMU_105_40', 'CMU_105_41', 'CMU_105_42', 'CMU_105_43', 'CMU_105_44', 'CMU_105_45', 'CMU_105_46', 'CMU_105_47', 'CMU_105_48', 'CMU_105_49', 'CMU_105_50', 'CMU_105_51', 'CMU_105_52', 'CMU_118_01', 'CMU_118_02', 'CMU_118_03', 'CMU_118_04', 'CMU_118_05', 'CMU_118_06', 'CMU_118_07', 'CMU_118_08', 'CMU_118_09', 'CMU_118_10', 'CMU_118_11', 'CMU_118_12', 'CMU_118_13', 'CMU_118_14', 'CMU_118_15', 'CMU_118_16', 'CMU_118_17', 'CMU_118_18', 'CMU_118_19', 'CMU_118_20', 'CMU_118_21', 'CMU_118_22', 'CMU_118_23', 'CMU_118_24', 'CMU_118_25', 'CMU_118_26', 'CMU_118_27', 'CMU_118_28', 'CMU_118_29', 'CMU_118_30', 'CMU_127_03', 'CMU_127_04', 'CMU_127_05', 'CMU_127_06', 'CMU_127_07', 'CMU_127_08', 'CMU_127_09', 'CMU_127_10', 'CMU_127_11', 'CMU_127_12', 'CMU_127_13', 'CMU_127_14', 'CMU_127_15', 'CMU_127_16', 'CMU_127_17', 'CMU_127_18', 'CMU_127_19', 'CMU_127_20', 'CMU_127_21', 'CMU_127_22', 'CMU_127_23', 'CMU_127_24', 'CMU_127_25', 'CMU_127_26', 'CMU_127_27', 'CMU_127_28', 'CMU_127_29', 'CMU_127_30', 'CMU_127_31', 'CMU_127_32', 'CMU_127_37', 'CMU_127_38', 'CMU_128_02', 'CMU_128_03', 'CMU_128_04', 'CMU_128_05', 'CMU_128_06', 'CMU_128_07', 'CMU_128_08', 'CMU_128_09', 'CMU_128_10', 'CMU_128_11', 'CMU_132_23', 'CMU_132_24', 'CMU_132_25', 'CMU_132_26', 'CMU_132_27', 'CMU_132_28', 'CMU_139_10', 'CMU_139_11', 'CMU_139_12', 'CMU_139_13', 'CMU_143_01', 'CMU_143_02', 'CMU_143_03', 'CMU_143_04', 'CMU_143_05', 'CMU_143_06', 'CMU_143_07', 'CMU_143_08', 'CMU_143_09', 'CMU_143_42')) # Subset of about 2 minutes of walking behaviors. WALK_TINY = ClipCollection( ids=('CMU_016_22', 'CMU_016_23', 'CMU_016_24', 'CMU_016_25', 'CMU_016_26', 'CMU_016_27', 'CMU_016_28', 'CMU_016_29', 'CMU_016_30', 'CMU_016_31', 'CMU_016_32', 'CMU_016_33', 'CMU_016_34', 'CMU_016_47', 'CMU_016_58', 'CMU_047_01', 'CMU_056_01', 'CMU_069_01', 'CMU_069_02', 'CMU_069_03', 'CMU_069_04', 'CMU_069_05', 'CMU_069_20', 'CMU_069_21', 'CMU_069_22', 'CMU_069_23', 'CMU_069_24', 'CMU_069_25', 'CMU_069_26', 'CMU_069_27', 'CMU_069_28', 'CMU_069_29', 'CMU_069_30', 'CMU_069_31', 'CMU_069_32', 'CMU_069_33')) # Subset of about 2 minutes of walking/running/jumping behaviors. RUN_JUMP_TINY = ClipCollection( ids=('CMU_009_01', 'CMU_009_02', 'CMU_009_03', 'CMU_009_04', 'CMU_009_05', 'CMU_009_06', 'CMU_009_07', 'CMU_009_08', 'CMU_009_09', 'CMU_009_10', 'CMU_009_11', 'CMU_016_22', 'CMU_016_23', 'CMU_016_24', 'CMU_016_25', 'CMU_016_26', 'CMU_016_27', 'CMU_016_28', 'CMU_016_29', 'CMU_016_30', 'CMU_016_31', 'CMU_016_32', 'CMU_016_47', 'CMU_016_48', 'CMU_016_49', 'CMU_016_50', 'CMU_016_55', 'CMU_016_58', 'CMU_049_04', 'CMU_049_05', 'CMU_069_01', 'CMU_069_02', 'CMU_069_03', 'CMU_069_04', 'CMU_069_05', 'CMU_075_01', 'CMU_075_02', 'CMU_075_03', 'CMU_075_10', 'CMU_075_11', 'CMU_127_03', 'CMU_127_06', 'CMU_127_07', 'CMU_127_08', 'CMU_127_09', 'CMU_127_10', 'CMU_127_11', 'CMU_127_12', 'CMU_128_02', 'CMU_128_03')) # Subset of about 3.5 hours of varied locomotion behaviors and hand movements. ALL = ClipCollection( ids=('CMU_001_01', 'CMU_002_01', 'CMU_002_02', 'CMU_002_03', 'CMU_002_04', 'CMU_005_01', 'CMU_006_01', 'CMU_006_02', 'CMU_006_03', 'CMU_006_04', 'CMU_006_05', 'CMU_006_06', 'CMU_006_07', 'CMU_006_08', 'CMU_006_09', 'CMU_006_10', 'CMU_006_11', 'CMU_006_12', 'CMU_006_13', 'CMU_006_14', 'CMU_006_15', 'CMU_007_01', 'CMU_007_02', 'CMU_007_03', 'CMU_007_04', 'CMU_007_05', 'CMU_007_06', 'CMU_007_07', 'CMU_007_08', 'CMU_007_09', 'CMU_007_10', 'CMU_007_11', 'CMU_007_12', 'CMU_008_01', 'CMU_008_02', 'CMU_008_03', 'CMU_008_04', 'CMU_008_05', 'CMU_008_06', 'CMU_008_07', 'CMU_008_08', 'CMU_008_09', 'CMU_008_10', 'CMU_008_11', 'CMU_009_01', 'CMU_009_02', 'CMU_009_03', 'CMU_009_04', 'CMU_009_05', 'CMU_009_06', 'CMU_009_07', 'CMU_009_08', 'CMU_009_09', 'CMU_009_10', 'CMU_009_11', 'CMU_009_12', 'CMU_010_04', 'CMU_013_11', 'CMU_013_13', 'CMU_013_19', 'CMU_013_26', 'CMU_013_27', 'CMU_013_28', 'CMU_013_29', 'CMU_013_30', 'CMU_013_31', 'CMU_013_32', 'CMU_013_39', 'CMU_013_40', 'CMU_013_41', 'CMU_013_42', 'CMU_014_06', 'CMU_014_07', 'CMU_014_08', 'CMU_014_09', 'CMU_014_14', 'CMU_014_20', 'CMU_014_24', 'CMU_014_25', 'CMU_014_26', 'CMU_015_01', 'CMU_015_03', 'CMU_015_04', 'CMU_015_05', 'CMU_015_06', 'CMU_015_07', 'CMU_015_08', 'CMU_015_09', 'CMU_015_12', 'CMU_015_14', 'CMU_016_01', 'CMU_016_02', 'CMU_016_03', 'CMU_016_04', 'CMU_016_05', 'CMU_016_06', 'CMU_016_07', 'CMU_016_08', 'CMU_016_09', 'CMU_016_10', 'CMU_016_11', 'CMU_016_12', 'CMU_016_13', 'CMU_016_14', 'CMU_016_15', 'CMU_016_16', 'CMU_016_17', 'CMU_016_18', 'CMU_016_19', 'CMU_016_20', 'CMU_016_21', 'CMU_016_22', 'CMU_016_23', 'CMU_016_24', 'CMU_016_25', 'CMU_016_26', 'CMU_016_27', 'CMU_016_28', 'CMU_016_29', 'CMU_016_30', 'CMU_016_31', 'CMU_016_32', 'CMU_016_33', 'CMU_016_34', 'CMU_016_35', 'CMU_016_36', 'CMU_016_37', 'CMU_016_38', 'CMU_016_39', 'CMU_016_40', 'CMU_016_41', 'CMU_016_42', 'CMU_016_43', 'CMU_016_44', 'CMU_016_45', 'CMU_016_46', 'CMU_016_47', 'CMU_016_48', 'CMU_016_49', 'CMU_016_50', 'CMU_016_51', 'CMU_016_52', 'CMU_016_53', 'CMU_016_54', 'CMU_016_55', 'CMU_016_56', 'CMU_016_57', 'CMU_016_58', 'CMU_017_01', 'CMU_017_02', 'CMU_017_03', 'CMU_017_04', 'CMU_017_05', 'CMU_017_06', 'CMU_017_07', 'CMU_017_08', 'CMU_017_09', 'CMU_017_10', 'CMU_024_01', 'CMU_025_01', 'CMU_026_01', 'CMU_026_02', 'CMU_026_03', 'CMU_026_04', 'CMU_026_05', 'CMU_026_06', 'CMU_026_07', 'CMU_026_08', 'CMU_027_01', 'CMU_027_02', 'CMU_027_03', 'CMU_027_04', 'CMU_027_05', 'CMU_027_06', 'CMU_027_07', 'CMU_027_08', 'CMU_027_09', 'CMU_029_01', 'CMU_029_02', 'CMU_029_03', 'CMU_029_04', 'CMU_029_05', 'CMU_029_06', 'CMU_029_07', 'CMU_029_08', 'CMU_029_09', 'CMU_029_10', 'CMU_029_11', 'CMU_029_12', 'CMU_029_13', 'CMU_031_01', 'CMU_031_02', 'CMU_031_03', 'CMU_031_06', 'CMU_031_07', 'CMU_031_08', 'CMU_032_01', 'CMU_032_02', 'CMU_032_03', 'CMU_032_04', 'CMU_032_05', 'CMU_032_06', 'CMU_032_07', 'CMU_032_08', 'CMU_032_09', 'CMU_032_10', 'CMU_032_11', 'CMU_035_01', 'CMU_035_02', 'CMU_035_03', 'CMU_035_04', 'CMU_035_05', 'CMU_035_06', 'CMU_035_07', 'CMU_035_08', 'CMU_035_09', 'CMU_035_10', 'CMU_035_11', 'CMU_035_12', 'CMU_035_13', 'CMU_035_14', 'CMU_035_15', 'CMU_035_16', 'CMU_035_17', 'CMU_035_18', 'CMU_035_19', 'CMU_035_20', 'CMU_035_21', 'CMU_035_22', 'CMU_035_23', 'CMU_035_24', 'CMU_035_25', 'CMU_035_26', 'CMU_035_27', 'CMU_035_28', 'CMU_035_29', 'CMU_035_30', 'CMU_035_31', 'CMU_035_32', 'CMU_035_33', 'CMU_035_34', 'CMU_036_02', 'CMU_036_03', 'CMU_036_09', 'CMU_037_01', 'CMU_038_01', 'CMU_038_02', 'CMU_038_03', 'CMU_038_04', 'CMU_039_11', 'CMU_040_02', 'CMU_040_03', 'CMU_040_04', 'CMU_040_05', 'CMU_040_10', 'CMU_040_11', 'CMU_040_12', 'CMU_041_02', 'CMU_041_03', 'CMU_041_04', 'CMU_041_05', 'CMU_041_06', 'CMU_041_10', 'CMU_041_11', 'CMU_045_01', 'CMU_046_01', 'CMU_047_01', 'CMU_049_01', 'CMU_049_02', 'CMU_049_03', 'CMU_049_04', 'CMU_049_05', 'CMU_049_06', 'CMU_049_07', 'CMU_049_08', 'CMU_049_09', 'CMU_049_10', 'CMU_049_11', 'CMU_049_12', 'CMU_049_13', 'CMU_049_14', 'CMU_049_15', 'CMU_049_16', 'CMU_049_17', 'CMU_049_18', 'CMU_049_19', 'CMU_049_20', 'CMU_049_22', 'CMU_056_01', 'CMU_056_04', 'CMU_056_05', 'CMU_056_06', 'CMU_056_07', 'CMU_056_08', 'CMU_060_02', 'CMU_060_03', 'CMU_060_05', 'CMU_060_12', 'CMU_060_14', 'CMU_061_01', 'CMU_061_02', 'CMU_061_03', 'CMU_061_04', 'CMU_061_05', 'CMU_061_06', 'CMU_061_07', 'CMU_061_08', 'CMU_061_09', 'CMU_061_10', 'CMU_061_15', 'CMU_069_01', 'CMU_069_02', 'CMU_069_03', 'CMU_069_04', 'CMU_069_05', 'CMU_069_06', 'CMU_069_07', 'CMU_069_08', 'CMU_069_09', 'CMU_069_10', 'CMU_069_11', 'CMU_069_12', 'CMU_069_13', 'CMU_069_14', 'CMU_069_15', 'CMU_069_16', 'CMU_069_17', 'CMU_069_18', 'CMU_069_19', 'CMU_069_20', 'CMU_069_21', 'CMU_069_22', 'CMU_069_23', 'CMU_069_24', 'CMU_069_25', 'CMU_069_26', 'CMU_069_27', 'CMU_069_28', 'CMU_069_29', 'CMU_069_30', 'CMU_069_31', 'CMU_069_32', 'CMU_069_33', 'CMU_069_34', 'CMU_069_36', 'CMU_069_37', 'CMU_069_38', 'CMU_069_39', 'CMU_069_40', 'CMU_069_41', 'CMU_069_42', 'CMU_069_43', 'CMU_069_44', 'CMU_069_45', 'CMU_069_46', 'CMU_069_47', 'CMU_069_48', 'CMU_069_49', 'CMU_069_50', 'CMU_069_51', 'CMU_069_52', 'CMU_069_53', 'CMU_069_54', 'CMU_069_55', 'CMU_069_56', 'CMU_069_57', 'CMU_069_58', 'CMU_069_59', 'CMU_069_60', 'CMU_069_61', 'CMU_069_62', 'CMU_069_63', 'CMU_069_64', 'CMU_069_65', 'CMU_069_66', 'CMU_069_67', 'CMU_075_01', 'CMU_075_02', 'CMU_075_03', 'CMU_075_04', 'CMU_075_05', 'CMU_075_06', 'CMU_075_07', 'CMU_075_08', 'CMU_075_09', 'CMU_075_10', 'CMU_075_11', 'CMU_075_12', 'CMU_075_13', 'CMU_075_14', 'CMU_075_15', 'CMU_076_01', 'CMU_076_02', 'CMU_076_06', 'CMU_076_08', 'CMU_076_09', 'CMU_076_10', 'CMU_076_11', 'CMU_077_02', 'CMU_077_03', 'CMU_077_04', 'CMU_077_10', 'CMU_077_11', 'CMU_077_12', 'CMU_077_13', 'CMU_077_14', 'CMU_077_15', 'CMU_077_16', 'CMU_077_17', 'CMU_077_18', 'CMU_077_21', 'CMU_077_27', 'CMU_077_28', 'CMU_077_29', 'CMU_077_30', 'CMU_077_31', 'CMU_077_32', 'CMU_077_33', 'CMU_077_34', 'CMU_078_01', 'CMU_078_02', 'CMU_078_03', 'CMU_078_04', 'CMU_078_05', 'CMU_078_07', 'CMU_078_09', 'CMU_078_10', 'CMU_078_13', 'CMU_078_14', 'CMU_078_15', 'CMU_078_16', 'CMU_078_17', 'CMU_078_18', 'CMU_078_19', 'CMU_078_20', 'CMU_078_21', 'CMU_078_22', 'CMU_078_23', 'CMU_078_24', 'CMU_078_25', 'CMU_078_26', 'CMU_078_27', 'CMU_078_28', 'CMU_078_29', 'CMU_078_30', 'CMU_078_31', 'CMU_078_32', 'CMU_078_33', 'CMU_082_08', 'CMU_082_09', 'CMU_082_10', 'CMU_082_11', 'CMU_082_14', 'CMU_082_15', 'CMU_083_18', 'CMU_083_19', 'CMU_083_20', 'CMU_083_21', 'CMU_083_33', 'CMU_083_36', 'CMU_083_37', 'CMU_083_38', 'CMU_083_39', 'CMU_083_40', 'CMU_083_41', 'CMU_083_42', 'CMU_083_43', 'CMU_083_44', 'CMU_083_45', 'CMU_083_46', 'CMU_083_48', 'CMU_083_49', 'CMU_083_51', 'CMU_083_52', 'CMU_083_53', 'CMU_083_54', 'CMU_083_55', 'CMU_083_56', 'CMU_083_57', 'CMU_083_58', 'CMU_083_59', 'CMU_083_60', 'CMU_083_61', 'CMU_083_62', 'CMU_083_63', 'CMU_083_64', 'CMU_083_65', 'CMU_083_66', 'CMU_083_67', 'CMU_086_01', 'CMU_086_02', 'CMU_086_03', 'CMU_086_07', 'CMU_086_08', 'CMU_086_11', 'CMU_086_14', 'CMU_090_06', 'CMU_090_07', 'CMU_091_01', 'CMU_091_02', 'CMU_091_03', 'CMU_091_04', 'CMU_091_05', 'CMU_091_06', 'CMU_091_07', 'CMU_091_08', 'CMU_091_10', 'CMU_091_11', 'CMU_091_12', 'CMU_091_13', 'CMU_091_14', 'CMU_091_15', 'CMU_091_16', 'CMU_091_17', 'CMU_091_18', 'CMU_091_19', 'CMU_091_20', 'CMU_091_21', 'CMU_091_22', 'CMU_091_23', 'CMU_091_24', 'CMU_091_25', 'CMU_091_26', 'CMU_091_27', 'CMU_091_28', 'CMU_091_29', 'CMU_091_30', 'CMU_091_31', 'CMU_091_32', 'CMU_091_33', 'CMU_091_34', 'CMU_091_35', 'CMU_091_36', 'CMU_091_37', 'CMU_091_38', 'CMU_091_39', 'CMU_091_40', 'CMU_091_41', 'CMU_091_42', 'CMU_091_43', 'CMU_091_44', 'CMU_091_45', 'CMU_091_46', 'CMU_091_47', 'CMU_091_48', 'CMU_091_49', 'CMU_091_50', 'CMU_091_51', 'CMU_091_52', 'CMU_091_53', 'CMU_091_54', 'CMU_091_55', 'CMU_091_56', 'CMU_091_57', 'CMU_091_58', 'CMU_091_59', 'CMU_091_60', 'CMU_091_61', 'CMU_091_62', 'CMU_104_53', 'CMU_104_54', 'CMU_104_55', 'CMU_104_56', 'CMU_104_57', 'CMU_105_01', 'CMU_105_02', 'CMU_105_03', 'CMU_105_04', 'CMU_105_05', 'CMU_105_07', 'CMU_105_08', 'CMU_105_10', 'CMU_105_17', 'CMU_105_18', 'CMU_105_19', 'CMU_105_20', 'CMU_105_22', 'CMU_105_29', 'CMU_105_31', 'CMU_105_34', 'CMU_105_36', 'CMU_105_37', 'CMU_105_38', 'CMU_105_39', 'CMU_105_40', 'CMU_105_41', 'CMU_105_42', 'CMU_105_43', 'CMU_105_44', 'CMU_105_45', 'CMU_105_46', 'CMU_105_47', 'CMU_105_48', 'CMU_105_49', 'CMU_105_50', 'CMU_105_51', 'CMU_105_52', 'CMU_105_53', 'CMU_105_54', 'CMU_105_55', 'CMU_105_56', 'CMU_105_57', 'CMU_105_58', 'CMU_105_59', 'CMU_105_60', 'CMU_105_61', 'CMU_105_62', 'CMU_107_01', 'CMU_107_02', 'CMU_107_03', 'CMU_107_04', 'CMU_107_05', 'CMU_107_06', 'CMU_107_07', 'CMU_107_08', 'CMU_107_09', 'CMU_107_11', 'CMU_107_12', 'CMU_107_13', 'CMU_107_14', 'CMU_108_01', 'CMU_108_02', 'CMU_108_03', 'CMU_108_04', 'CMU_108_05', 'CMU_108_06', 'CMU_108_07', 'CMU_108_08', 'CMU_108_09', 'CMU_108_12', 'CMU_108_13', 'CMU_108_14', 'CMU_108_17', 'CMU_108_18', 'CMU_108_19', 'CMU_108_20', 'CMU_108_21', 'CMU_108_22', 'CMU_108_23', 'CMU_108_24', 'CMU_108_25', 'CMU_108_26', 'CMU_108_27', 'CMU_108_28', 'CMU_114_13', 'CMU_114_14', 'CMU_114_15', 'CMU_118_01', 'CMU_118_02', 'CMU_118_03', 'CMU_118_04', 'CMU_118_05', 'CMU_118_06', 'CMU_118_07', 'CMU_118_08', 'CMU_118_09', 'CMU_118_10', 'CMU_118_11', 'CMU_118_12', 'CMU_118_13', 'CMU_118_14', 'CMU_118_15', 'CMU_118_16', 'CMU_118_17', 'CMU_118_18', 'CMU_118_19', 'CMU_118_20', 'CMU_118_21', 'CMU_118_22', 'CMU_118_23', 'CMU_118_24', 'CMU_118_25', 'CMU_118_26', 'CMU_118_27', 'CMU_118_28', 'CMU_118_29', 'CMU_118_30', 'CMU_118_32', 'CMU_120_20', 'CMU_124_03', 'CMU_124_04', 'CMU_124_05', 'CMU_124_06', 'CMU_127_02', 'CMU_127_03', 'CMU_127_04', 'CMU_127_05', 'CMU_127_06', 'CMU_127_07', 'CMU_127_08', 'CMU_127_09', 'CMU_127_10', 'CMU_127_11', 'CMU_127_12', 'CMU_127_13', 'CMU_127_14', 'CMU_127_15', 'CMU_127_16', 'CMU_127_17', 'CMU_127_18', 'CMU_127_19', 'CMU_127_20', 'CMU_127_21', 'CMU_127_22', 'CMU_127_23', 'CMU_127_24', 'CMU_127_25', 'CMU_127_26', 'CMU_127_27', 'CMU_127_28', 'CMU_127_29', 'CMU_127_30', 'CMU_127_31', 'CMU_127_32', 'CMU_127_37', 'CMU_127_38', 'CMU_128_02', 'CMU_128_03', 'CMU_128_04', 'CMU_128_05', 'CMU_128_06', 'CMU_128_07', 'CMU_128_08', 'CMU_128_09', 'CMU_128_10', 'CMU_128_11', 'CMU_132_01', 'CMU_132_02', 'CMU_132_03', 'CMU_132_04', 'CMU_132_05', 'CMU_132_06', 'CMU_132_07', 'CMU_132_08', 'CMU_132_09', 'CMU_132_10', 'CMU_132_11', 'CMU_132_12', 'CMU_132_13', 'CMU_132_14', 'CMU_132_15', 'CMU_132_16', 'CMU_132_17', 'CMU_132_18', 'CMU_132_19', 'CMU_132_20', 'CMU_132_21', 'CMU_132_22', 'CMU_132_23', 'CMU_132_24', 'CMU_132_25', 'CMU_132_26', 'CMU_132_27', 'CMU_132_28', 'CMU_132_29', 'CMU_132_30', 'CMU_132_31', 'CMU_132_32', 'CMU_132_33', 'CMU_132_34', 'CMU_132_35', 'CMU_132_36', 'CMU_132_37', 'CMU_132_38', 'CMU_132_39', 'CMU_132_40', 'CMU_132_41', 'CMU_132_42', 'CMU_132_43', 'CMU_132_44', 'CMU_132_45', 'CMU_132_46', 'CMU_132_47', 'CMU_132_48', 'CMU_132_49', 'CMU_132_50', 'CMU_132_51', 'CMU_132_52', 'CMU_132_53', 'CMU_132_54', 'CMU_132_55', 'CMU_133_03', 'CMU_133_04', 'CMU_133_05', 'CMU_133_06', 'CMU_133_07', 'CMU_133_08', 'CMU_133_10', 'CMU_133_11', 'CMU_133_12', 'CMU_133_13', 'CMU_133_14', 'CMU_133_15', 'CMU_133_16', 'CMU_133_17', 'CMU_133_18', 'CMU_133_19', 'CMU_133_20', 'CMU_133_21', 'CMU_133_22', 'CMU_133_23', 'CMU_133_24', 'CMU_139_04', 'CMU_139_10', 'CMU_139_11', 'CMU_139_12', 'CMU_139_13', 'CMU_139_14', 'CMU_139_15', 'CMU_139_16', 'CMU_139_17', 'CMU_139_18', 'CMU_139_21', 'CMU_139_28', 'CMU_140_01', 'CMU_140_02', 'CMU_140_08', 'CMU_140_09', 'CMU_143_01', 'CMU_143_02', 'CMU_143_03', 'CMU_143_04', 'CMU_143_05', 'CMU_143_06', 'CMU_143_07', 'CMU_143_08', 'CMU_143_09', 'CMU_143_14', 'CMU_143_15', 'CMU_143_16', 'CMU_143_29', 'CMU_143_32', 'CMU_143_39', 'CMU_143_40', 'CMU_143_41', 'CMU_143_42')) CMU_SUBSETS_DICT = dict( walk_tiny=WALK_TINY, run_jump_tiny=RUN_JUMP_TINY, get_up=GET_UP, locomotion_small=LOCOMOTION_SMALL, all=ALL )
dm_control-main
dm_control/locomotion/tasks/reference_pose/cmu_subsets.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. # ============================================================================ """Tasks for multi-clip mocap tracking with RL.""" import abc import collections import typing from typing import Any, Callable, Mapping, Optional, Sequence, Set, Text, Union from absl import logging from dm_control import composer from dm_control.composer.observation import observable as base_observable from dm_control.locomotion.mocap import loader from dm_control.locomotion.tasks.reference_pose import datasets from dm_control.locomotion.tasks.reference_pose import types from dm_control.locomotion.tasks.reference_pose import utils from dm_control.locomotion.tasks.reference_pose import rewards from dm_control.mujoco.wrapper import mjbindings from dm_control.utils import transformations as tr from dm_env import specs import numpy as np import tree if typing.TYPE_CHECKING: from dm_control.locomotion.walkers import legacy_base from dm_control import mjcf mjlib = mjbindings.mjlib DEFAULT_PHYSICS_TIMESTEP = 0.005 _MAX_END_STEP = 10000 def _strip_reference_prefix(dictionary: Mapping[Text, Any], prefix: Text, keep_prefixes: Optional[Set[Text]] = None): """Strips a prefix from dictionary keys and remove keys without the prefix. Strips a prefix from the keys of a dictionary and removes any key from the result dictionary that doesn't match the determined prefix, unless explicitly excluded in keep_prefixes. E.g. dictionary={ 'example_key': 1, 'example_another_key': 2, 'doesnt_match': 3, 'keep_this': 4, }, prefix='example_', keep_prefixes=['keep_'] would return { 'key': 1, 'another_key': 2, 'keep_this': 4, } Args: dictionary: The dictionary whose keys will be stripped. prefix: The prefix to strip. keep_prefixes: Optionally specify prefixes for keys that will be unchanged and retained in the result dictionary. Returns: The dictionary with the modified keys and original values (and unchanged keys specified by keep_prefixes). """ keep_prefixes = keep_prefixes or [] new_dictionary = dict() for key in dictionary: if key.startswith(prefix): key_without_prefix = key.split(prefix)[1] # note that this will not copy the underlying array. new_dictionary[key_without_prefix] = dictionary[key] else: for keep_prefix in keep_prefixes: if key.startswith(keep_prefix): new_dictionary[key] = dictionary[key] return new_dictionary class ReferencePosesTask(composer.Task, metaclass=abc.ABCMeta): """Abstract base class for task that uses reference data.""" def __init__( self, walker: Callable[..., 'legacy_base.Walker'], arena: composer.Arena, ref_path: Text, ref_steps: Sequence[int], dataset: Union[Text, types.ClipCollection], termination_error_threshold: float = 0.3, prop_termination_error_threshold: float = 0.1, min_steps: int = 10, reward_type: Text = 'termination_reward', physics_timestep: float = DEFAULT_PHYSICS_TIMESTEP, always_init_at_clip_start: bool = False, proto_modifier: Optional[Any] = None, prop_factory: Optional[Any] = None, disable_props: bool = False, ghost_offset: Optional[Sequence[Union[int, float]]] = None, body_error_multiplier: Union[int, float] = 1.0, actuator_force_coeff: float = 0.015, enabled_reference_observables: Optional[Sequence[Text]] = None, ): """Abstract task that uses reference data. Args: walker: Walker constructor to be used. arena: Arena to be used. ref_path: Path to the dataset containing reference poses. ref_steps: tuples of indices of reference observation. E.g if ref_steps=(1, 2, 3) the walker/reference observation at time t will contain information from t+1, t+2, t+3. dataset: A ClipCollection instance or a name of a dataset that appears as a key in DATASETS in datasets.py termination_error_threshold: Error threshold for episode terminations for hand body position and joint error only. prop_termination_error_threshold: Error threshold for episode terminations for prop position. min_steps: minimum number of steps within an episode. This argument determines the latest allowable starting point within a given reference trajectory. reward_type: type of reward to use, must be a string that appears as a key in the REWARD_FN dict in rewards.py. physics_timestep: Physics timestep to use for simulation. always_init_at_clip_start: only initialize epsidodes at the start of a reference trajectory. proto_modifier: Optional proto modifier to modify reference trajectories, e.g. adding a vertical offset. prop_factory: Optional function that takes the mocap proto and returns the corresponding props for the trajectory. disable_props: If prop_factory is specified but disable_props is True, no props will be created. ghost_offset: if not None, include a ghost rendering of the walker with the reference pose at the specified position offset. body_error_multiplier: A multiplier that is applied to the body error term when determining failure termination condition. actuator_force_coeff: A coefficient for the actuator force reward channel. enabled_reference_observables: Optional iterable of enabled observables. If not specified, a reasonable default set will be enabled. """ self._ref_steps = np.sort(ref_steps) self._max_ref_step = self._ref_steps[-1] self._termination_error_threshold = termination_error_threshold self._prop_termination_error_threshold = prop_termination_error_threshold self._reward_fn = rewards.get_reward(reward_type) self._reward_keys = rewards.get_reward_channels(reward_type) self._min_steps = min_steps self._always_init_at_clip_start = always_init_at_clip_start self._ghost_offset = ghost_offset self._body_error_multiplier = body_error_multiplier self._actuator_force_coeff = actuator_force_coeff logging.info('Reward type %s', reward_type) if isinstance(dataset, Text): try: dataset = datasets.DATASETS[dataset] except KeyError: logging.error('Dataset %s not found in datasets.py', dataset) raise self._load_reference_data( ref_path=ref_path, proto_modifier=proto_modifier, dataset=dataset) self._get_possible_starts() logging.info('%d starting points found.', len(self._possible_starts)) # load a dummy trajectory self._current_clip_index = 0 self._current_clip = self._loader.get_trajectory( self._dataset.ids[0], zero_out_velocities=False) # Create the environment. self._arena = arena self._walker = utils.add_walker(walker, self._arena) self.set_timesteps( physics_timestep=physics_timestep, control_timestep=self._current_clip.dt) # Identify the desired body components. try: walker_bodies = self._walker.mocap_tracking_bodies except AttributeError: logging.info('Walker must implement mocap bodies for this task.') raise walker_bodies_names = [bdy.name for bdy in walker_bodies] self._body_idxs = np.array( [walker_bodies_names.index(bdy) for bdy in walker_bodies_names]) self._prop_factory = prop_factory if disable_props: self._props = [] else: self._props = self._current_clip.create_props(prop_factory=prop_factory) for prop in self._props: self._arena.add_free_entity(prop) # Create the observables. self._add_observables(enabled_reference_observables) # initialize counters etc. self._time_step = 0 self._current_start_time = 0.0 self._last_step = 0 self._current_clip_index = 0 self._reference_observations = dict() self._end_mocap = False self._should_truncate = False # Set up required dummy quantities for observations self._prop_prefixes = [] self._disable_props = disable_props if not disable_props: if len(self._props) == 1: self._prop_prefixes += ['prop/'] else: self._prop_prefixes += [f'prop_{i}/' for i in range(len(self._props))] self._clip_reference_features = self._current_clip.as_dict() self._strip_reference_prefix() self._walker_joints = self._clip_reference_features['joints'][0] self._walker_features = tree.map_structure(lambda x: x[0], self._clip_reference_features) self._walker_features_prev = tree.map_structure( lambda x: x[0], self._clip_reference_features) self._current_reference_features = dict() self._reference_ego_bodies_quats = collections.defaultdict(dict) # if requested add ghost body to visualize motion capture reference. if self._ghost_offset is not None: self._ghost = utils.add_walker( walker, self._arena, name='ghost', ghost=True) self._ghost.observables.disable_all() if disable_props: self._ghost_props = [] else: self._ghost_props = self._current_clip.create_props( prop_factory=self._ghost_prop_factory) for prop in self._ghost_props: self._arena.add_free_entity(prop) prop.observables.disable_all() else: self._ghost_props = [] # initialize reward channels self._reset_reward_channels() def _strip_reference_prefix(self): self._clip_reference_features = _strip_reference_prefix( # pytype: disable=wrong-arg-types self._clip_reference_features, 'walker/', keep_prefixes=self._prop_prefixes) positions = [] quaternions = [] for prefix in self._prop_prefixes: position_key, quaternion_key = f'{prefix}position', f'{prefix}quaternion' positions.append(self._clip_reference_features[position_key]) quaternions.append(self._clip_reference_features[quaternion_key]) del self._clip_reference_features[position_key] del self._clip_reference_features[quaternion_key] # positions has dimension (#props, #timesteps, 3). However, the convention # for reference observations is (#timesteps, #props, 3). Therefore we # transpose the dimensions by specifying the desired positions in the list # for each dimension as an argument to np.transpose. axes = [1, 0, 2] if self._prop_prefixes: self._clip_reference_features['prop_positions'] = np.transpose( positions, axes=axes) self._clip_reference_features['prop_quaternions'] = np.transpose( quaternions, axes=axes) def _ghost_prop_factory(self, prop_proto, priority_friction=False): if self._prop_factory is None: return None prop = self._prop_factory(prop_proto, priority_friction=priority_friction) for geom in prop.mjcf_model.find_all('geom'): geom.set_attributes(contype=0, conaffinity=0, rgba=(0.5, 0.5, 0.5, .999)) prop.observables.disable_all() return prop def _load_reference_data(self, ref_path, proto_modifier, dataset: types.ClipCollection): self._loader = loader.HDF5TrajectoryLoader( ref_path, proto_modifier=proto_modifier) self._dataset = dataset self._num_clips = len(self._dataset.ids) if self._dataset.end_steps is None: # load all trajectories to infer clip end steps. self._all_clips = [ self._loader.get_trajectory( # pylint: disable=g-complex-comprehension clip_id, start_step=clip_start_step, end_step=_MAX_END_STEP) for clip_id, clip_start_step in zip( self._dataset.ids, self._dataset.start_steps) ] # infer clip end steps to set sampling distribution self._dataset.end_steps = tuple(clip.end_step for clip in self._all_clips) else: self._all_clips = [None] * self._num_clips def _add_observables(self, enabled_reference_observables): # pylint: disable=g-long-lambda self._walker.observables.add_observable( 'reference_rel_joints', base_observable.Generic(lambda _: self._reference_observations[ 'walker/reference_rel_joints'])) self._walker.observables.add_observable( 'reference_rel_bodies_pos_global', base_observable.Generic(lambda _: self._reference_observations[ 'walker/reference_rel_bodies_pos_global'])) self._walker.observables.add_observable( 'reference_rel_bodies_quats', base_observable.Generic(lambda _: self._reference_observations[ 'walker/reference_rel_bodies_quats'])) self._walker.observables.add_observable( 'reference_rel_bodies_pos_local', base_observable.Generic(lambda _: self._reference_observations[ 'walker/reference_rel_bodies_pos_local'])) self._walker.observables.add_observable( 'reference_ego_bodies_quats', base_observable.Generic(lambda _: self._reference_observations[ 'walker/reference_ego_bodies_quats'])) self._walker.observables.add_observable( 'reference_rel_root_quat', base_observable.Generic(lambda _: self._reference_observations[ 'walker/reference_rel_root_quat'])) self._walker.observables.add_observable( 'reference_rel_root_pos_local', base_observable.Generic(lambda _: self._reference_observations[ 'walker/reference_rel_root_pos_local'])) # pylint: enable=g-long-lambda self._walker.observables.add_observable( 'reference_appendages_pos', base_observable.Generic(self.get_reference_appendages_pos)) if enabled_reference_observables: for name, observable in self.observables.items(): observable.enabled = name in enabled_reference_observables self._walker.observables.add_observable( 'clip_id', base_observable.Generic(self.get_clip_id)) self._walker.observables.add_observable( 'velocimeter_control', base_observable.Generic(self.get_veloc_control)) self._walker.observables.add_observable( 'gyro_control', base_observable.Generic(self.get_gyro_control)) self._walker.observables.add_observable( 'joints_vel_control', base_observable.Generic(self.get_joints_vel_control)) self._arena.observables.add_observable( 'reference_props_pos_global', base_observable.Generic(self.get_reference_props_pos_global)) self._arena.observables.add_observable( 'reference_props_quat_global', base_observable.Generic(self.get_reference_props_quat_global)) observables = [] observables += self._walker.observables.proprioception observables += self._walker.observables.kinematic_sensors observables += self._walker.observables.dynamic_sensors for observable in observables: observable.enabled = True for prop in self._props: prop.observables.position.enabled = True prop.observables.orientation.enabled = True def _get_possible_starts(self): # List all possible (clip, step) starting points. self._possible_starts = [] self._start_probabilities = [] dataset = self._dataset for clip_number, (start, end, weight) in enumerate( zip(dataset.start_steps, dataset.end_steps, dataset.weights)): # length - required lookahead - minimum number of steps last_possible_start = end - self._max_ref_step - self._min_steps if self._always_init_at_clip_start: self._possible_starts += [(clip_number, start)] self._start_probabilities += [weight] else: self._possible_starts += [ (clip_number, j) for j in range(start, last_possible_start) ] self._start_probabilities += [ weight for _ in range(start, last_possible_start) ] # normalize start probabilities self._start_probabilities = np.array(self._start_probabilities) / np.sum( self._start_probabilities) def initialize_episode_mjcf(self, random_state: np.random.RandomState): if hasattr(self._arena, 'regenerate'): self._arena.regenerate(random_state) # Get a new clip here to instantiate the right prop for this episode. self._get_clip_to_track(random_state) # Set up props. # We call the prop factory here to ensure that props can change per episode. for prop in self._props: prop.detach() del prop if not self._disable_props: self._props = self._current_clip.create_props( prop_factory=self._prop_factory) for prop in self._props: self._arena.add_free_entity(prop) prop.observables.position.enabled = True prop.observables.orientation.enabled = True if self._ghost_offset is not None: for prop in self._ghost_props: prop.detach() del prop self._ghost_props = self._current_clip.create_props( prop_factory=self._ghost_prop_factory) for prop in self._ghost_props: self._arena.add_free_entity(prop) prop.observables.disable_all() def _get_clip_to_track(self, random_state: np.random.RandomState): # Randomly select a starting point. index = random_state.choice( len(self._possible_starts), p=self._start_probabilities) clip_index, start_step = self._possible_starts[index] self._current_clip_index = clip_index clip_id = self._dataset.ids[self._current_clip_index] if self._all_clips[self._current_clip_index] is None: # fetch selected trajectory logging.info('Loading clip %s', clip_id) self._all_clips[self._current_clip_index] = self._loader.get_trajectory( clip_id, start_step=self._dataset.start_steps[self._current_clip_index], end_step=self._dataset.end_steps[self._current_clip_index], zero_out_velocities=False) self._current_clip = self._all_clips[self._current_clip_index] self._clip_reference_features = self._current_clip.as_dict() self._strip_reference_prefix() # The reference features are already restricted to # clip_start_step:clip_end_step. However start_step is in # [clip_start_step:clip_end_step]. Hence we subtract clip_start_step to # obtain a valid index for the reference features. self._time_step = start_step - self._dataset.start_steps[ self._current_clip_index] self._current_start_time = (start_step - self._dataset.start_steps[ self._current_clip_index]) * self._current_clip.dt self._last_step = len( self._clip_reference_features['joints']) - self._max_ref_step - 1 logging.info('Mocap %s at step %d with remaining length %d.', clip_id, start_step, self._last_step - start_step) def initialize_episode(self, physics: 'mjcf.Physics', random_state: np.random.RandomState): """Randomly selects a starting point and set the walker.""" # Set the walker at the beginning of the clip. self._set_walker(physics) self._walker_features = utils.get_features( physics, self._walker, props=self._props) self._walker_features_prev = self._walker_features.copy() self._walker_joints = np.array(physics.bind(self._walker.mocap_joints).qpos) # pytype: disable=attribute-error # compute initial error self._compute_termination_error() # assert error is 0 at initialization. In particular this will prevent # a proto/walker mismatch. if self._termination_error > 1e-2: raise ValueError(('The termination exceeds 1e-2 at initialization. ' 'This is likely due to a proto/walker mismatch.')) self._update_ghost(physics) self._reference_observations.update( self.get_all_reference_observations(physics)) # reset reward channels self._reset_reward_channels() def _reset_reward_channels(self): if self._reward_keys: self.last_reward_channels = collections.OrderedDict([ (k, 0.0) for k in self._reward_keys ]) else: self.last_reward_channels = None def _compute_termination_error(self): target_joints = self._clip_reference_features['joints'][self._time_step] error_joints = np.mean(np.abs(target_joints - self._walker_joints)) target_bodies = self._clip_reference_features['body_positions'][ self._time_step] error_bodies = np.mean( np.abs((target_bodies - self._walker_features['body_positions'])[self._body_idxs])) self._termination_error = ( 0.5 * self._body_error_multiplier * error_bodies + 0.5 * error_joints) if self._props: target_props = self._clip_reference_features['prop_positions'][ self._time_step] cur_props = self._walker_features['prop_positions'] # Separately compute prop termination error as euclidean distance. self._prop_termination_error = np.mean( np.linalg.norm(target_props - cur_props, axis=-1)) def before_step(self, physics: 'mjcf.Physics', action, random_state: np.random.RandomState): self._walker.apply_action(physics, action, random_state) def after_step(self, physics: 'mjcf.Physics', random_state: np.random.RandomState): """Update the data after step.""" del random_state # unused by after_step. self._walker_features_prev = self._walker_features.copy() def after_compile(self, physics: 'mjcf.Physics', random_state: np.random.RandomState): # populate reference observations field to initialize observations. if not self._reference_observations: self._reference_observations.update( self.get_all_reference_observations(physics)) def should_terminate_episode(self, physics: 'mjcf.Physics'): del physics # physics unused by should_terminate_episode. if self._should_truncate: logging.info('Truncate with error %f.', self._termination_error) return True if self._end_mocap: logging.info('End of mocap.') return True return False def get_discount(self, physics: 'mjcf.Physics'): del physics # unused by get_discount. if self._should_truncate: return 0.0 return 1.0 def get_reference_rel_joints(self, physics: 'mjcf.Physics'): """Observation of the reference joints relative to walker.""" del physics # physics unused by reference observations. time_steps = self._time_step + self._ref_steps diff = (self._clip_reference_features['joints'][time_steps] - self._walker_joints) return diff[:, self._walker.mocap_to_observable_joint_order].flatten() def get_reference_rel_bodies_pos_global(self, physics: 'mjcf.Physics'): """Observation of the reference bodies relative to walker.""" del physics # physics unused by reference observations. time_steps = self._time_step + self._ref_steps return (self._clip_reference_features['body_positions'][time_steps] - self._walker_features['body_positions'])[:, self._body_idxs].flatten() def get_reference_rel_bodies_quats(self, physics: 'mjcf.Physics'): """Observation of the reference bodies quats relative to walker.""" del physics # physics unused by reference observations. time_steps = self._time_step + self._ref_steps obs = [] for t in time_steps: for b in self._body_idxs: obs.append( tr.quat_diff( self._walker_features['body_quaternions'][b, :], self._clip_reference_features['body_quaternions'][t, b, :])) return np.concatenate([o.flatten() for o in obs]) def get_reference_rel_bodies_pos_local(self, physics: 'mjcf.Physics'): """Observation of the reference bodies relative to walker in local frame.""" time_steps = self._time_step + self._ref_steps obs = self._walker.transform_vec_to_egocentric_frame( physics, (self._clip_reference_features['body_positions'][time_steps] - self._walker_features['body_positions'])[:, self._body_idxs]) return np.concatenate([o.flatten() for o in obs]) def get_reference_ego_bodies_quats(self, unused_physics: 'mjcf.Physics'): """Body quat of the reference relative to the reference root quat.""" time_steps = self._time_step + self._ref_steps obs = [] quats_for_clip = self._reference_ego_bodies_quats[self._current_clip_index] for t in time_steps: if t not in quats_for_clip: root_quat = self._clip_reference_features['quaternion'][t, :] quats_for_clip[t] = [ tr.quat_diff( # pylint: disable=g-complex-comprehension root_quat, self._clip_reference_features['body_quaternions'][t, b, :]) for b in self._body_idxs ] obs.extend(quats_for_clip[t]) return np.concatenate([o.flatten() for o in obs]) def get_reference_rel_root_quat(self, physics: 'mjcf.Physics'): """Root quaternion of reference relative to current root quat.""" del physics # physics unused by reference observations. time_steps = self._time_step + self._ref_steps obs = [] for t in time_steps: obs.append( tr.quat_diff(self._walker_features['quaternion'], self._clip_reference_features['quaternion'][t, :])) return np.concatenate([o.flatten() for o in obs]) def get_reference_appendages_pos(self, physics: 'mjcf.Physics'): """Reference appendage positions in reference frame.""" del physics # physics unused by reference observations. time_steps = self._time_step + self._ref_steps return self._clip_reference_features['appendages'][time_steps].flatten() def get_reference_rel_root_pos_local(self, physics: 'mjcf.Physics'): """Reference position relative to current root position in root frame.""" time_steps = self._time_step + self._ref_steps obs = self._walker.transform_vec_to_egocentric_frame( physics, (self._clip_reference_features['position'][time_steps] - self._walker_features['position'])) return np.concatenate([o.flatten() for o in obs]) def get_reference_props_pos_global(self, physics: 'mjcf.Physics'): time_steps = self._time_step + self._ref_steps # size N x 3 where N = # of props if self._props: return self._clip_reference_features['prop_positions'][ time_steps].flatten() else: return [] def get_reference_props_quat_global(self, physics: 'mjcf.Physics'): time_steps = self._time_step + self._ref_steps # size N x 4 where N = # of props if self._props: return self._clip_reference_features['prop_quaternions'][ time_steps].flatten() else: return [] def get_veloc_control(self, physics: 'mjcf.Physics'): """Velocity measurements in the prev root frame at the control timestep.""" del physics # physics unused by get_veloc_control. rmat_prev = tr.quat_to_mat(self._walker_features_prev['quaternion'])[:3, :3] veloc_world = ( self._walker_features['position'] - self._walker_features_prev['position']) / self._control_timestep return np.dot(veloc_world, rmat_prev) def get_gyro_control(self, physics: 'mjcf.Physics'): """Gyro measurements in the prev root frame at the control timestep.""" del physics # physics unused by get_gyro_control. quat_curr, quat_prev = (self._walker_features['quaternion'], self._walker_features_prev['quaternion']) normed_diff = tr.quat_diff(quat_prev, quat_curr) normed_diff /= np.linalg.norm(normed_diff) return tr.quat_to_axisangle(normed_diff) / self._control_timestep def get_joints_vel_control(self, physics: 'mjcf.Physics'): """Joint velocity measurements at the control timestep.""" del physics # physics unused by get_joints_vel_control. joints_curr, joints_prev = (self._walker_features['joints'], self._walker_features_prev['joints']) return (joints_curr - joints_prev)[ self._walker.mocap_to_observable_joint_order]/self._control_timestep def get_clip_id(self, physics: 'mjcf.Physics'): """Observation of the clip id.""" del physics # physics unused by get_clip_id. return np.array([self._current_clip_index]) def get_all_reference_observations(self, physics: 'mjcf.Physics'): reference_observations = dict() reference_observations[ 'walker/reference_rel_bodies_pos_local'] = self.get_reference_rel_bodies_pos_local( physics) reference_observations[ 'walker/reference_rel_joints'] = self.get_reference_rel_joints(physics) reference_observations[ 'walker/reference_rel_bodies_pos_global'] = self.get_reference_rel_bodies_pos_global( physics) reference_observations[ 'walker/reference_ego_bodies_quats'] = self.get_reference_ego_bodies_quats( physics) reference_observations[ 'walker/reference_rel_root_quat'] = self.get_reference_rel_root_quat( physics) reference_observations[ 'walker/reference_rel_bodies_quats'] = self.get_reference_rel_bodies_quats( physics) reference_observations[ 'walker/reference_rel_root_pos_local'] = self.get_reference_rel_root_pos_local( physics) if self._props: reference_observations[ 'props/reference_pos_global'] = self.get_reference_props_pos_global( physics) reference_observations[ 'props/reference_quat_global'] = self.get_reference_props_quat_global( physics) return reference_observations def get_reward(self, physics: 'mjcf.Physics') -> float: reward, unused_debug_outputs, reward_channels = self._reward_fn( termination_error=self._termination_error, termination_error_threshold=self._termination_error_threshold, reference_features=self._current_reference_features, walker_features=self._walker_features, reference_observations=self._reference_observations) if 'actuator_force' in self._reward_keys: reward_channels['actuator_force'] = -self._actuator_force_coeff*np.mean( np.square(self._walker.actuator_force(physics))) self._should_truncate = self._termination_error > self._termination_error_threshold if self._props: prop_termination = self._prop_termination_error > self._prop_termination_error_threshold self._should_truncate = self._should_truncate or prop_termination self.last_reward_channels = reward_channels return reward def _set_walker(self, physics: 'mjcf.Physics'): timestep_features = tree.map_structure(lambda x: x[self._time_step], self._clip_reference_features) utils.set_walker_from_features(physics, self._walker, timestep_features) if self._props: utils.set_props_from_features(physics, self._props, timestep_features) mjlib.mj_kinematics(physics.model.ptr, physics.data.ptr) def _update_ghost(self, physics: 'mjcf.Physics'): if self._ghost_offset is not None: target = tree.map_structure(lambda x: x[self._time_step], self._clip_reference_features) utils.set_walker_from_features(physics, self._ghost, target, self._ghost_offset) if self._ghost_props: utils.set_props_from_features( physics, self._ghost_props, target, z_offset=self._ghost_offset) mjlib.mj_kinematics(physics.model.ptr, physics.data.ptr) def action_spec(self, physics: 'mjcf.Physics'): """Action spec of the walker only.""" ctrl = physics.bind(self._walker.actuators).ctrl # pytype: disable=attribute-error shape = ctrl.shape dtype = ctrl.dtype minimum = [] maximum = [] for actuator in self._walker.actuators: if physics.bind(actuator).ctrllimited: # pytype: disable=attribute-error ctrlrange = physics.bind(actuator).ctrlrange # pytype: disable=attribute-error minimum.append(ctrlrange[0]) maximum.append(ctrlrange[1]) else: minimum.append(-float('inf')) maximum.append(float('inf')) return specs.BoundedArray( shape=shape, dtype=dtype, minimum=np.asarray(minimum, dtype=dtype), maximum=np.asarray(maximum, dtype=dtype), name='\t'.join(actuator.full_identifier # pytype: disable=attribute-error for actuator in self._walker.actuators)) @property @abc.abstractmethod def name(self): raise NotImplementedError @property def root_entity(self): return self._arena class MultiClipMocapTracking(ReferencePosesTask): """Task for multi-clip mocap tracking.""" def __init__( self, walker: Callable[..., 'legacy_base.Walker'], arena: composer.Arena, ref_path: Text, ref_steps: Sequence[int], dataset: Union[Text, Sequence[Any]], termination_error_threshold: float = 0.3, prop_termination_error_threshold: float = 0.1, min_steps: int = 10, reward_type: Text = 'termination_reward', physics_timestep: float = DEFAULT_PHYSICS_TIMESTEP, always_init_at_clip_start: bool = False, proto_modifier: Optional[Any] = None, prop_factory: Optional[Any] = None, disable_props: bool = True, ghost_offset: Optional[Sequence[Union[int, float]]] = None, body_error_multiplier: Union[int, float] = 1.0, actuator_force_coeff: float = 0.015, enabled_reference_observables: Optional[Sequence[Text]] = None, ): """Mocap tracking task. Args: walker: Walker constructor to be used. arena: Arena to be used. ref_path: Path to the dataset containing reference poses. ref_steps: tuples of indices of reference observation. E.g if ref_steps=(1, 2, 3) the walker/reference observation at time t will contain information from t+1, t+2, t+3. dataset: dataset: A ClipCollection instance or a named dataset that appears as a key in DATASETS in datasets.py termination_error_threshold: Error threshold for episode terminations for hand body position and joint error only. prop_termination_error_threshold: Error threshold for episode terminations for prop position. min_steps: minimum number of steps within an episode. This argument determines the latest allowable starting point within a given reference trajectory. reward_type: type of reward to use, must be a string that appears as a key in the REWARD_FN dict in rewards.py. physics_timestep: Physics timestep to use for simulation. always_init_at_clip_start: only initialize epsidodes at the start of a reference trajectory. proto_modifier: Optional proto modifier to modify reference trajectories, e.g. adding a vertical offset. prop_factory: Optional function that takes the mocap proto and returns the corresponding props for the trajectory. disable_props: If prop_factory is specified but disable_props is True, no props will be created. ghost_offset: if not None, include a ghost rendering of the walker with the reference pose at the specified position offset. body_error_multiplier: A multiplier that is applied to the body error term when determining failure termination condition. actuator_force_coeff: A coefficient for the actuator force reward channel. enabled_reference_observables: Optional iterable of enabled observables. If not specified, a reasonable default set will be enabled. """ super().__init__( walker=walker, arena=arena, ref_path=ref_path, ref_steps=ref_steps, termination_error_threshold=termination_error_threshold, prop_termination_error_threshold=prop_termination_error_threshold, min_steps=min_steps, dataset=dataset, reward_type=reward_type, physics_timestep=physics_timestep, always_init_at_clip_start=always_init_at_clip_start, proto_modifier=proto_modifier, prop_factory=prop_factory, disable_props=disable_props, ghost_offset=ghost_offset, body_error_multiplier=body_error_multiplier, actuator_force_coeff=actuator_force_coeff, enabled_reference_observables=enabled_reference_observables) self._walker.observables.add_observable( 'time_in_clip', base_observable.Generic(self.get_normalized_time_in_clip)) def after_step(self, physics: 'mjcf.Physics', random_state): """Update the data after step.""" super().after_step(physics, random_state) self._time_step += 1 # Update the walker's data for this timestep. self._walker_features = utils.get_features( physics, self._walker, props=self._props) # features for default error self._walker_joints = np.array(physics.bind(self._walker.mocap_joints).qpos) # pytype: disable=attribute-error self._current_reference_features = { k: v[self._time_step].copy() for k, v in self._clip_reference_features.items() } # Error. self._compute_termination_error() # Terminate based on the error. self._end_mocap = self._time_step == self._last_step self._reference_observations.update( self.get_all_reference_observations(physics)) self._update_ghost(physics) def get_normalized_time_in_clip(self, physics: 'mjcf.Physics'): """Observation of the normalized time in the mocap clip.""" normalized_time_in_clip = (self._current_start_time + physics.time()) / self._current_clip.duration return np.array([normalized_time_in_clip]) @property def name(self): return 'MultiClipMocapTracking' class PlaybackTask(ReferencePosesTask): """Simple task to visualize mocap data.""" def __init__(self, walker, arena, ref_path: Text, dataset: Union[Text, types.ClipCollection], proto_modifier: Optional[Any] = None, physics_timestep=DEFAULT_PHYSICS_TIMESTEP): super().__init__(walker=walker, arena=arena, ref_path=ref_path, ref_steps=(1,), dataset=dataset, termination_error_threshold=np.inf, physics_timestep=physics_timestep, always_init_at_clip_start=True, proto_modifier=proto_modifier) self._current_clip_index = -1 def _get_clip_to_track(self, random_state: np.random.RandomState): self._current_clip_index = (self._current_clip_index + 1) % self._num_clips start_step = self._dataset.start_steps[self._current_clip_index] clip_id = self._dataset.ids[self._current_clip_index] logging.info('Showing clip %d of %d, clip id %s', self._current_clip_index+1, self._num_clips, clip_id) if self._all_clips[self._current_clip_index] is None: # fetch selected trajectory logging.info('Loading clip %s', clip_id) self._all_clips[self._current_clip_index] = self._loader.get_trajectory( clip_id, start_step=self._dataset.start_steps[self._current_clip_index], end_step=self._dataset.end_steps[self._current_clip_index], zero_out_velocities=False) self._current_clip = self._all_clips[self._current_clip_index] self._clip_reference_features = self._current_clip.as_dict() self._clip_reference_features = _strip_reference_prefix( self._clip_reference_features, 'walker/') # The reference features are already restricted to # clip_start_step:clip_end_step. However start_step is in # [clip_start_step:clip_end_step]. Hence we subtract clip_start_step to # obtain a valid index for the reference features. self._time_step = start_step - self._dataset.start_steps[ self._current_clip_index] self._current_start_time = (start_step - self._dataset.start_steps[ self._current_clip_index]) * self._current_clip.dt self._last_step = len( self._clip_reference_features['joints']) - self._max_ref_step - 1 logging.info('Mocap %s at step %d with remaining length %d.', clip_id, start_step, self._last_step - start_step) def _set_walker(self, physics: 'mjcf.Physics'): timestep_features = tree.map_structure(lambda x: x[self._time_step], self._clip_reference_features) utils.set_walker_from_features(physics, self._walker, timestep_features) mjlib.mj_kinematics(physics.model.ptr, physics.data.ptr) def after_step(self, physics, random_state: np.random.RandomState): super().after_step(physics, random_state) self._time_step += 1 self._set_walker(physics) self._end_mocap = self._time_step == self._last_step def get_reward(self, physics): return 0.0 @property def name(self): return 'PlaybackTask'
dm_control-main
dm_control/locomotion/tasks/reference_pose/tracking.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 mocap tracking.""" import os from absl.testing import absltest from absl.testing import parameterized from dm_control import composer from dm_control.locomotion import arenas from dm_control.locomotion import walkers from dm_control.locomotion.mocap import props from dm_control.locomotion.tasks.reference_pose import tracking from dm_control.locomotion.tasks.reference_pose import types import numpy as np from dm_control.utils import io as resources TEST_FILE_DIR = os.path.normpath(os.path.join(os.path.dirname(__file__), '../../mocap')) TEST_FILE_PATH = os.path.join(TEST_FILE_DIR, 'test_trajectories.h5') REFERENCE_PROP_KEYS = [ f'reference_props_{key}_global' for key in ['pos', 'quat'] ] PROP_OBSERVATION_KEYS = [ f'cmuv2019_box/{key}' for key in ['position', 'orientation'] ] N_PROPS = 1 GHOST_OFFSET = np.array((0, 0, 0.1)) class MultiClipMocapTrackingTest(parameterized.TestCase): def setUp(self): super().setUp() self.walker = walkers.CMUHumanoidPositionControlled def _make_wrong_walker(name): return walkers.CMUHumanoidPositionControlled( include_face=False, model_version='2020', scale_default=True, name=name) self.wrong_walker = _make_wrong_walker self.arena = arenas.Floor() self.test_data = resources.GetResourceFilename(TEST_FILE_PATH) @parameterized.named_parameters(('termination_reward', 'termination_reward'), ('comic', 'comic')) def test_initialization_and_step(self, reward): task = tracking.MultiClipMocapTracking( walker=self.walker, arena=self.arena, ref_path=self.test_data, dataset=types.ClipCollection(ids=('cmuv2019_001', 'cmuv2019_002')), ref_steps=(1, 2, 3, 4, 5), min_steps=1, reward_type=reward, ) env = composer.Environment(task=task) env.reset() # check no task error after episode init before first step self.assertLess(task._termination_error, 1e-3) action_spec = env.action_spec() env.step(np.zeros(action_spec.shape)) @parameterized.named_parameters(('first_clip', 0), ('second_clip', 1)) def test_clip_weights(self, clip_number): # test whether clip weights work correctly if ids are not specified. clip_weights = (1, 0) if clip_number == 0 else (0, 1) task = tracking.MultiClipMocapTracking( walker=self.walker, arena=self.arena, ref_path=self.test_data, ref_steps=(1, 2, 3, 4, 5), min_steps=1, dataset=types.ClipCollection( ids=('cmuv2019_001', 'cmuv2019_002'), weights=clip_weights), reward_type='comic', ) env = composer.Environment(task=task) env.reset() self.assertEqual(task._current_clip.identifier, task._dataset.ids[clip_number]) @parameterized.named_parameters( ('start_step_id_length_mismatch_explicit_id', (0,), (10, 10), (1, 1)), ('end_step_id_length_mismatch_explicit_id', (0, 0), (10,), (1, 1)), ('clip_weights_id_length_mismatch_explicit_id', (0, 0), (10, 10), (1,)), ) def test_task_validation(self, clip_start_steps, clip_end_steps, clip_weights): # test whether task construction fails with invalid arguments. with self.assertRaisesRegex(ValueError, 'ClipCollection'): unused_task = tracking.MultiClipMocapTracking( walker=self.walker, arena=self.arena, ref_path=self.test_data, ref_steps=(1, 2, 3, 4, 5), min_steps=1, dataset=types.ClipCollection( ids=('cmuv2019_001', 'cmuv2019_002'), start_steps=clip_start_steps, end_steps=clip_end_steps, weights=clip_weights), reward_type='comic', ) def test_init_at_clip_start(self): task = tracking.MultiClipMocapTracking( walker=self.walker, arena=self.arena, ref_path=self.test_data, dataset=types.ClipCollection( ids=('cmuv2019_001', 'cmuv2019_002'), start_steps=(2, 0), end_steps=(10, 10)), ref_steps=(1, 2, 3, 4, 5), min_steps=1, reward_type='termination_reward', always_init_at_clip_start=True, ) self.assertEqual(task._possible_starts, [(0, 2), (1, 0)]) def test_failure_with_wrong_walker(self): with self.assertRaisesRegex(ValueError, 'proto/walker'): task = tracking.MultiClipMocapTracking( walker=self.wrong_walker, arena=self.arena, ref_path=self.test_data, ref_steps=(1, 2, 3, 4, 5), min_steps=1, dataset=types.ClipCollection( ids=('cmuv2019_001', 'cmuv2019_002'), start_steps=(0, 0), end_steps=(10, 10)), reward_type='comic', ) env = composer.Environment(task=task) env.reset() def test_enabled_reference_observables(self): task = tracking.MultiClipMocapTracking( walker=self.walker, arena=self.arena, ref_path=self.test_data, dataset=types.ClipCollection(ids=('cmuv2019_001', 'cmuv2019_002')), ref_steps=(1, 2, 3, 4, 5), min_steps=1, reward_type='comic', enabled_reference_observables=('walker/reference_rel_joints',) ) env = composer.Environment(task=task) timestep = env.reset() self.assertIn('walker/reference_rel_joints', timestep.observation.keys()) self.assertNotIn('walker/reference_rel_root_pos_local', timestep.observation.keys()) # check that all desired observables are enabled. desired_observables = [] desired_observables += task._walker.observables.proprioception desired_observables += task._walker.observables.kinematic_sensors desired_observables += task._walker.observables.dynamic_sensors for observable in desired_observables: self.assertTrue(observable.enabled) def test_prop_factory(self): task = tracking.MultiClipMocapTracking( walker=self.walker, arena=self.arena, ref_path=self.test_data, dataset=types.ClipCollection(ids=('cmuv2019_001', 'cmuv2019_002')), ref_steps=(0,), min_steps=1, disable_props=False, prop_factory=props.Prop, ) env = composer.Environment(task=task) observation = env.reset().observation # Test the expected prop observations exist and have the expected size. dims = [3, 4] for key, dim in zip(REFERENCE_PROP_KEYS, dims): self.assertIn(key, task.observables) self.assertSequenceEqual(observation[key].shape, (N_PROPS, dim)) # Since no ghost offset was specified, test that there are no ghost props. self.assertEmpty(task._ghost_props) # Test that props go to the expected location on reset. for ref_key, obs_key in zip(REFERENCE_PROP_KEYS, PROP_OBSERVATION_KEYS): np.testing.assert_array_equal(observation[ref_key], observation[obs_key]) def test_ghost_prop(self): task = tracking.MultiClipMocapTracking( walker=self.walker, arena=self.arena, ref_path=self.test_data, dataset=types.ClipCollection(ids=('cmuv2019_001', 'cmuv2019_002')), ref_steps=(0,), min_steps=1, disable_props=False, prop_factory=props.Prop, ghost_offset=GHOST_OFFSET, ) env = composer.Environment(task=task) # Test that the ghost props are present when ghost_offset specified. self.assertLen(task._ghost_props, N_PROPS) # Test that the ghost prop tracks the goal trajectory after step. env.reset() observation = env.step(env.action_spec().generate_value()).observation ghost_pos, ghost_quat = task._ghost_props[0].get_pose(env.physics) goal_pos, goal_quat = ( np.squeeze(observation[key]) for key in REFERENCE_PROP_KEYS) np.testing.assert_array_equal(np.array(ghost_pos), goal_pos + GHOST_OFFSET) np.testing.assert_array_equal(ghost_quat, goal_quat) def test_disable_props(self): task = tracking.MultiClipMocapTracking( walker=self.walker, arena=self.arena, ref_path=self.test_data, dataset=types.ClipCollection(ids=('cmuv2019_001', 'cmuv2019_002')), ref_steps=(0,), min_steps=1, prop_factory=props.Prop, disable_props=True, ) env = composer.Environment(task=task) observation = env.reset().observation # Test that the prop observations are empty. for key in REFERENCE_PROP_KEYS: self.assertIn(key, task.observables) self.assertSequenceEqual(observation[key].shape, (1, 0)) # Test that the props and ghost props are not constructed. self.assertEmpty(task._props) self.assertEmpty(task._ghost_props) def test_prop_termination(self): task = tracking.MultiClipMocapTracking( walker=self.walker, arena=self.arena, ref_path=self.test_data, dataset=types.ClipCollection(ids=('cmuv2019_001', 'cmuv2019_002')), ref_steps=(0,), min_steps=1, disable_props=False, prop_factory=props.Prop, ) env = composer.Environment(task=task) observation = env.reset().observation # Test that prop position contributes to prop termination error. task._set_walker(env.physics) wrong_position = observation[REFERENCE_PROP_KEYS[0]] + np.ones(3) task._props[0].set_pose(env.physics, wrong_position) task.after_step(env.physics, 0) task._compute_termination_error() self.assertGreater(task._prop_termination_error, 0.) task.get_reward(env.physics) self.assertEqual(task._should_truncate, True) def test_ghost_walker(self): task = tracking.MultiClipMocapTracking( walker=self.walker, arena=self.arena, ref_path=self.test_data, dataset=types.ClipCollection(ids=('cmuv2019_001', 'cmuv2019_002')), ref_steps=(0,), min_steps=1, ghost_offset=None, ) env = composer.Environment(task=task) task_with_ghost = tracking.MultiClipMocapTracking( walker=self.walker, arena=self.arena, ref_path=self.test_data, dataset=types.ClipCollection(ids=('cmuv2019_001', 'cmuv2019_002')), ref_steps=(0,), min_steps=1, ghost_offset=GHOST_OFFSET, ) env_with_ghost = composer.Environment(task=task_with_ghost) # Test that the ghost does not introduce additional actions. self.assertEqual(env_with_ghost.action_spec(), env.action_spec()) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/tasks/reference_pose/tracking_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. # ============================================================================ """A LabMaze square room where the outermost cells are always empty.""" import labmaze import numpy as np _PADDING = 4 class PaddedRoom(labmaze.BaseMaze): """A LabMaze square room where the outermost cells are always empty.""" def __init__(self, room_size, num_objects=0, random_state=None, pad_with_walls=True, num_agent_spawn_positions=1): self._room_size = room_size self._num_objects = num_objects self._num_agent_spawn_positions = num_agent_spawn_positions self._random_state = random_state or np.random empty_maze = '\n'.join(['.' * (room_size + _PADDING)] * (room_size + _PADDING) + ['']) self._entity_layer = labmaze.TextGrid(empty_maze) if pad_with_walls: self._entity_layer[0, :] = '*' self._entity_layer[-1, :] = '*' self._entity_layer[:, 0] = '*' self._entity_layer[:, -1] = '*' self._variations_layer = labmaze.TextGrid(empty_maze) def regenerate(self): self._entity_layer[1:-1, 1:-1] = ' ' self._variations_layer[:, :] = '.' generated = list( self._random_state.choice( self._room_size * self._room_size, self._num_objects + self._num_agent_spawn_positions, replace=False)) for i, obj in enumerate(generated): if i < self._num_agent_spawn_positions: token = labmaze.defaults.SPAWN_TOKEN else: token = labmaze.defaults.OBJECT_TOKEN obj_y, obj_x = obj // self._room_size, obj % self._room_size self._entity_layer[obj_y + int(_PADDING / 2), obj_x + int(_PADDING / 2)] = token @property def entity_layer(self): return self._entity_layer @property def variations_layer(self): return self._variations_layer @property def width(self): return self._room_size + _PADDING @property def height(self): return self._room_size + _PADDING
dm_control-main
dm_control/locomotion/arenas/padded_room.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 locomotion.arenas.bowl.""" from absl.testing import absltest from dm_control import mjcf from dm_control.locomotion.arenas import bowl class BowlTest(absltest.TestCase): def test_can_compile_mjcf(self): arena = bowl.Bowl() mjcf.Physics.from_mjcf_model(arena.mjcf_model) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/arenas/bowl_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 locomotion.arenas.corridors.""" from absl.testing import absltest from absl.testing import parameterized from dm_control import mjcf from dm_control.composer.variation import deterministic from dm_control.locomotion.arenas import corridors class CorridorsTest(parameterized.TestCase): @parameterized.parameters([ corridors.EmptyCorridor, corridors.GapsCorridor, corridors.WallsCorridor, ]) def test_can_compile_mjcf(self, arena_type): arena = arena_type() mjcf.Physics.from_mjcf_model(arena.mjcf_model) @parameterized.parameters([ corridors.EmptyCorridor, corridors.GapsCorridor, corridors.WallsCorridor, ]) def test_can_regenerate_corridor_size(self, arena_type): width_sequence = [5.2, 3.8, 7.4] length_sequence = [21.1, 19.4, 16.3] arena = arena_type( corridor_width=deterministic.Sequence(width_sequence), corridor_length=deterministic.Sequence(length_sequence)) # Add a probe geom that will generate contacts with the side walls. probe_body = arena.mjcf_model.worldbody.add('body', name='probe') probe_joint = probe_body.add('freejoint') probe_geom = probe_body.add('geom', name='probe', type='box') for expected_width, expected_length in zip(width_sequence, length_sequence): # No random_state is required since we are using deterministic variations. arena.regenerate(random_state=None) def resize_probe_geom_and_assert_num_contacts( delta_size, expected_num_contacts, expected_width=expected_width, expected_length=expected_length): probe_geom.size = [ (expected_length / 2 + corridors._CORRIDOR_X_PADDING) + delta_size, expected_width / 2 + delta_size, 0.1] physics = mjcf.Physics.from_mjcf_model(arena.mjcf_model) probe_geomid = physics.bind(probe_geom).element_id physics.bind(probe_joint).qpos[:3] = [expected_length / 2, 0, 100] physics.forward() probe_contacts = [c for c in physics.data.contact if c.geom1 == probe_geomid or c.geom2 == probe_geomid] self.assertLen(probe_contacts, expected_num_contacts) epsilon = 1e-7 # If the probe geom is epsilon-smaller than the expected corridor size, # then we expect to detect no contact. resize_probe_geom_and_assert_num_contacts(-epsilon, 0) # If the probe geom is epsilon-larger than the expected corridor size, # then we expect to generate 4 contacts with each side wall, so 16 total. resize_probe_geom_and_assert_num_contacts(epsilon, 16) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/arenas/corridors_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. # ============================================================================ """LabMaze textures.""" from dm_control import composer from dm_control import mjcf from labmaze import assets as labmaze_assets class SkyBox(composer.Entity): """Represents a texture asset for the sky box.""" def _build(self, style): labmaze_textures = labmaze_assets.get_sky_texture_paths(style) self._mjcf_root = mjcf.RootElement(model='labmaze_' + style) self._texture = self._mjcf_root.asset.add( 'texture', type='skybox', name='texture', fileleft=labmaze_textures.left, fileright=labmaze_textures.right, fileup=labmaze_textures.up, filedown=labmaze_textures.down, filefront=labmaze_textures.front, fileback=labmaze_textures.back) @property def mjcf_model(self): return self._mjcf_root @property def texture(self): return self._texture class WallTextures(composer.Entity): """Represents wall texture assets.""" def _build(self, style): labmaze_textures = labmaze_assets.get_wall_texture_paths(style) self._mjcf_root = mjcf.RootElement(model='labmaze_' + style) self._textures = [] for texture_name, texture_path in labmaze_textures.items(): self._textures.append(self._mjcf_root.asset.add( 'texture', type='2d', name=texture_name, file=texture_path.format(texture_name))) @property def mjcf_model(self): return self._mjcf_root @property def textures(self): return self._textures class FloorTextures(composer.Entity): """Represents floor texture assets.""" def _build(self, style): labmaze_textures = labmaze_assets.get_floor_texture_paths(style) self._mjcf_root = mjcf.RootElement(model='labmaze_' + style) self._textures = [] for texture_name, texture_path in labmaze_textures.items(): self._textures.append(self._mjcf_root.asset.add( 'texture', type='2d', name=texture_name, file=texture_path.format(texture_name))) @property def mjcf_model(self): return self._mjcf_root @property def textures(self): return self._textures
dm_control-main
dm_control/locomotion/arenas/labmaze_textures.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 arenas.mazes.covering.""" from absl.testing import absltest from dm_control.locomotion.arenas import covering import labmaze import numpy as np _STRING_DTYPE = '|U1' class CoveringTest(absltest.TestCase): def testRandomMazes(self): maze = labmaze.RandomMaze(height=17, width=17, max_rooms=5, room_min_size=3, room_max_size=5, spawns_per_room=0, objects_per_room=0, random_seed=54321) for _ in range(1000): maze.regenerate() walls = covering.make_walls(maze.entity_layer) reconstructed = np.full(maze.entity_layer.shape, ' ', dtype=_STRING_DTYPE) for wall in walls: reconstructed[wall.start.y:wall.end.y, wall.start.x:wall.end.x] = '*' np.testing.assert_array_equal(reconstructed, maze.entity_layer) def testOddCovering(self): maze = labmaze.RandomMaze(height=17, width=17, max_rooms=5, room_min_size=3, room_max_size=5, spawns_per_room=0, objects_per_room=0, random_seed=54321) for _ in range(1000): maze.regenerate() walls = covering.make_walls(maze.entity_layer, make_odd_sized_walls=True) reconstructed = np.full(maze.entity_layer.shape, ' ', dtype=_STRING_DTYPE) for wall in walls: reconstructed[wall.start.y:wall.end.y, wall.start.x:wall.end.x] = '*' np.testing.assert_array_equal(reconstructed, maze.entity_layer) for wall in walls: self.assertEqual((wall.end.y - wall.start.y) % 2, 1) self.assertEqual((wall.end.x - wall.start.x) % 2, 1) def testNoOverlappingWalls(self): maze_string = """..** .*** .*** """.replace(' ', '') walls = covering.make_walls(labmaze.TextGrid(maze_string)) surface = 0 for wall in walls: size_x = wall.end.x - wall.start.x size_y = wall.end.y - wall.start.y surface += size_x * size_y self.assertEqual(surface, 8) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/arenas/covering_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. # ============================================================================ """Arenas for Locomotion tasks.""" from dm_control.locomotion.arenas.bowl import Bowl from dm_control.locomotion.arenas.corridors import EmptyCorridor from dm_control.locomotion.arenas.corridors import GapsCorridor from dm_control.locomotion.arenas.corridors import WallsCorridor from dm_control.locomotion.arenas.floors import Floor from dm_control.locomotion.arenas.labmaze_textures import FloorTextures from dm_control.locomotion.arenas.labmaze_textures import SkyBox from dm_control.locomotion.arenas.labmaze_textures import WallTextures from dm_control.locomotion.arenas.mazes import MazeWithTargets from dm_control.locomotion.arenas.mazes import RandomMazeWithTargets from dm_control.locomotion.arenas.padded_room import PaddedRoom
dm_control-main
dm_control/locomotion/arenas/__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. # ============================================================================ """Corridor-based arenas.""" import abc from dm_control import composer from dm_control.composer import variation from dm_control.locomotion.arenas import assets as locomotion_arenas_assets _SIDE_WALLS_GEOM_GROUP = 3 _CORRIDOR_X_PADDING = 2.0 _WALL_THICKNESS = 0.16 _SIDE_WALL_HEIGHT = 4.0 _DEFAULT_ALPHA = 0.5 class Corridor(composer.Arena, metaclass=abc.ABCMeta): """Abstract base class for corridor-type arenas.""" @abc.abstractmethod def regenerate(self, random_state): raise NotImplementedError @property @abc.abstractmethod def corridor_length(self): raise NotImplementedError @property @abc.abstractmethod def corridor_width(self): raise NotImplementedError @property @abc.abstractmethod def ground_geoms(self): raise NotImplementedError def is_at_target_position(self, position, tolerance=0.0): """Checks if a `position` is within `tolerance' of an end of the corridor. This can also be used to evaluate more complicated T-shaped or L-shaped corridors. Args: position: An iterable of 2 elements corresponding to the x and y location of the position to evaluate. tolerance: A `float` tolerance to use while evaluating the position. Returns: A `bool` indicating whether the `position` is within the `tolerance` of an end of the corridor. """ x, _ = position return x > self.corridor_length - tolerance class EmptyCorridor(Corridor): """An empty corridor with planes around the perimeter.""" def _build(self, corridor_width=4, corridor_length=40, visible_side_planes=True, name='empty_corridor'): """Builds the corridor. Args: corridor_width: A number or a `composer.variation.Variation` object that specifies the width of the corridor. corridor_length: A number or a `composer.variation.Variation` object that specifies the length of the corridor. visible_side_planes: Whether to the side planes that bound the corridor's perimeter should be rendered. name: The name of this arena. """ super()._build(name=name) self._corridor_width = corridor_width self._corridor_length = corridor_length self._walls_body = self._mjcf_root.worldbody.add('body', name='walls') self._mjcf_root.visual.map.znear = 0.0005 self._mjcf_root.asset.add( 'texture', type='skybox', builtin='gradient', rgb1=[0.4, 0.6, 0.8], rgb2=[0, 0, 0], width=100, height=600) self._mjcf_root.visual.headlight.set_attributes( ambient=[0.4, 0.4, 0.4], diffuse=[0.8, 0.8, 0.8], specular=[0.1, 0.1, 0.1]) alpha = _DEFAULT_ALPHA if visible_side_planes else 0.0 self._ground_plane = self._mjcf_root.worldbody.add( 'geom', type='plane', rgba=[0.5, 0.5, 0.5, 1], size=[1, 1, 1]) self._left_plane = self._mjcf_root.worldbody.add( 'geom', type='plane', xyaxes=[1, 0, 0, 0, 0, 1], size=[1, 1, 1], rgba=[1, 0, 0, alpha], group=_SIDE_WALLS_GEOM_GROUP) self._right_plane = self._mjcf_root.worldbody.add( 'geom', type='plane', xyaxes=[-1, 0, 0, 0, 0, 1], size=[1, 1, 1], rgba=[1, 0, 0, alpha], group=_SIDE_WALLS_GEOM_GROUP) self._near_plane = self._mjcf_root.worldbody.add( 'geom', type='plane', xyaxes=[0, 1, 0, 0, 0, 1], size=[1, 1, 1], rgba=[1, 0, 0, alpha], group=_SIDE_WALLS_GEOM_GROUP) self._far_plane = self._mjcf_root.worldbody.add( 'geom', type='plane', xyaxes=[0, -1, 0, 0, 0, 1], size=[1, 1, 1], rgba=[1, 0, 0, alpha], group=_SIDE_WALLS_GEOM_GROUP) self._current_corridor_length = None self._current_corridor_width = None def regenerate(self, random_state): """Regenerates this corridor. New values are drawn from the `corridor_width` and `corridor_height` distributions specified in `_build`. The corridor is resized accordingly. Args: random_state: A `numpy.random.RandomState` object that is passed to the `Variation` objects. """ self._walls_body.geom.clear() corridor_width = variation.evaluate(self._corridor_width, random_state=random_state) corridor_length = variation.evaluate(self._corridor_length, random_state=random_state) self._current_corridor_length = corridor_length self._current_corridor_width = corridor_width self._ground_plane.pos = [corridor_length / 2, 0, 0] self._ground_plane.size = [ corridor_length / 2 + _CORRIDOR_X_PADDING, corridor_width / 2, 1] self._left_plane.pos = [ corridor_length / 2, corridor_width / 2, _SIDE_WALL_HEIGHT / 2] self._left_plane.size = [ corridor_length / 2 + _CORRIDOR_X_PADDING, _SIDE_WALL_HEIGHT / 2, 1] self._right_plane.pos = [ corridor_length / 2, -corridor_width / 2, _SIDE_WALL_HEIGHT / 2] self._right_plane.size = [ corridor_length / 2 + _CORRIDOR_X_PADDING, _SIDE_WALL_HEIGHT / 2, 1] self._near_plane.pos = [ -_CORRIDOR_X_PADDING, 0, _SIDE_WALL_HEIGHT / 2] self._near_plane.size = [corridor_width / 2, _SIDE_WALL_HEIGHT / 2, 1] self._far_plane.pos = [ corridor_length + _CORRIDOR_X_PADDING, 0, _SIDE_WALL_HEIGHT / 2] self._far_plane.size = [corridor_width / 2, _SIDE_WALL_HEIGHT / 2, 1] @property def corridor_length(self): return self._current_corridor_length @property def corridor_width(self): return self._current_corridor_width @property def ground_geoms(self): return (self._ground_plane,) class GapsCorridor(EmptyCorridor): """A corridor that consists of multiple platforms separated by gaps.""" # pylint: disable=arguments-renamed def _build(self, platform_length=1., gap_length=2.5, corridor_width=4, corridor_length=40, ground_rgba=(0.5, 0.5, 0.5, 1), visible_side_planes=False, aesthetic='default', name='gaps_corridor'): """Builds the corridor. Args: platform_length: A number or a `composer.variation.Variation` object that specifies the size of the platforms along the corridor. gap_length: A number or a `composer.variation.Variation` object that specifies the size of the gaps along the corridor. corridor_width: A number or a `composer.variation.Variation` object that specifies the width of the corridor. corridor_length: A number or a `composer.variation.Variation` object that specifies the length of the corridor. ground_rgba: A sequence of 4 numbers or a `composer.variation.Variation` object specifying the color of the ground. visible_side_planes: Whether to the side planes that bound the corridor's perimeter should be rendered. aesthetic: option to adjust the material properties and skybox name: The name of this arena. """ super()._build( corridor_width=corridor_width, corridor_length=corridor_length, visible_side_planes=visible_side_planes, name=name) self._platform_length = platform_length self._gap_length = gap_length self._ground_rgba = ground_rgba self._aesthetic = aesthetic if self._aesthetic != 'default': ground_info = locomotion_arenas_assets.get_ground_texture_info(aesthetic) sky_info = locomotion_arenas_assets.get_sky_texture_info(aesthetic) texturedir = locomotion_arenas_assets.get_texturedir(aesthetic) self._mjcf_root.compiler.texturedir = texturedir self._ground_texture = self._mjcf_root.asset.add( 'texture', name='aesthetic_texture', file=ground_info.file, type=ground_info.type) self._ground_material = self._mjcf_root.asset.add( 'material', name='aesthetic_material', texture=self._ground_texture, texuniform='true') # remove existing skybox for texture in self._mjcf_root.asset.find_all('texture'): if texture.type == 'skybox': texture.remove() self._skybox = self._mjcf_root.asset.add( 'texture', name='aesthetic_skybox', file=sky_info.file, type='skybox', gridsize=sky_info.gridsize, gridlayout=sky_info.gridlayout) self._ground_body = self._mjcf_root.worldbody.add('body', name='ground') # pylint: enable=arguments-renamed def regenerate(self, random_state): """Regenerates this corridor. New values are drawn from the `corridor_width` and `corridor_height` distributions specified in `_build`. The corridor resized accordingly, and new sets of platforms are created according to values drawn from the `platform_length`, `gap_length`, and `ground_rgba` distributions specified in `_build`. Args: random_state: A `numpy.random.RandomState` object that is passed to the `Variation` objects. """ # Resize the entire corridor first. super().regenerate(random_state) # Move the ground plane down and make it invisible. self._ground_plane.pos = [self._current_corridor_length / 2, 0, -10] self._ground_plane.rgba = [0, 0, 0, 0] # Clear the existing platform pieces. self._ground_body.geom.clear() # Make the first platform larger. platform_length = 3. * _CORRIDOR_X_PADDING platform_pos = [ platform_length / 2, 0, -_WALL_THICKNESS, ] platform_size = [ platform_length / 2, self._current_corridor_width / 2, _WALL_THICKNESS, ] if self._aesthetic != 'default': self._ground_body.add( 'geom', type='box', name='start_floor', pos=platform_pos, size=platform_size, material=self._ground_material) else: self._ground_body.add( 'geom', type='box', rgba=variation.evaluate(self._ground_rgba, random_state), name='start_floor', pos=platform_pos, size=platform_size) current_x = platform_length platform_id = 0 while current_x < self._current_corridor_length: platform_length = variation.evaluate( self._platform_length, random_state=random_state) platform_pos = [ current_x + platform_length / 2., 0, -_WALL_THICKNESS, ] platform_size = [ platform_length / 2, self._current_corridor_width / 2, _WALL_THICKNESS, ] if self._aesthetic != 'default': self._ground_body.add( 'geom', type='box', name='floor_{}'.format(platform_id), pos=platform_pos, size=platform_size, material=self._ground_material) else: self._ground_body.add( 'geom', type='box', rgba=variation.evaluate(self._ground_rgba, random_state), name='floor_{}'.format(platform_id), pos=platform_pos, size=platform_size) platform_id += 1 # Move x to start of the next platform. current_x += platform_length + variation.evaluate( self._gap_length, random_state=random_state) @property def ground_geoms(self): return (self._ground_plane,) + tuple(self._ground_body.find_all('geom')) class WallsCorridor(EmptyCorridor): """A corridor obstructed by multiple walls aligned against the two sides.""" # pylint: disable=arguments-renamed def _build(self, wall_gap=2.5, wall_width=2.5, wall_height=2.0, swap_wall_side=True, wall_rgba=(1, 1, 1, 1), corridor_width=4, corridor_length=40, visible_side_planes=False, include_initial_padding=True, name='walls_corridor'): """Builds the corridor. Args: wall_gap: A number or a `composer.variation.Variation` object that specifies the gap between each consecutive pair obstructing walls. wall_width: A number or a `composer.variation.Variation` object that specifies the width that the obstructing walls extend into the corridor. wall_height: A number or a `composer.variation.Variation` object that specifies the height of the obstructing walls. swap_wall_side: A boolean or a `composer.variation.Variation` object that specifies whether the next obstructing wall should be aligned against the opposite side of the corridor compared to the previous one. wall_rgba: A sequence of 4 numbers or a `composer.variation.Variation` object specifying the color of the walls. corridor_width: A number or a `composer.variation.Variation` object that specifies the width of the corridor. corridor_length: A number or a `composer.variation.Variation` object that specifies the length of the corridor. visible_side_planes: Whether to the side planes that bound the corridor's perimeter should be rendered. include_initial_padding: Whether to include initial offset before first obstacle. name: The name of this arena. """ super()._build( corridor_width=corridor_width, corridor_length=corridor_length, visible_side_planes=visible_side_planes, name=name) self._wall_height = wall_height self._wall_rgba = wall_rgba self._wall_gap = wall_gap self._wall_width = wall_width self._swap_wall_side = swap_wall_side self._include_initial_padding = include_initial_padding # pylint: enable=arguments-renamed def regenerate(self, random_state): """Regenerates this corridor. New values are drawn from the `corridor_width` and `corridor_height` distributions specified in `_build`. The corridor resized accordingly, and new sets of obstructing walls are created according to values drawn from the `wall_gap`, `wall_width`, `wall_height`, and `wall_rgba` distributions specified in `_build`. Args: random_state: A `numpy.random.RandomState` object that is passed to the `Variation` objects. """ super().regenerate(random_state) wall_x = variation.evaluate( self._wall_gap, random_state=random_state) - _CORRIDOR_X_PADDING if self._include_initial_padding: wall_x += 2*_CORRIDOR_X_PADDING wall_side = 0 wall_id = 0 while wall_x < self._current_corridor_length: wall_width = variation.evaluate( self._wall_width, random_state=random_state) wall_height = variation.evaluate( self._wall_height, random_state=random_state) wall_rgba = variation.evaluate(self._wall_rgba, random_state=random_state) if variation.evaluate(self._swap_wall_side, random_state=random_state): wall_side = 1 - wall_side wall_pos = [ wall_x, (2 * wall_side - 1) * (self._current_corridor_width - wall_width) / 2, wall_height / 2 ] wall_size = [_WALL_THICKNESS / 2, wall_width / 2, wall_height / 2] self._walls_body.add( 'geom', type='box', name='wall_{}'.format(wall_id), pos=wall_pos, size=wall_size, rgba=wall_rgba) wall_id += 1 wall_x += variation.evaluate(self._wall_gap, random_state=random_state) @property def ground_geoms(self): return (self._ground_plane,)
dm_control-main
dm_control/locomotion/arenas/corridors.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 locomotion.arenas.mazes.""" from absl.testing import absltest from dm_control import mjcf from dm_control.locomotion.arenas import labmaze_textures from dm_control.locomotion.arenas import mazes class MazesTest(absltest.TestCase): def test_can_compile_mjcf(self): # Set the wall and floor textures to match DMLab and set the skybox. 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) mjcf.Physics.from_mjcf_model(arena.mjcf_model) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/arenas/mazes_test.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. # ============================================================================ """Tests for locomotion.arenas.padded_room.""" from absl.testing import absltest from dm_control import mjcf from dm_control.locomotion.arenas import labmaze_textures from dm_control.locomotion.arenas import mazes from dm_control.locomotion.arenas import padded_room class PaddedRoomTest(absltest.TestCase): def test_can_compile_mjcf(self): # Set the wall and floor textures to match DMLab and set the skybox. 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 = padded_room.PaddedRoom(room_size=4, num_objects=2) arena = mazes.MazeWithTargets( maze=maze, skybox_texture=skybox_texture, wall_textures=wall_textures, floor_textures=floor_textures) mjcf.Physics.from_mjcf_model(arena.mjcf_model) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/arenas/padded_room_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. # ============================================================================ """Bowl arena with bumps.""" from dm_control import composer from dm_control.locomotion.arenas import assets as locomotion_arenas_assets from dm_control.mujoco.wrapper import mjbindings import numpy as np from scipy import ndimage mjlib = mjbindings.mjlib _TOP_CAMERA_DISTANCE = 100 _TOP_CAMERA_Y_PADDING_FACTOR = 1.1 # Constants related to terrain generation. _TERRAIN_SMOOTHNESS = .5 # 0.0: maximally bumpy; 1.0: completely smooth. _TERRAIN_BUMP_SCALE = .2 # Spatial scale of terrain bumps (in meters). class Bowl(composer.Arena): """A bowl arena with sinusoidal bumps.""" def _build(self, size=(10, 10), aesthetic='default', name='bowl'): super()._build(name=name) self._hfield = self._mjcf_root.asset.add( 'hfield', name='terrain', nrow=201, ncol=201, size=(6, 6, 0.5, 0.1)) if aesthetic != 'default': ground_info = locomotion_arenas_assets.get_ground_texture_info(aesthetic) sky_info = locomotion_arenas_assets.get_sky_texture_info(aesthetic) texturedir = locomotion_arenas_assets.get_texturedir(aesthetic) self._mjcf_root.compiler.texturedir = texturedir self._texture = self._mjcf_root.asset.add( 'texture', name='aesthetic_texture', file=ground_info.file, type=ground_info.type) self._material = self._mjcf_root.asset.add( 'material', name='aesthetic_material', texture=self._texture, texuniform='true') self._skybox = self._mjcf_root.asset.add( 'texture', name='aesthetic_skybox', file=sky_info.file, type='skybox', gridsize=sky_info.gridsize, gridlayout=sky_info.gridlayout) self._terrain_geom = self._mjcf_root.worldbody.add( 'geom', name='terrain', type='hfield', pos=(0, 0, -0.01), hfield='terrain', material=self._material) self._ground_geom = self._mjcf_root.worldbody.add( 'geom', type='plane', name='groundplane', size=list(size) + [0.5], material=self._material) else: self._terrain_geom = self._mjcf_root.worldbody.add( 'geom', name='terrain', type='hfield', rgba=(0.2, 0.3, 0.4, 1), pos=(0, 0, -0.01), hfield='terrain') self._ground_geom = self._mjcf_root.worldbody.add( 'geom', type='plane', name='groundplane', rgba=(0.2, 0.3, 0.4, 1), size=list(size) + [0.5]) self._mjcf_root.visual.headlight.set_attributes( ambient=[.4, .4, .4], diffuse=[.8, .8, .8], specular=[.1, .1, .1]) self._regenerate = True def regenerate(self, random_state): # regeneration of the bowl requires physics, so postponed to initialization. self._regenerate = True def initialize_episode(self, physics, random_state): if self._regenerate: self._regenerate = False # Get heightfield resolution, assert that it is square. res = physics.bind(self._hfield).nrow assert res == physics.bind(self._hfield).ncol # Sinusoidal bowl shape. row_grid, col_grid = np.ogrid[-1:1:res*1j, -1:1:res*1j] radius = np.clip(np.sqrt(col_grid**2 + row_grid**2), .1, 1) bowl_shape = .5 - np.cos(2*np.pi*radius)/2 # Random smooth bumps. terrain_size = 2 * physics.bind(self._hfield).size[0] bump_res = int(terrain_size / _TERRAIN_BUMP_SCALE) bumps = random_state.uniform(_TERRAIN_SMOOTHNESS, 1, (bump_res, bump_res)) smooth_bumps = ndimage.zoom(bumps, res / float(bump_res)) # Terrain is elementwise product. terrain = bowl_shape * smooth_bumps start_idx = physics.bind(self._hfield).adr physics.model.hfield_data[start_idx:start_idx+res**2] = terrain.ravel() # If we have a rendering context, we need to re-upload the modified # heightfield data. if physics.contexts: with physics.contexts.gl.make_current() as ctx: ctx.call(mjlib.mjr_uploadHField, physics.model.ptr, physics.contexts.mujoco.ptr, physics.bind(self._hfield).element_id) @property def ground_geoms(self): return (self._terrain_geom, self._ground_geom)
dm_control-main
dm_control/locomotion/arenas/bowl.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 locomotion.arenas.floors.""" from absl.testing import absltest from dm_control import mjcf from dm_control.locomotion.arenas import floors import numpy as np class FloorsTest(absltest.TestCase): def test_can_compile_mjcf(self): arena = floors.Floor() mjcf.Physics.from_mjcf_model(arena.mjcf_model) def test_size(self): floor_size = (12.9, 27.1) arena = floors.Floor(size=floor_size) self.assertEqual(tuple(arena.ground_geoms[0].size[:2]), floor_size) def test_top_camera(self): floor_width, floor_height = 12.9, 27.1 arena = floors.Floor(size=[floor_width, floor_height]) self.assertGreater(arena._top_camera_y_padding_factor, 1) np.testing.assert_array_equal(arena._top_camera.quat, (1, 0, 0, 0)) expected_camera_y = floor_height * arena._top_camera_y_padding_factor np.testing.assert_allclose( np.tan(np.deg2rad(arena._top_camera.fovy / 2)), expected_camera_y / arena._top_camera.pos[2]) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/arenas/floors_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. # ============================================================================ """Simple floor arenas.""" from dm_control import composer from dm_control.locomotion.arenas import assets as locomotion_arenas_assets import numpy as np _GROUNDPLANE_QUAD_SIZE = 0.25 class Floor(composer.Arena): """A simple floor arena with a checkered pattern.""" def _build(self, size=(8, 8), reflectance=.2, aesthetic='default', name='floor', top_camera_y_padding_factor=1.1, top_camera_distance=100): super()._build(name=name) self._size = size self._top_camera_y_padding_factor = top_camera_y_padding_factor self._top_camera_distance = top_camera_distance self._mjcf_root.visual.headlight.set_attributes( ambient=[.4, .4, .4], diffuse=[.8, .8, .8], specular=[.1, .1, .1]) if aesthetic != 'default': ground_info = locomotion_arenas_assets.get_ground_texture_info(aesthetic) sky_info = locomotion_arenas_assets.get_sky_texture_info(aesthetic) texturedir = locomotion_arenas_assets.get_texturedir(aesthetic) self._mjcf_root.compiler.texturedir = texturedir self._ground_texture = self._mjcf_root.asset.add( 'texture', name='aesthetic_texture', file=ground_info.file, type=ground_info.type) self._ground_material = self._mjcf_root.asset.add( 'material', name='aesthetic_material', texture=self._ground_texture, texuniform='true') self._skybox = self._mjcf_root.asset.add( 'texture', name='aesthetic_skybox', file=sky_info.file, type='skybox', gridsize=sky_info.gridsize, gridlayout=sky_info.gridlayout) else: self._ground_texture = self._mjcf_root.asset.add( 'texture', rgb1=[.2, .3, .4], rgb2=[.1, .2, .3], type='2d', builtin='checker', name='groundplane', width=200, height=200, mark='edge', markrgb=[0.8, 0.8, 0.8]) self._ground_material = self._mjcf_root.asset.add( 'material', name='groundplane', texrepeat=[2, 2], # Makes white squares exactly 1x1 length units. texuniform=True, reflectance=reflectance, texture=self._ground_texture) # Build groundplane. self._ground_geom = self._mjcf_root.worldbody.add( 'geom', type='plane', name='groundplane', material=self._ground_material, size=list(size) + [_GROUNDPLANE_QUAD_SIZE]) # Choose the FOV so that the floor always fits nicely within the frame # irrespective of actual floor size. fovy_radians = 2 * np.arctan2(top_camera_y_padding_factor * size[1], top_camera_distance) self._top_camera = self._mjcf_root.worldbody.add( 'camera', name='top_camera', pos=[0, 0, top_camera_distance], quat=[1, 0, 0, 0], fovy=np.rad2deg(fovy_radians)) @property def ground_geoms(self): return (self._ground_geom,) def regenerate(self, random_state): pass @property def size(self): return self._size
dm_control-main
dm_control/locomotion/arenas/floors.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. # ============================================================================ """Maze-based arenas.""" import string from absl import logging from dm_control import composer from dm_control.composer.observation import observable from dm_control.locomotion.arenas import assets as locomotion_arenas_assets from dm_control.locomotion.arenas import covering import labmaze import numpy as np # Put all "actual" wall geoms in a separate group since they are not rendered. _WALL_GEOM_GROUP = 3 _TOP_CAMERA_DISTANCE = 100 _TOP_CAMERA_Y_PADDING_FACTOR = 1.1 _DEFAULT_WALL_CHAR = '*' _DEFAULT_FLOOR_CHAR = '.' class MazeWithTargets(composer.Arena): """A 2D maze with target positions specified by a LabMaze-style text maze.""" def _build(self, maze, xy_scale=2.0, z_height=2.0, skybox_texture=None, wall_textures=None, floor_textures=None, aesthetic='default', name='maze'): """Initializes this maze arena. Args: maze: A `labmaze.BaseMaze` instance. xy_scale: The size of each maze cell in metres. z_height: The z-height of the maze in metres. skybox_texture: (optional) A `composer.Entity` that provides a texture asset for the skybox. wall_textures: (optional) Either a `composer.Entity` that provides texture assets for the maze walls, or a dict mapping printable characters to such Entities. In the former case, the maze walls are assumed to be represented by '*' in the maze's entity layer. In the latter case, the dict's keys specify the different characters that can be present in the maze's entity layer, and the dict's values are the corresponding texture providers. floor_textures: (optional) A `composer.Entity` that provides texture assets for the maze floor. Unlike with walls, we do not currently support per-variation floor texture. Instead, we sample textures from the same texture provider for each variation in the variations layer. aesthetic: option to adjust the material properties and skybox name: (optional) A string, the name of this arena. """ super()._build(name) self._maze = maze self._xy_scale = xy_scale self._z_height = z_height self._x_offset = (self._maze.width - 1) / 2 self._y_offset = (self._maze.height - 1) / 2 self._mjcf_root.default.geom.rgba = [1, 1, 1, 1] if aesthetic != 'default': sky_info = locomotion_arenas_assets.get_sky_texture_info(aesthetic) texturedir = locomotion_arenas_assets.get_texturedir(aesthetic) self._mjcf_root.compiler.texturedir = texturedir self._skybox = self._mjcf_root.asset.add( 'texture', name='aesthetic_skybox', file=sky_info.file, type='skybox', gridsize=sky_info.gridsize, gridlayout=sky_info.gridlayout) elif skybox_texture: self._skybox_texture = skybox_texture.texture self.attach(skybox_texture) else: self._skybox_texture = self._mjcf_root.asset.add( 'texture', type='skybox', name='skybox', builtin='gradient', rgb1=[.4, .6, .8], rgb2=[0, 0, 0], width=100, height=100) self._texturing_geom_names = [] self._texturing_material_names = [] if wall_textures: if isinstance(wall_textures, dict): for texture_provider in set(wall_textures.values()): self.attach(texture_provider) self._wall_textures = { wall_char: texture_provider.textures for wall_char, texture_provider in wall_textures.items() } else: self.attach(wall_textures) self._wall_textures = {_DEFAULT_WALL_CHAR: wall_textures.textures} else: self._wall_textures = {_DEFAULT_WALL_CHAR: [self._mjcf_root.asset.add( 'texture', type='2d', name='wall', builtin='flat', rgb1=[.8, .8, .8], width=100, height=100)]} if aesthetic != 'default': ground_info = locomotion_arenas_assets.get_ground_texture_info(aesthetic) self._floor_textures = [ self._mjcf_root.asset.add( 'texture', name='aesthetic_texture_main', file=ground_info.file, type=ground_info.type), self._mjcf_root.asset.add( 'texture', name='aesthetic_texture', file=ground_info.file, type=ground_info.type) ] elif floor_textures: self._floor_textures = floor_textures.textures self.attach(floor_textures) else: self._floor_textures = [self._mjcf_root.asset.add( 'texture', type='2d', name='floor', builtin='flat', rgb1=[.2, .2, .2], width=100, height=100)] ground_x = ((self._maze.width - 1) + 1) * (xy_scale / 2) ground_y = ((self._maze.height - 1) + 1) * (xy_scale / 2) self._mjcf_root.worldbody.add( 'geom', name='ground', type='plane', pos=[0, 0, 0], size=[ground_x, ground_y, 1], rgba=[0, 0, 0, 0]) self._maze_body = self._mjcf_root.worldbody.add('body', name='maze_body') self._mjcf_root.visual.map.znear = 0.0005 # Choose the FOV so that the maze always fits nicely within the frame # irrespective of actual maze size. maze_size = max(self._maze.width, self._maze.height) top_camera_fovy = (360 / np.pi) * np.arctan2( _TOP_CAMERA_Y_PADDING_FACTOR * maze_size * self._xy_scale / 2, _TOP_CAMERA_DISTANCE) self._top_camera = self._mjcf_root.worldbody.add( 'camera', name='top_camera', pos=[0, 0, _TOP_CAMERA_DISTANCE], zaxis=[0, 0, 1], fovy=top_camera_fovy) self._target_positions = () self._spawn_positions = () self._text_maze_regenerated_hook = None self._tile_geom_names = {} def _build_observables(self): return MazeObservables(self) @property def top_camera(self): return self._top_camera @property def xy_scale(self): return self._xy_scale @property def z_height(self): return self._z_height @property def maze(self): return self._maze @property def text_maze_regenerated_hook(self): """A callback that is executed after the LabMaze object is regenerated.""" return self._text_maze_modifier @text_maze_regenerated_hook.setter def text_maze_regenerated_hook(self, hook): self._text_maze_regenerated_hook = hook @property def target_positions(self): """A tuple of Cartesian target positions generated for the current maze.""" return self._target_positions @property def spawn_positions(self): """The Cartesian position at which the agent should be spawned.""" return self._spawn_positions @property def target_grid_positions(self): """A tuple of grid coordinates of targets generated for the current maze.""" return self._target_grid_positions @property def spawn_grid_positions(self): """The grid-coordinate position at which the agent should be spawned.""" return self._spawn_grid_positions def regenerate(self, random_state=np.random.RandomState()): """Generates a new maze layout.""" del random_state self._maze.regenerate() logging.debug('GENERATED MAZE:\n%s', self._maze.entity_layer) self._find_spawn_and_target_positions() if self._text_maze_regenerated_hook: self._text_maze_regenerated_hook() # Remove old texturing planes. for geom_name in self._texturing_geom_names: del self._mjcf_root.worldbody.geom[geom_name] self._texturing_geom_names = [] # Remove old texturing materials. for material_name in self._texturing_material_names: del self._mjcf_root.asset.material[material_name] self._texturing_material_names = [] # Remove old actual-wall geoms. self._maze_body.geom.clear() self._current_wall_texture = { wall_char: np.random.choice(wall_textures) for wall_char, wall_textures in self._wall_textures.items() } for wall_char in self._wall_textures: self._make_wall_geoms(wall_char) self._make_floor_variations() def _make_wall_geoms(self, wall_char): walls = covering.make_walls( self._maze.entity_layer, wall_char=wall_char, make_odd_sized_walls=True) for i, wall in enumerate(walls): wall_mid = covering.GridCoordinates( (wall.start.y + wall.end.y - 1) / 2, (wall.start.x + wall.end.x - 1) / 2) wall_pos = np.array([(wall_mid.x - self._x_offset) * self._xy_scale, -(wall_mid.y - self._y_offset) * self._xy_scale, self._z_height / 2]) wall_size = np.array([(wall.end.x - wall_mid.x - 0.5) * self._xy_scale, (wall.end.y - wall_mid.y - 0.5) * self._xy_scale, self._z_height / 2]) self._maze_body.add('geom', name='wall{}_{}'.format(wall_char, i), type='box', pos=wall_pos, size=wall_size, group=_WALL_GEOM_GROUP) self._make_wall_texturing_planes(wall_char, i, wall_pos, wall_size) def _make_wall_texturing_planes(self, wall_char, wall_id, wall_pos, wall_size): xyaxes = { 'x': {-1: [0, -1, 0, 0, 0, 1], 1: [0, 1, 0, 0, 0, 1]}, 'y': {-1: [1, 0, 0, 0, 0, 1], 1: [-1, 0, 0, 0, 0, 1]}, 'z': {-1: [-1, 0, 0, 0, 1, 0], 1: [1, 0, 0, 0, 1, 0]} } for direction_index, direction in enumerate(('x', 'y', 'z')): index = list(i for i in range(3) if i != direction_index) delta_vector = np.array([int(i == direction_index) for i in range(3)]) material_name = 'wall{}_{}_{}'.format(wall_char, wall_id, direction) self._texturing_material_names.append(material_name) mat = self._mjcf_root.asset.add( 'material', name=material_name, texture=self._current_wall_texture[wall_char], texrepeat=(2 * wall_size[index] / self._xy_scale)) for sign, sign_name in zip((-1, 1), ('neg', 'pos')): if direction == 'z' and sign == -1: continue geom_name = ( 'wall{}_{}_texturing_{}_{}'.format( wall_char, wall_id, sign_name, direction)) self._texturing_geom_names.append(geom_name) self._mjcf_root.worldbody.add( 'geom', type='plane', name=geom_name, pos=(wall_pos + sign * delta_vector * wall_size), size=np.concatenate([wall_size[index], [self._xy_scale]]), xyaxes=xyaxes[direction][sign], material=mat, contype=0, conaffinity=0) def _make_floor_variations(self, build_tile_geoms_fn=None): """Builds the floor tiles. Args: build_tile_geoms_fn: An optional callable returning floor tile geoms. If not passed, the floor will be built using a default covering method. Takes a kwarg `wall_char` that can be used control how active floor tiles are selected. """ main_floor_texture = np.random.choice(self._floor_textures) for variation in _DEFAULT_FLOOR_CHAR + string.ascii_uppercase: if variation not in self._maze.variations_layer: break if build_tile_geoms_fn is None: # Break the floor variation down to odd-sized tiles. tiles = covering.make_walls(self._maze.variations_layer, wall_char=variation, make_odd_sized_walls=True) else: tiles = build_tile_geoms_fn(wall_char=variation) # Sample a texture that's not the same as the main floor texture. variation_texture = main_floor_texture if variation != _DEFAULT_FLOOR_CHAR: if len(self._floor_textures) == 1: return else: while variation_texture is main_floor_texture: variation_texture = np.random.choice(self._floor_textures) for i, tile in enumerate(tiles): tile_mid = covering.GridCoordinates( (tile.start.y + tile.end.y - 1) / 2, (tile.start.x + tile.end.x - 1) / 2) tile_pos = np.array([(tile_mid.x - self._x_offset) * self._xy_scale, -(tile_mid.y - self._y_offset) * self._xy_scale, 0.0]) tile_size = np.array([(tile.end.x - tile_mid.x - 0.5) * self._xy_scale, (tile.end.y - tile_mid.y - 0.5) * self._xy_scale, self._xy_scale]) if variation == _DEFAULT_FLOOR_CHAR: tile_name = 'floor_{}'.format(i) else: tile_name = 'floor_{}_{}'.format(variation, i) self._tile_geom_names[tile.start] = tile_name self._texturing_material_names.append(tile_name) self._texturing_geom_names.append(tile_name) material = self._mjcf_root.asset.add( 'material', name=tile_name, texture=variation_texture, texrepeat=(2 * tile_size[[0, 1]] / self._xy_scale)) self._mjcf_root.worldbody.add( 'geom', name=tile_name, type='plane', material=material, pos=tile_pos, size=tile_size, contype=0, conaffinity=0) @property def ground_geoms(self): return tuple([ geom for geom in self.mjcf_model.find_all('geom') if 'ground' in geom.name ]) def find_token_grid_positions(self, tokens): out = {token: [] for token in tokens} for y in range(self._maze.entity_layer.shape[0]): for x in range(self._maze.entity_layer.shape[1]): for token in tokens: if self._maze.entity_layer[y, x] == token: out[token].append((y, x)) return out def grid_to_world_positions(self, grid_positions): out = [] for y, x in grid_positions: out.append(np.array([(x - self._x_offset) * self._xy_scale, -(y - self._y_offset) * self._xy_scale, 0.0])) return out def world_to_grid_positions(self, world_positions): out = [] # the order of x, y is reverse between grid positions format and # world positions format. for x, y, _ in world_positions: out.append(np.array([self._y_offset - y / self._xy_scale, self._x_offset + x / self._xy_scale])) return out def _find_spawn_and_target_positions(self): grid_positions = self.find_token_grid_positions([ labmaze.defaults.OBJECT_TOKEN, labmaze.defaults.SPAWN_TOKEN]) self._target_grid_positions = tuple( grid_positions[labmaze.defaults.OBJECT_TOKEN]) self._spawn_grid_positions = tuple( grid_positions[labmaze.defaults.SPAWN_TOKEN]) self._target_positions = tuple( self.grid_to_world_positions(self._target_grid_positions)) self._spawn_positions = tuple( self.grid_to_world_positions(self._spawn_grid_positions)) class MazeObservables(composer.Observables): @composer.observable def top_camera(self): return observable.MJCFCamera(self._entity.top_camera) class RandomMazeWithTargets(MazeWithTargets): """A randomly generated 2D maze with target positions.""" def _build(self, x_cells, y_cells, xy_scale=2.0, z_height=2.0, max_rooms=labmaze.defaults.MAX_ROOMS, room_min_size=labmaze.defaults.ROOM_MIN_SIZE, room_max_size=labmaze.defaults.ROOM_MAX_SIZE, spawns_per_room=labmaze.defaults.SPAWN_COUNT, targets_per_room=labmaze.defaults.OBJECT_COUNT, max_variations=labmaze.defaults.MAX_VARIATIONS, simplify=labmaze.defaults.SIMPLIFY, skybox_texture=None, wall_textures=None, floor_textures=None, aesthetic='default', name='random_maze'): """Initializes this random maze arena. Args: x_cells: The number of cells along the x-direction of the maze. Must be an odd integer. y_cells: The number of cells along the y-direction of the maze. Must be an odd integer. xy_scale: The size of each maze cell in metres. z_height: The z-height of the maze in metres. max_rooms: (optional) The maximum number of rooms in each generated maze. room_min_size: (optional) The minimum size of each room generated. room_max_size: (optional) The maximum size of each room generated. spawns_per_room: (optional) Number of spawn points to generate in each room. targets_per_room: (optional) Number of targets to generate in each room. max_variations: (optional) Maximum number of variations to generate in the variations layer. simplify: (optional) flag to simplify the maze. skybox_texture: (optional) A `composer.Entity` that provides a texture asset for the skybox. wall_textures: (optional) A `composer.Entity` that provides texture assets for the maze walls. floor_textures: (optional) A `composer.Entity` that provides texture assets for the maze floor. aesthetic: option to adjust the material properties and skybox name: (optional) A string, the name of this arena. """ random_seed = np.random.randint(2147483648) # 2**31 super()._build( maze=labmaze.RandomMaze( height=y_cells, width=x_cells, max_rooms=max_rooms, room_min_size=room_min_size, room_max_size=room_max_size, max_variations=max_variations, spawns_per_room=spawns_per_room, objects_per_room=targets_per_room, simplify=simplify, random_seed=random_seed), xy_scale=xy_scale, z_height=z_height, skybox_texture=skybox_texture, wall_textures=wall_textures, floor_textures=floor_textures, aesthetic=aesthetic, name=name)
dm_control-main
dm_control/locomotion/arenas/mazes.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. # ============================================================================ """Calculates a covering of text mazes with overlapping rectangular walls.""" import collections import numpy as np GridCoordinates = collections.namedtuple('GridCoordinates', ('y', 'x')) MazeWall = collections.namedtuple('MazeWall', ('start', 'end')) class _MazeWallCoveringContext: """Calculates a covering of text mazes with overlapping rectangular walls. This class uses a greedy algorithm to try and minimize the number of geoms generated to create a given maze. The solution is not guaranteed to be optimal, but in most cases should result in a significantly smaller number of geoms than if each cell were treated as an individual box. """ def __init__(self, text_maze, wall_char='*', make_odd_sized_walls=False): """Initializes this _MazeWallCoveringContext. Args: text_maze: A `labmaze.TextGrid` instance. wall_char: (optional) The character that signifies a wall. make_odd_sized_walls: (optional) A boolean, if `True` all wall sections generated span odd numbers of grid cells. This option exists primarily to appease MuJoCo's texture repeating algorithm. """ self._text_maze = text_maze self._wall_char = wall_char self._make_odd_sized_walls = make_odd_sized_walls self._covered = np.full(text_maze.shape, False, dtype=bool) self._maze_size = GridCoordinates(*text_maze.shape) self._next_start = GridCoordinates(0, 0) self._calculated = False self._walls = () def calculate(self): """Calculates a covering of text mazes with overlapping rectangular walls. Returns: A tuple of `MazeWall` objects, each describing the corners of a wall. """ if not self._calculated: self._calculated = True self._find_next_start() walls = [] while self._next_start.y < self._maze_size.y: walls.append(self._find_next_wall()) self._find_next_start() self._walls = tuple(walls) return self._walls def _find_next_start(self): """Moves `self._next_start` to the top-left corner of the next wall.""" for y in range(self._next_start.y, self._maze_size.y): start_x = self._next_start.x if y == self._next_start.y else 0 for x in range(start_x, self._maze_size.x): if self._text_maze[y, x] == self._wall_char and not self._covered[y, x]: self._next_start = GridCoordinates(y, x) return self._next_start = self._maze_size def _scan_row(self, row, start_col, end_col): """Scans a row of text maze to find the longest strip of wall.""" for col in range(start_col, end_col): if (self._text_maze[row, col] != self._wall_char or self._covered[row, col]): return col return end_col def _find_next_wall(self): """Finds the largest piece of rectangular wall at the current location. This function assumes that `self._next_start` is already at the top-left corner of the next piece of wall. Returns: A `MazeWall` named tuple representing the next piece of wall created. """ start = self._next_start x = self._maze_size.x end_x_for_rows = [] total_cells = [] for y in range(start.y, self._maze_size.y): x = self._scan_row(y, start.x, x) if x > start.x: if self._make_odd_sized_walls and (x - start.x) % 2 == 0: x -= 1 end_x_for_rows.append(x) total_cells.append((x - start.x) * (y - start.y + 1)) y += 1 else: break if not self._make_odd_sized_walls: end_y_offset = total_cells.index(max(total_cells)) else: end_y_offset = 2 * total_cells[::2].index(max(total_cells[::2])) end = GridCoordinates(start.y + end_y_offset + 1, end_x_for_rows[end_y_offset]) self._covered[start.y:end.y, start.x:end.x] = True self._next_start = GridCoordinates(start.y, end.x) return MazeWall(start, end) def make_walls(text_maze, wall_char='*', make_odd_sized_walls=False): """Calculates a covering of text mazes with overlapping rectangular walls. Args: text_maze: A `labmaze.TextMaze` instance. wall_char: (optional) The character that signifies a wall. make_odd_sized_walls: (optional) A boolean, if `True` all wall sections generated span odd numbers of grid cells. This option exists primarily to appease MuJoCo's texture repeating algorithm. Returns: A tuple of `MazeWall` objects, each describing the corners of a wall. """ wall_covering_context = _MazeWallCoveringContext( text_maze, wall_char=wall_char, make_odd_sized_walls=make_odd_sized_walls) return wall_covering_context.calculate()
dm_control-main
dm_control/locomotion/arenas/covering.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. # ============================================================================ """Locomotion texture assets.""" import collections import os import sys ROOT_DIR = '../locomotion/arenas/assets' def get_texturedir(style): return os.path.join(ROOT_DIR, style) SKY_STYLES = ('outdoor_natural') SkyBox = collections.namedtuple( 'SkyBox', ('file', 'gridsize', 'gridlayout')) def get_sky_texture_info(style): if style not in SKY_STYLES: raise ValueError('`style` should be one of {}: got {!r}'.format( SKY_STYLES, style)) return SkyBox(file='OutdoorSkybox2048.png', gridsize='3 4', gridlayout='.U..LFRB.D..') GROUND_STYLES = ('outdoor_natural') GroundTexture = collections.namedtuple( 'GroundTexture', ('file', 'type')) def get_ground_texture_info(style): if style not in GROUND_STYLES: raise ValueError('`style` should be one of {}: got {!r}'.format( GROUND_STYLES, style)) return GroundTexture( file='OutdoorGrassFloorD.png', type='2d')
dm_control-main
dm_control/locomotion/arenas/assets/__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 props.target_sphere.""" from absl.testing import absltest from dm_control import composer from dm_control.entities.props import primitive from dm_control.locomotion.arenas import floors from dm_control.locomotion.props import target_sphere class TargetSphereTest(absltest.TestCase): def testActivation(self): target_radius = 0.6 prop_radius = 0.1 target_height = 1 arena = floors.Floor() target = target_sphere.TargetSphere(radius=target_radius, height_above_ground=target_height) prop = primitive.Primitive(geom_type='sphere', size=[prop_radius]) arena.attach(target) arena.add_free_entity(prop) task = composer.NullTask(arena) task.initialize_episode = ( lambda physics, random_state: prop.set_pose(physics, [0, 0, 2])) env = composer.Environment(task) env.reset() max_activated_height = target_height + target_radius + prop_radius while env.physics.bind(prop.geom).xpos[2] > max_activated_height: self.assertFalse(target.activated) self.assertEqual(env.physics.bind(target.material).rgba[-1], 1) env.step([]) while env.physics.bind(prop.geom).xpos[2] > 0.2: self.assertTrue(target.activated) self.assertEqual(env.physics.bind(target.material).rgba[-1], 0) env.step([]) # Target should be reset when the environment is reset. env.reset() self.assertFalse(target.activated) self.assertEqual(env.physics.bind(target.material).rgba[-1], 1) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/props/target_sphere_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 non-colliding sphere that is activated through touch.""" from dm_control import composer from dm_control import mjcf class TargetSphere(composer.Entity): """A non-colliding sphere that is activated through touch. Once the target has been reached, it remains in the "activated" state for the remainder of the current episode. The target is automatically reset to "not activated" state at episode initialization time. """ def _build(self, radius=0.6, height_above_ground=1, rgb1=(0, 0.4, 0), rgb2=(0, 0.7, 0), specific_collision_geom_ids=None, name='target'): """Builds this target sphere. Args: radius: The radius (in meters) of this target sphere. height_above_ground: The height (in meters) of this target above ground. rgb1: A sequence of three floating point values between 0.0 and 1.0 (inclusive) representing the color of the first element in the stripe pattern of the target. rgb2: A sequence of three floating point values between 0.0 and 1.0 (inclusive) representing the color of the second element in the stripe pattern of the target. specific_collision_geom_ids: Only activate if collides with these geoms. name: The name of this entity. """ self._mjcf_root = mjcf.RootElement(model=name) self._texture = self._mjcf_root.asset.add( 'texture', name='target_sphere', type='cube', builtin='checker', rgb1=rgb1, rgb2=rgb2, width='100', height='100') self._material = self._mjcf_root.asset.add( 'material', name='target_sphere', texture=self._texture) self._geom = self._mjcf_root.worldbody.add( 'geom', type='sphere', name='geom', gap=2*radius, pos=[0, 0, height_above_ground], size=[radius], material=self._material) self._geom_id = -1 self._activated = False self._specific_collision_geom_ids = specific_collision_geom_ids @property def geom(self): return self._geom @property def material(self): return self._material @property def activated(self): """Whether this target has been reached during this episode.""" return self._activated def reset(self, physics): self._activated = False physics.bind(self._material).rgba[-1] = 1 @property def mjcf_model(self): return self._mjcf_root def initialize_episode_mjcf(self, unused_random_state): self._activated = False def _update_activation(self, physics): if not self._activated: for contact in physics.data.contact: if self._specific_collision_geom_ids: has_specific_collision = ( contact.geom1 in self._specific_collision_geom_ids or contact.geom2 in self._specific_collision_geom_ids) else: has_specific_collision = True if (has_specific_collision and self._geom_id in (contact.geom1, contact.geom2)): self._activated = True physics.bind(self._material).rgba[-1] = 0 def initialize_episode(self, physics, unused_random_state): self._geom_id = physics.model.name2id(self._geom.full_identifier, 'geom') self._update_activation(physics) def after_substep(self, physics, unused_random_state): self._update_activation(physics) class TargetSphereTwoTouch(composer.Entity): """A non-colliding sphere that is activated through touch. The target indicates if it has been touched at least once and touched at least twice this episode with a two-bit activated state tuple. It remains activated for the remainder of the current episode. The target is automatically reset at episode initialization. """ def _build(self, radius=0.6, height_above_ground=1, rgb_initial=((0, 0.4, 0), (0, 0.7, 0)), rgb_interval=((1., 1., .4), (0.7, 0.7, 0.)), rgb_final=((.4, 0.7, 1.), (0, 0.4, .7)), touch_debounce=.2, specific_collision_geom_ids=None, name='target'): """Builds this target sphere. Args: radius: The radius (in meters) of this target sphere. height_above_ground: The height (in meters) of this target above ground. rgb_initial: A tuple of two colors for the stripe pattern of the target. rgb_interval: A tuple of two colors for the stripe pattern of the target. rgb_final: A tuple of two colors for the stripe pattern of the target. touch_debounce: duration to not count second touch. specific_collision_geom_ids: Only activate if collides with these geoms. name: The name of this entity. """ self._mjcf_root = mjcf.RootElement(model=name) self._texture_initial = self._mjcf_root.asset.add( 'texture', name='target_sphere_init', type='cube', builtin='checker', rgb1=rgb_initial[0], rgb2=rgb_initial[1], width='100', height='100') self._texture_interval = self._mjcf_root.asset.add( 'texture', name='target_sphere_inter', type='cube', builtin='checker', rgb1=rgb_interval[0], rgb2=rgb_interval[1], width='100', height='100') self._texture_final = self._mjcf_root.asset.add( 'texture', name='target_sphere_final', type='cube', builtin='checker', rgb1=rgb_final[0], rgb2=rgb_final[1], width='100', height='100') self._material = self._mjcf_root.asset.add( 'material', name='target_sphere_init', texture=self._texture_initial) self._geom = self._mjcf_root.worldbody.add( 'geom', type='sphere', name='geom', gap=2*radius, pos=[0, 0, height_above_ground], size=[radius], material=self._material) self._geom_id = -1 self._touched_once = False self._touched_twice = False self._touch_debounce = touch_debounce self._specific_collision_geom_ids = specific_collision_geom_ids @property def geom(self): return self._geom @property def material(self): return self._material @property def activated(self): """Whether this target has been reached during this episode.""" return (self._touched_once, self._touched_twice) def reset(self, physics): self._touched_once = False self._touched_twice = False self._geom.material = self._material physics.bind(self._material).texid = physics.bind( self._texture_initial).element_id @property def mjcf_model(self): return self._mjcf_root def initialize_episode_mjcf(self, unused_random_state): self._touched_once = False self._touched_twice = False def _update_activation(self, physics): if not (self._touched_once and self._touched_twice): for contact in physics.data.contact: if self._specific_collision_geom_ids: has_specific_collision = ( contact.geom1 in self._specific_collision_geom_ids or contact.geom2 in self._specific_collision_geom_ids) else: has_specific_collision = True if (has_specific_collision and self._geom_id in (contact.geom1, contact.geom2)): if not self._touched_once: self._touched_once = True self._touch_time = physics.time() physics.bind(self._material).texid = physics.bind( self._texture_interval).element_id if self._touched_once and ( physics.time() > (self._touch_time + self._touch_debounce)): self._touched_twice = True physics.bind(self._material).texid = physics.bind( self._texture_final).element_id def initialize_episode(self, physics, unused_random_state): self._geom_id = physics.model.name2id(self._geom.full_identifier, 'geom') self._update_activation(physics) def after_substep(self, physics, unused_random_state): self._update_activation(physics)
dm_control-main
dm_control/locomotion/props/target_sphere.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. # ============================================================================ """Props for Locomotion tasks.""" from dm_control.locomotion.props.target_sphere import TargetSphere from dm_control.locomotion.props.target_sphere import TargetSphereTwoTouch
dm_control-main
dm_control/locomotion/props/__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. # ============================================================================ """A soccer ball that keeps track of ball-player contacts.""" import os from dm_control import mjcf from dm_control.entities import props import numpy as np from dm_control.utils import io as resources _ASSETS_PATH = os.path.join(os.path.dirname(__file__), 'assets', 'soccer_ball') # FIFA regulation parameters for a size 5 ball. _REGULATION_RADIUS = 0.117 # Meters. _REGULATION_MASS = 0.45 # Kilograms. _DEFAULT_FRICTION = (0.7, 0.05, 0.04) # (slide, spin, roll). _DEFAULT_DAMP_RATIO = 0.4 def _get_texture(name): contents = resources.GetResource( os.path.join(_ASSETS_PATH, '{}.png'.format(name))) return mjcf.Asset(contents, '.png') def regulation_soccer_ball(): return SoccerBall( radius=_REGULATION_RADIUS, mass=_REGULATION_MASS, friction=_DEFAULT_FRICTION, damp_ratio=_DEFAULT_DAMP_RATIO) class SoccerBall(props.Primitive): """A soccer ball that keeps track of entities that come into contact.""" def _build(self, radius=0.35, mass=0.045, friction=(0.7, 0.075, 0.075), damp_ratio=1.0, name='soccer_ball'): """Builds this soccer ball. Args: radius: The radius (in meters) of this target sphere. mass: Mass (in kilograms) of the ball. friction: Friction parameters of the ball geom with the three dimensions corresponding to (slide, spin, roll) frictions. damp_ratio: A real positive number. Lower implies less dampening upon contacts. name: The name of this entity. """ super()._build(geom_type='sphere', size=(radius,), name=name) texture = self._mjcf_root.asset.add( 'texture', name='soccer_ball', type='cube', fileup=_get_texture('up'), filedown=_get_texture('down'), filefront=_get_texture('front'), fileback=_get_texture('back'), fileleft=_get_texture('left'), fileright=_get_texture('right')) material = self._mjcf_root.asset.add( 'material', name='soccer_ball', texture=texture) if damp_ratio < 0.0: raise ValueError( f'Invalid `damp_ratio` parameter ({damp_ratio} is not positive).') self._geom.set_attributes( pos=[0, 0, radius], size=[radius], condim=6, priority=1, mass=mass, friction=friction, solref=[0.02, damp_ratio], material=material) # Add some tracking cameras for visualization and logging. self._mjcf_root.worldbody.add( 'camera', name='ball_cam_near', pos=[0, -2, 2], zaxis=[0, -1, 1], fovy=70, mode='trackcom') self._mjcf_root.worldbody.add( 'camera', name='ball_cam', pos=[0, -7, 7], zaxis=[0, -1, 1], fovy=70, mode='trackcom') self._mjcf_root.worldbody.add( 'camera', name='ball_cam_far', pos=[0, -10, 10], zaxis=[0, -1, 1], fovy=70, mode='trackcom') # Keep track of entities to team mapping. self._players = [] # Initialize tracker attributes. self.initialize_entity_trackers() def register_player(self, player): self._players.append(player) def initialize_entity_trackers(self): self._last_hit = None self._hit = False self._repossessed = False self._intercepted = False # Tracks distance traveled by the ball in between consecutive hits. self._pos_at_last_step = None self._dist_since_last_hit = None self._dist_between_last_hits = None def initialize_episode(self, physics, unused_random_state): self._geom_id = physics.model.name2id(self._geom.full_identifier, 'geom') self._geom_id_to_player = {} for player in self._players: geoms = player.walker.mjcf_model.find_all('geom') for geom in geoms: geom_id = physics.model.name2id(geom.full_identifier, 'geom') self._geom_id_to_player[geom_id] = player self.initialize_entity_trackers() def after_substep(self, physics, unused_random_state): """Resolve contacts and update ball-player contact trackers.""" if self._hit: # Ball has already registered a valid contact within step (during one of # previous after_substep calls). return # Iterate through all contacts to find the first contact between the ball # and one of the registered entities. for contact in physics.data.contact: # Keep contacts that involve the ball and one of the registered entities. has_self = False for geom_id in (contact.geom1, contact.geom2): if geom_id == self._geom_id: has_self = True else: player = self._geom_id_to_player.get(geom_id) if has_self and player: # Detected a contact between the ball and an registered player. if self._last_hit is not None: self._intercepted = player.team != self._last_hit.team else: self._intercepted = True # Register repossessed before updating last_hit player. self._repossessed = player is not self._last_hit self._last_hit = player # Register hit event. self._hit = True break def before_step(self, physics, random_state): super().before_step(physics, random_state) # Reset per simulation step indicator. self._hit = False self._repossessed = False self._intercepted = False def after_step(self, physics, random_state): super().after_step(physics, random_state) pos = physics.bind(self._geom).xpos if self._hit: # SoccerBall is hit on this step. Update dist_between_last_hits # to dist_since_last_hit before resetting dist_since_last_hit. self._dist_between_last_hits = self._dist_since_last_hit self._dist_since_last_hit = 0. self._pos_at_last_step = pos.copy() if self._dist_since_last_hit is not None: # Accumulate distance traveled since last hit event. self._dist_since_last_hit += np.linalg.norm(pos - self._pos_at_last_step) self._pos_at_last_step = pos.copy() @property def last_hit(self): """The player that last came in contact with the ball or `None`.""" return self._last_hit @property def hit(self): """Indicates if the ball is hit during the last simulation step. For a timeline shown below: ..., agent.step, simulation, agent.step, ... Returns: True: if the ball is hit by a registered player during simulation step. False: if not. """ return self._hit @property def repossessed(self): """Indicates if the ball has been repossessed by a different player. For a timeline shown below: ..., agent.step, simulation, agent.step, ... Returns: True if the ball is hit by a registered player during simulation step and that player is different from `last_hit`. False: if the ball is not hit, or the ball is hit by `last_hit` player. """ return self._repossessed @property def intercepted(self): """Indicates if the ball has been intercepted by a different team. For a timeline shown below: ..., agent.step, simulation, agent.step, ... Returns: True: if the ball is hit for the first time, or repossessed by an player from a different team. False: if the ball is not hit, not repossessed, or repossessed by a teammate to `last_hit`. """ return self._intercepted @property def dist_between_last_hits(self): """Distance between last consecutive hits. Returns: Distance between last two consecutive hit events or `None` if there has not been two consecutive hits on the ball. """ return self._dist_between_last_hits
dm_control-main
dm_control/locomotion/soccer/soccer_ball.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. # ============================================================================ """"A task where players play a soccer game.""" from dm_control import composer from dm_control.locomotion.soccer import initializers from dm_control.locomotion.soccer import observables as observables_lib from dm_control.locomotion.soccer import soccer_ball from dm_env import specs import numpy as np _THROW_IN_BALL_Z = 0.5 def _disable_geom_contacts(entities): for entity in entities: mjcf_model = entity.mjcf_model for geom in mjcf_model.find_all("geom"): geom.set_attributes(contype=0) class Task(composer.Task): """A task where two teams of walkers play soccer.""" def __init__( self, players, arena, ball=None, initializer=None, observables=None, disable_walker_contacts=False, nconmax_per_player=200, njmax_per_player=400, control_timestep=0.025, tracking_cameras=(), ): """Construct an instance of soccer.Task. This task implements the high-level game logic of multi-agent MuJoCo soccer. Args: players: a sequence of `soccer.Player` instances, representing participants to the game from both teams. arena: an instance of `soccer.Pitch`, implementing the physical geoms and the sensors associated with the pitch. ball: optional instance of `soccer.SoccerBall`, implementing the physical geoms and sensors associated with the soccer ball. If None, defaults to using `soccer_ball.SoccerBall()`. initializer: optional instance of `soccer.Initializer` that initializes the task at the start of each episode. If None, defaults to `initializers.UniformInitializer()`. observables: optional instance of `soccer.ObservablesAdder` that adds observables for each player. If None, defaults to `observables.CoreObservablesAdder()`. disable_walker_contacts: if `True`, disable physical contacts between players. nconmax_per_player: allocated maximum number of contacts per player. It may be necessary to increase this value if you encounter errors due to `mjWARN_CONTACTFULL`. njmax_per_player: allocated maximum number of scalar constraints per player. It may be necessary to increase this value if you encounter errors due to `mjWARN_CNSTRFULL`. control_timestep: control timestep of the agent. tracking_cameras: a sequence of `camera.MultiplayerTrackingCamera` instances to track the players and ball. """ self.arena = arena self.players = players self._initializer = initializer or initializers.UniformInitializer() self._observables = observables or observables_lib.CoreObservablesAdder() if disable_walker_contacts: _disable_geom_contacts([p.walker for p in self.players]) # Create ball and attach ball to arena. self.ball = ball or soccer_ball.SoccerBall() self.arena.add_free_entity(self.ball) self.arena.register_ball(self.ball) # Register soccer ball contact tracking for players. for player in self.players: player.walker.create_root_joints(self.arena.attach(player.walker)) self.ball.register_player(player) # Add per-walkers observables. self._observables(self, player) self._tracking_cameras = tracking_cameras self.set_timesteps( physics_timestep=0.005, control_timestep=control_timestep) self.root_entity.mjcf_model.size.nconmax = nconmax_per_player * len(players) self.root_entity.mjcf_model.size.njmax = njmax_per_player * len(players) @property def observables(self): observables = [] for player in self.players: observables.append( player.walker.observables.as_dict(fully_qualified=False)) return observables def _throw_in(self, physics, random_state, ball): x, y, _ = physics.bind(ball.geom).xpos shrink_x, shrink_y = random_state.uniform([0.7, 0.7], [0.9, 0.9]) ball.set_pose(physics, [x * shrink_x, y * shrink_y, _THROW_IN_BALL_Z]) ball.set_velocity( physics, velocity=np.zeros(3), angular_velocity=np.zeros(3)) ball.initialize_entity_trackers() def _tracked_entity_positions(self, physics): """Return a list of the positions of the ball and all players.""" ball_pos, unused_ball_quat = self.ball.get_pose(physics) entity_positions = [ball_pos] for player in self.players: walker_pos, unused_walker_quat = player.walker.get_pose(physics) entity_positions.append(walker_pos) return entity_positions def after_compile(self, physics, random_state): super().after_compile(physics, random_state) for camera in self._tracking_cameras: camera.after_compile(physics) def after_step(self, physics, random_state): super().after_step(physics, random_state) for camera in self._tracking_cameras: camera.after_step(self._tracked_entity_positions(physics)) def initialize_episode_mjcf(self, random_state): self.arena.initialize_episode_mjcf(random_state) def initialize_episode(self, physics, random_state): self.arena.initialize_episode(physics, random_state) for player in self.players: player.walker.reinitialize_pose(physics, random_state) self._initializer(self, physics, random_state) for camera in self._tracking_cameras: camera.initialize_episode(self._tracked_entity_positions(physics)) @property def root_entity(self): return self.arena def get_reward(self, physics): """Returns a list of per-player rewards. Each player will receive a reward of: +1 if their team scored a goal -1 if their team conceded a goal 0 if no goals were scored on this timestep. Note: the observations also contain various environment statistics that may be used to derive per-player rewards (as done in http://arxiv.org/abs/1902.07151). Args: physics: An instance of `Physics`. Returns: A list of 0-dimensional numpy arrays, one per player. """ scoring_team = self.arena.detected_goal() if not scoring_team: return [np.zeros((), dtype=np.float32) for _ in self.players] rewards = [] for p in self.players: if p.team == scoring_team: rewards.append(np.ones((), dtype=np.float32)) else: rewards.append(-np.ones((), dtype=np.float32)) return rewards def get_reward_spec(self): return [ specs.Array(name="reward", shape=(), dtype=np.float32) for _ in self.players ] def get_discount(self, physics): if self.arena.detected_goal(): return np.zeros((), np.float32) return np.ones((), np.float32) def get_discount_spec(self): return specs.Array(name="discount", shape=(), dtype=np.float32) def should_terminate_episode(self, physics): """Returns True if a goal was scored by either team.""" return self.arena.detected_goal() is not None def before_step(self, physics, actions, random_state): for player, action in zip(self.players, actions): player.walker.apply_action(physics, action, random_state) if self.arena.detected_off_court(): self._throw_in(physics, random_state, self.ball) def action_spec(self, physics): """Return multi-agent action_spec.""" return [player.walker.action_spec for player in self.players] class MultiturnTask(Task): """Continuous game play through scoring events until timeout.""" def __init__(self, players, arena, ball=None, initializer=None, observables=None, disable_walker_contacts=False, nconmax_per_player=200, njmax_per_player=400, control_timestep=0.025, tracking_cameras=()): """See base class.""" super().__init__( players, arena, ball=ball, initializer=initializer, observables=observables, disable_walker_contacts=disable_walker_contacts, nconmax_per_player=nconmax_per_player, njmax_per_player=njmax_per_player, control_timestep=control_timestep, tracking_cameras=tracking_cameras) # If `True`, reset ball entity trackers before the next step. self._should_reset = False def should_terminate_episode(self, physics): return False def get_discount(self, physics): return np.ones((), np.float32) def before_step(self, physics, actions, random_state): super(MultiturnTask, self).before_step(physics, actions, random_state) if self._should_reset: self.ball.initialize_entity_trackers() self._should_reset = False def after_step(self, physics, random_state): super(MultiturnTask, self).after_step(physics, random_state) if self.arena.detected_goal(): self._initializer(self, physics, random_state) self._should_reset = True
dm_control-main
dm_control/locomotion/soccer/task.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 based on an actuated jumping ball.""" import enum import os from dm_control.locomotion.walkers import cmu_humanoid import numpy as np _ASSETS_PATH = os.path.join(os.path.dirname(__file__), 'assets', 'humanoid') _MAX_WALKER_ID = 10 _INVALID_WALKER_ID = 'walker_id must be in [0-{}], got: {{}}.'.format( _MAX_WALKER_ID) _INTERIOR_GEOMS = frozenset({ 'lhipjoint', 'rhipjoint', 'lfemur', 'lowerback', 'upperback', 'rclavicle', 'lclavicle', 'thorax', 'lhumerus', 'root_geom', 'lowerneck', 'rhumerus', 'rfemur' }) def _add_visual_only_geoms(mjcf_root): """Introduce visual only geoms to complement the `JERSEY` visual.""" lowerneck = mjcf_root.find('body', 'lowerneck') neck_offset = 0.066 - 0.0452401 lowerneck.add( 'geom', name='halfneck', # shrink neck radius from 0.06 to 0.05 else it pokes through shirt size=(0.05, 0.02279225 - neck_offset), pos=(-0.00165071, 0.0452401 + neck_offset, 0.00534359), quat=(0.66437, 0.746906, 0.027253, 0), mass=0., contype=0, conaffinity=0, rgba=(.7, .5, .3, 1)) lhumerus = mjcf_root.find('body', 'lhumerus') humerus_offset = 0.20 - 0.138421 lhumerus.add( 'geom', name='lelbow', size=(0.035, 0.1245789 - humerus_offset), pos=(0.0, -0.138421 - humerus_offset, 0.0), quat=(0.612372, -0.612372, 0.353553, 0.353553), mass=0., contype=0, conaffinity=0, rgba=(.7, .5, .3, 1)) rhumerus = mjcf_root.find('body', 'rhumerus') humerus_offset = 0.20 - 0.138421 rhumerus.add( 'geom', name='relbow', size=(0.035, 0.1245789 - humerus_offset), pos=(0.0, -0.138421 - humerus_offset, 0.0), quat=(0.612372, -0.612372, -0.353553, -0.353553), mass=0., contype=0, conaffinity=0, rgba=(.7, .5, .3, 1)) lfemur = mjcf_root.find('body', 'lfemur') femur_offset = 0.384 - 0.202473 lfemur.add( 'geom', name='lknee', # shrink knee radius from 0.06 to 0.055 else it pokes through short size=(0.055, 0.1822257 - femur_offset), pos=(-5.0684e-08, -0.202473 - femur_offset, 0), quat=(0.696364, -0.696364, -0.122788, -0.122788), mass=0., contype=0, conaffinity=0, rgba=(.7, .5, .3, 1)) rfemur = mjcf_root.find('body', 'rfemur') femur_offset = 0.384 - 0.202473 rfemur.add( 'geom', name='rknee', # shrink knee radius from 0.06 to 0.055 else it pokes through short size=(0.055, 0.1822257 - femur_offset), pos=(-5.0684e-08, -0.202473 - femur_offset, 0), quat=(0.696364, -0.696364, 0.122788, 0.122788), mass=0., contype=0, conaffinity=0, rgba=(.7, .5, .3, 1)) class Humanoid(cmu_humanoid.CMUHumanoidPositionControlled): """A CMU humanoid walker specialised visually for soccer.""" class Visual(enum.Enum): GEOM = 1 JERSEY = 2 def _build(self, # pytype: disable=signature-mismatch # overriding-parameter-count-checks visual, marker_rgba, walker_id=None, initializer=None, name='walker'): """Build a soccer-specific Humanoid walker.""" if not isinstance(visual, Humanoid.Visual): raise ValueError('`visual` must be one of `Humanoid.Visual`.') if len(marker_rgba) != 4: raise ValueError('`marker_rgba` must be a sequence of length 4.') if walker_id is None and visual != Humanoid.Visual.GEOM: raise ValueError( '`walker_id` must be set unless `visual` is set to `Visual.GEOM`.') if walker_id is not None and not 0 <= walker_id <= _MAX_WALKER_ID: raise ValueError(_INVALID_WALKER_ID.format(walker_id)) if visual == Humanoid.Visual.JERSEY: team = 'R' if marker_rgba[0] > marker_rgba[2] else 'B' marker_rgba = None # disable geom coloring for None geom visual. else: marker_rgba[-1] = .7 super(Humanoid, self)._build( marker_rgba=marker_rgba, initializer=initializer, include_face=True) self._mjcf_root.model = name # Changes to humanoid geoms for visual improvements. # Hands: hide hand geoms and add slightly larger visual geoms. for hand_name in ['lhand', 'rhand']: hand = self._mjcf_root.find('body', hand_name) for geom in hand.find_all('geom'): geom.rgba = (0, 0, 0, 0) if geom.name == hand_name: geom_size = geom.size * 1.3 # Palm rescaling. else: geom_size = geom.size * 1.5 # Finger rescaling. geom.parent.add( 'geom', name=geom.name + '_visual', type=geom.type, quat=geom.quat, mass=0, contype=0, conaffinity=0, size=geom_size, pos=geom.pos * 1.5) # Lighting: remove tracking light as we have multiple walkers in the scene. tracking_light = self._mjcf_root.find('light', 'tracking_light') tracking_light.remove() if visual == Humanoid.Visual.JERSEY: shirt_number = walker_id + 1 self._mjcf_root.asset.add( 'texture', name='skin', type='2d', file=os.path.join(_ASSETS_PATH, f'{team}_{walker_id + 1:02d}.png')) self._mjcf_root.asset.add('material', name='skin', texture='skin') self._mjcf_root.asset.add( 'skin', name='skin', file=os.path.join(_ASSETS_PATH, 'jersey.skn'), material='skin') for geom in self._mjcf_root.find_all('geom'): if geom.name in _INTERIOR_GEOMS: geom.rgba = (0.0, 0.0, 0.0, 0.0) _add_visual_only_geoms(self._mjcf_root) # Initialize previous action. self._prev_action = np.zeros(shape=self.action_spec.shape, dtype=self.action_spec.dtype) @property def marker_geoms(self): """Returns a sequence of marker geoms to be colored visually.""" marker_geoms = [] face = self._mjcf_root.find('geom', 'face') if face is not None: marker_geoms.append(face) marker_geoms += self._mjcf_root.find('body', 'rfoot').find_all('geom') marker_geoms += self._mjcf_root.find('body', 'lfoot').find_all('geom') return marker_geoms + [ self._mjcf_root.find('geom', 'lowerneck'), self._mjcf_root.find('geom', 'lclavicle'), self._mjcf_root.find('geom', 'rclavicle'), self._mjcf_root.find('geom', 'thorax'), self._mjcf_root.find('geom', 'upperback'), self._mjcf_root.find('geom', 'lowerback'), self._mjcf_root.find('geom', 'rfemur'), self._mjcf_root.find('geom', 'lfemur'), self._mjcf_root.find('geom', 'root_geom'), ] def initialize_episode(self, physics, random_state): self._prev_action = np.zeros(shape=self.action_spec.shape, dtype=self.action_spec.dtype) def apply_action(self, physics, action, random_state): super().apply_action(physics, action, random_state) # Updates previous action. self._prev_action[:] = action @property def prev_action(self): return self._prev_action
dm_control-main
dm_control/locomotion/soccer/humanoid.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.soccer.pitch.""" from absl.testing import absltest from absl.testing import parameterized from dm_control import composer from dm_control.composer.variation import distributions from dm_control.entities import props from dm_control.locomotion.soccer import pitch as pitch_lib from dm_control.locomotion.soccer import team as team_lib import numpy as np class PitchTest(parameterized.TestCase): def _pitch_with_ball(self, pitch_size, ball_pos): pitch = pitch_lib.Pitch(size=pitch_size) self.assertEqual(pitch.size, pitch_size) sphere = props.Primitive(geom_type='sphere', size=(0.1,), pos=ball_pos) pitch.register_ball(sphere) pitch.attach(sphere) env = composer.Environment( composer.NullTask(pitch), random_state=np.random.RandomState(42)) env.reset() return pitch def test_pitch_none_detected(self): pitch = self._pitch_with_ball((12, 9), (0, 0, 0)) self.assertEmpty(pitch.detected_off_court()) self.assertIsNone(pitch.detected_goal()) def test_pitch_detected_off_court(self): pitch = self._pitch_with_ball((12, 9), (20, 0, 0)) self.assertLen(pitch.detected_off_court(), 1) self.assertIsNone(pitch.detected_goal()) def test_pitch_detected_away_goal(self): pitch = self._pitch_with_ball((12, 9), (-9.5, 0, 1)) self.assertLen(pitch.detected_off_court(), 1) self.assertEqual(team_lib.Team.AWAY, pitch.detected_goal()) def test_pitch_detected_home_goal(self): pitch = self._pitch_with_ball((12, 9), (9.5, 0, 1)) self.assertLen(pitch.detected_off_court(), 1) self.assertEqual(team_lib.Team.HOME, pitch.detected_goal()) @parameterized.parameters((True, distributions.Uniform()), (False, distributions.Uniform())) def test_randomize_pitch(self, keep_aspect_ratio, randomizer): pitch = pitch_lib.RandomizedPitch( min_size=(4, 3), max_size=(8, 6), randomizer=randomizer, keep_aspect_ratio=keep_aspect_ratio) pitch.initialize_episode_mjcf(np.random.RandomState(42)) self.assertBetween(pitch.size[0], 4, 8) self.assertBetween(pitch.size[1], 3, 6) if keep_aspect_ratio: self.assertAlmostEqual((pitch.size[0] - 4) / (8. - 4.), (pitch.size[1] - 3) / (6. - 3.)) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/soccer/pitch_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. # ============================================================================ """Multi-agent MuJoCo soccer environment.""" import enum from dm_control import composer from dm_control.locomotion import walkers from dm_control.locomotion.soccer.boxhead import BoxHead from dm_control.locomotion.soccer.humanoid import Humanoid from dm_control.locomotion.soccer.initializers import Initializer from dm_control.locomotion.soccer.initializers import UniformInitializer from dm_control.locomotion.soccer.observables import CoreObservablesAdder from dm_control.locomotion.soccer.observables import InterceptionObservablesAdder from dm_control.locomotion.soccer.observables import MultiObservablesAdder from dm_control.locomotion.soccer.observables import ObservablesAdder from dm_control.locomotion.soccer.pitch import MINI_FOOTBALL_GOAL_SIZE from dm_control.locomotion.soccer.pitch import MINI_FOOTBALL_MAX_AREA_PER_HUMANOID from dm_control.locomotion.soccer.pitch import MINI_FOOTBALL_MIN_AREA_PER_HUMANOID from dm_control.locomotion.soccer.pitch import Pitch from dm_control.locomotion.soccer.pitch import RandomizedPitch from dm_control.locomotion.soccer.soccer_ball import regulation_soccer_ball from dm_control.locomotion.soccer.soccer_ball import SoccerBall from dm_control.locomotion.soccer.task import MultiturnTask from dm_control.locomotion.soccer.task import Task from dm_control.locomotion.soccer.team import Player from dm_control.locomotion.soccer.team import RGBA_BLUE from dm_control.locomotion.soccer.team import RGBA_RED from dm_control.locomotion.soccer.team import Team from dm_control.locomotion.walkers.initializers import mocap import numpy as np class WalkerType(enum.Enum): BOXHEAD = 0 ANT = 1 HUMANOID = 2 def _make_walker(name, walker_id, marker_rgba, walker_type=WalkerType.BOXHEAD): """Construct a BoxHead walker.""" if walker_type == WalkerType.BOXHEAD: return BoxHead( name=name, walker_id=walker_id, marker_rgba=marker_rgba, ) if walker_type == WalkerType.ANT: return walkers.Ant(name=name, marker_rgba=marker_rgba) if walker_type == WalkerType.HUMANOID: initializer = mocap.CMUMocapInitializer() return Humanoid( name=name, marker_rgba=marker_rgba, walker_id=walker_id, visual=Humanoid.Visual.JERSEY, initializer=initializer) raise ValueError("Unrecognized walker type: %s" % walker_type) def _make_players(team_size, walker_type): """Construct home and away teams each of `team_size` players.""" home_players = [] away_players = [] for i in range(team_size): home_walker = _make_walker("home%d" % i, i, RGBA_BLUE, walker_type) home_players.append(Player(Team.HOME, home_walker)) away_walker = _make_walker("away%d" % i, i, RGBA_RED, walker_type) away_players.append(Player(Team.AWAY, away_walker)) return home_players + away_players def _area_to_size(area, aspect_ratio=0.75): """Convert from area and aspect_ratio to (width, height).""" return np.sqrt([area / aspect_ratio, area * aspect_ratio]) / 2. def load(team_size, time_limit=45., random_state=None, disable_walker_contacts=False, enable_field_box=False, keep_aspect_ratio=False, terminate_on_goal=True, walker_type=WalkerType.BOXHEAD): """Construct `team_size`-vs-`team_size` soccer environment. Args: team_size: Integer, the number of players per team. Must be between 1 and 11. time_limit: Float, the maximum duration of each episode in seconds. random_state: (optional) an int seed or `np.random.RandomState` instance. disable_walker_contacts: (optional) if `True`, disable physical contacts between walkers. enable_field_box: (optional) if `True`, enable physical bounding box for the soccer ball (but not the players). keep_aspect_ratio: (optional) if `True`, maintain constant pitch aspect ratio. terminate_on_goal: (optional) if `False`, continuous game play across scoring events. walker_type: the type of walker to instantiate in the environment. Returns: A `composer.Environment` instance. Raises: ValueError: If `team_size` is not between 1 and 11. ValueError: If `walker_type` is not recognized. """ goal_size = None min_size = (32, 24) max_size = (48, 36) ball = SoccerBall() if walker_type == WalkerType.HUMANOID: goal_size = MINI_FOOTBALL_GOAL_SIZE num_walkers = team_size * 2 min_size = _area_to_size(MINI_FOOTBALL_MIN_AREA_PER_HUMANOID * num_walkers) max_size = _area_to_size(MINI_FOOTBALL_MAX_AREA_PER_HUMANOID * num_walkers) ball = regulation_soccer_ball() task_factory = Task if not terminate_on_goal: task_factory = MultiturnTask return composer.Environment( task=task_factory( players=_make_players(team_size, walker_type), arena=RandomizedPitch( min_size=min_size, max_size=max_size, keep_aspect_ratio=keep_aspect_ratio, field_box=enable_field_box, goal_size=goal_size), ball=ball, disable_walker_contacts=disable_walker_contacts), time_limit=time_limit, random_state=random_state)
dm_control-main
dm_control/locomotion/soccer/__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. # ============================================================================ """Define teams and players participating in a match.""" import collections import enum class Team(enum.Enum): HOME = 0 AWAY = 1 RGBA_BLUE = [.1, .1, .8, 1.] RGBA_RED = [.8, .1, .1, 1.] Player = collections.namedtuple('Player', ['team', 'walker'])
dm_control-main
dm_control/locomotion/soccer/team.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. # ============================================================================ """Cameras for recording soccer videos.""" from dm_control.mujoco import engine import numpy as np class MultiplayerTrackingCamera: """Camera that smoothly tracks multiple entities.""" def __init__( self, min_distance, distance_factor, smoothing_update_speed, azimuth=90, elevation=-45, width=1920, height=1080, ): """Construct a new MultiplayerTrackingcamera. The target lookat point is the centroid of all tracked entities. Target camera distance is set to min_distance + distance_factor * d_max, where d_max is the maximum distance of any entity to the lookat point. Args: min_distance: minimum camera distance. distance_factor: camera distance multiplier (see above). smoothing_update_speed: exponential filter parameter to smooth camera movement. 1 means no filter; smaller values mean less change per step. azimuth: constant azimuth to use for camera. elevation: constant elevation to use for camera. width: width to use for rendered video. height: height to use for rendered video. """ self._min_distance = min_distance self._distance_factor = distance_factor if smoothing_update_speed < 0 or smoothing_update_speed > 1: raise ValueError("Filter speed must be in range [0, 1].") self._smoothing_update_speed = smoothing_update_speed self._azimuth = azimuth self._elevation = elevation self._width = width self._height = height self._camera = None @property def camera(self): return self._camera def render(self): """Render the current frame.""" if self._camera is None: raise ValueError( "Camera has not been initialized yet." " render can only be called after physics has been compiled." ) return self._camera.render() def after_compile(self, physics): """Instantiate the camera and ensure rendering buffer is large enough.""" buffer_height = max(self._height, physics.model.vis.global_.offheight) buffer_width = max(self._width, physics.model.vis.global_.offwidth) physics.model.vis.global_.offheight = buffer_height physics.model.vis.global_.offwidth = buffer_width self._camera = engine.MovableCamera( physics, height=self._height, width=self._width) def _get_target_camera_pose(self, entity_positions): """Returns the pose that the camera should be pulled toward. Args: entity_positions: list of numpy arrays representing current positions of the entities to be tracked. Returns: mujoco.engine.Pose representing the target camera pose. """ stacked_positions = np.stack(entity_positions) centroid = np.mean(stacked_positions, axis=0) radii = np.linalg.norm(stacked_positions - centroid, axis=1) assert len(radii) == len(entity_positions) camera_distance = self._min_distance + self._distance_factor * np.max(radii) return engine.Pose( lookat=centroid, distance=camera_distance, azimuth=self._azimuth, elevation=self._elevation, ) def initialize_episode(self, entity_positions): """Begin the episode with the camera set to its target pose.""" target_pose = self._get_target_camera_pose(entity_positions) self._camera.set_pose(*target_pose) def after_step(self, entity_positions): """Move camera toward its target poses.""" target_pose = self._get_target_camera_pose(entity_positions) cur_pose = self._camera.get_pose() smoothing_update_speed = self._smoothing_update_speed filtered_pose = [ target_val * smoothing_update_speed + \ current_val * (1 - smoothing_update_speed) for target_val, current_val in zip(target_pose, cur_pose) ] self._camera.set_pose(*filtered_pose)
dm_control-main
dm_control/locomotion/soccer/camera.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. # ============================================================================ """Soccer task episode initializers.""" import abc import numpy as np _INIT_BALL_Z = 0.5 _SPAWN_RATIO = 0.6 class Initializer(metaclass=abc.ABCMeta): @abc.abstractmethod def __call__(self, task, physics, random_state): """Initialize episode for a task.""" class UniformInitializer(Initializer): """Uniformly initialize walkers and soccer ball over spawn_range.""" def __init__(self, spawn_ratio=_SPAWN_RATIO, init_ball_z=_INIT_BALL_Z, max_collision_avoidance_retries=100): self._spawn_ratio = spawn_ratio self._init_ball_z = init_ball_z # Lazily initialize geom ids for contact avoidance. self._ball_geom_ids = None self._walker_geom_ids = None self._all_geom_ids = None self._max_retries = max_collision_avoidance_retries def _initialize_ball(self, ball, spawn_range, physics, random_state): """Initialize ball in given spawn_range.""" if isinstance(spawn_range, np.ndarray): x, y = random_state.uniform(-spawn_range, spawn_range) elif isinstance(spawn_range, (list, tuple)) and len(spawn_range) == 2: x, y = random_state.uniform(spawn_range[0], spawn_range[1]) else: raise ValueError( 'Unsupported spawn_range. Must be ndarray or list/tuple of length 2.') ball.set_pose(physics, [x, y, self._init_ball_z]) # Note: this method is not always called immediately after `physics.reset()` # so we need to explicitly zero out the velocity. ball.set_velocity(physics, velocity=0., angular_velocity=0.) def _initialize_walker(self, walker, spawn_range, physics, random_state): """Uniformly initialize walker in spawn_range.""" walker.reinitialize_pose(physics, random_state) x, y = random_state.uniform(-spawn_range, spawn_range) (_, _, z), quat = walker.get_pose(physics) walker.set_pose(physics, [x, y, z], quat) rotation = random_state.uniform(-np.pi, np.pi) quat = [np.cos(rotation / 2), 0, 0, np.sin(rotation / 2)] walker.shift_pose(physics, quaternion=quat) # Note: this method is not always called immediately after `physics.reset()` # so we need to explicitly zero out the velocity. walker.set_velocity(physics, velocity=0., angular_velocity=0.) def _initialize_entities(self, task, physics, random_state): spawn_range = np.asarray(task.arena.size) * self._spawn_ratio self._initialize_ball(task.ball, spawn_range, physics, random_state) for player in task.players: self._initialize_walker(player.walker, spawn_range, physics, random_state) def _initialize_geom_ids(self, task, physics): self._ball_geom_ids = {physics.bind(task.ball.geom)} self._walker_geom_ids = [] for player in task.players: walker_geoms = player.walker.mjcf_model.find_all('geom') self._walker_geom_ids.append(set(physics.bind(walker_geoms).element_id)) self._all_geom_ids = set(self._ball_geom_ids) for walker_geom_ids in self._walker_geom_ids: self._all_geom_ids |= walker_geom_ids def _has_relevant_contact(self, contact, geom_ids): other_geom_ids = self._all_geom_ids - geom_ids if ((contact.geom1 in geom_ids and contact.geom2 in other_geom_ids) or (contact.geom2 in geom_ids and contact.geom1 in other_geom_ids)): return True return False def __call__(self, task, physics, random_state): # Initialize geom_ids for collision detection. if not self._all_geom_ids: self._initialize_geom_ids(task, physics) num_retries = 0 while True: self._initialize_entities(task, physics, random_state) should_retry = False physics.forward() # forward physics for contact resolution. for contact in physics.data.contact: if self._has_relevant_contact(contact, self._ball_geom_ids): should_retry = True break for walker_geom_ids in self._walker_geom_ids: if self._has_relevant_contact(contact, walker_geom_ids): should_retry = True break if not should_retry: break num_retries += 1 if num_retries > self._max_retries: raise RuntimeError('UniformInitializer: `max_retries` (%d) exceeded.' % self._max_retries)
dm_control-main
dm_control/locomotion/soccer/initializers.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.soccer.Humanoid.""" import itertools from absl.testing import absltest from absl.testing import parameterized from dm_control.locomotion.soccer import humanoid from dm_control.locomotion.soccer import team class HumanoidTest(parameterized.TestCase): @parameterized.parameters( itertools.product( humanoid.Humanoid.Visual, (team.RGBA_RED, team.RGBA_BLUE), (None, 0, 10), )) def test_instantiation(self, visual, marker_rgba, walker_id): if visual != humanoid.Humanoid.Visual.GEOM and walker_id is None: self.skipTest('Invalid configuration skipped.') humanoid.Humanoid( visual=visual, marker_rgba=marker_rgba, walker_id=walker_id) @parameterized.parameters(-1, 11) def test_invalid_walker_id(self, walker_id): with self.assertRaisesWithLiteralMatch( ValueError, humanoid._INVALID_WALKER_ID.format(walker_id)): humanoid.Humanoid( visual=humanoid.Humanoid.Visual.JERSEY, walker_id=walker_id, marker_rgba=team.RGBA_BLUE) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/soccer/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. # ============================================================================ """Walkers based on an actuated jumping ball.""" import io 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 legacy_base import numpy as np from PIL import Image from dm_control.utils import io as resources _ASSETS_PATH = os.path.join(os.path.dirname(__file__), 'assets', 'boxhead') _MAX_WALKER_ID = 10 _INVALID_WALKER_ID = 'walker_id must be in [0-{}], got: {{}}.'.format( _MAX_WALKER_ID) def _compensate_gravity(physics, body_elements): """Applies Cartesian forces to bodies in order to exactly counteract gravity. Note that this will also affect the output of pressure, force, or torque sensors within the kinematic chain leading from the worldbody to the bodies that are being gravity-compensated. Args: physics: An `mjcf.Physics` instance to modify. body_elements: An iterable of `mjcf.Element`s specifying the bodies to which gravity compensation will be applied. """ gravity = np.hstack([physics.model.opt.gravity, [0, 0, 0]]) bodies = physics.bind(body_elements) bodies.xfrc_applied = -gravity * bodies.mass[..., None] def _alpha_blend(foreground, background): """Does alpha compositing of two RGBA images. Both inputs must be (..., 4) numpy arrays whose shapes are compatible for broadcasting. They are assumed to contain float RGBA values in [0, 1]. Args: foreground: foreground RGBA image. background: background RGBA image. Returns: A numpy array of shape (..., 4) containing the blended image. """ fg, bg = np.broadcast_arrays(foreground, background) fg_rgb = fg[..., :3] fg_a = fg[..., 3:] bg_rgb = bg[..., :3] bg_a = bg[..., 3:] out = np.empty_like(bg) out_a = out[..., 3:] out_rgb = out[..., :3] # https://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending out_a[:] = fg_a + bg_a * (1. - fg_a) out_rgb[:] = fg_rgb * fg_a + bg_rgb * bg_a * (1. - fg_a) # Avoid division by zero if foreground and background are both transparent. out_rgb[:] = np.where(out_a, out_rgb / out_a, out_rgb) return out def _asset_png_with_background_rgba_bytes(asset_fname, background_rgba): """Decode PNG from asset file and add solid background.""" # Retrieve PNG image contents as a bytestring, convert to a numpy array. contents = resources.GetResource(os.path.join(_ASSETS_PATH, asset_fname)) digit_rgba = np.array(Image.open(io.BytesIO(contents)), dtype=np.double) # Add solid background with `background_rgba`. blended = 255. * _alpha_blend(digit_rgba / 255., np.asarray(background_rgba)) # Encode composite image array to a PNG bytestring. img = Image.fromarray(blended.astype(np.uint8), mode='RGBA') buf = io.BytesIO() img.save(buf, format='PNG') png_encoding = buf.getvalue() buf.close() return png_encoding class BoxHeadObservables(legacy_base.WalkerObservables): """BoxHead observables with low-res camera and modulo'd rotational joints.""" def __init__(self, entity, camera_resolution): self._camera_resolution = camera_resolution super().__init__(entity) @composer.observable def egocentric_camera(self): width, height = self._camera_resolution return observable.MJCFCamera(self._entity.egocentric_camera, width=width, height=height) @property def proprioception(self): proprioception = super().proprioception if self._entity.observable_camera_joints: return proprioception + [self.camera_joints_pos, self.camera_joints_vel] return proprioception @composer.observable def camera_joints_pos(self): def _sin(value, random_state): del random_state return np.sin(value) def _cos(value, random_state): del random_state return np.cos(value) sin_rotation_joints = observable.MJCFFeature( 'qpos', self._entity.observable_camera_joints, corruptor=_sin) cos_rotation_joints = observable.MJCFFeature( 'qpos', self._entity.observable_camera_joints, corruptor=_cos) def _camera_joints(physics): return np.concatenate([ sin_rotation_joints(physics), cos_rotation_joints(physics) ], -1) return observable.Generic(_camera_joints) @composer.observable def camera_joints_vel(self): return observable.MJCFFeature( 'qvel', self._entity.observable_camera_joints) class BoxHead(legacy_base.Walker): """A rollable and jumpable ball with a head.""" def _build(self, name='walker', marker_rgba=None, camera_control=False, camera_resolution=(28, 28), roll_gear=-60, steer_gear=55, walker_id=None, initializer=None): """Build a BoxHead. 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. camera_resolution: egocentric camera rendering resolution. roll_gear: gear determining forward acceleration. steer_gear: gear determining steering (spinning) torque. walker_id: (Optional) An integer in [0-10], this number will be shown on the walker's head. Defaults to `None` which does not show any number. initializer: (Optional) A `WalkerInitializer` object. Raises: ValueError: if received invalid walker_id. """ super()._build(initializer=initializer) xml_path = os.path.join(_ASSETS_PATH, 'boxhead.xml') self._mjcf_root = mjcf.from_xml_string(resources.GetResource(xml_path, 'r')) if name: self._mjcf_root.model = name if walker_id is not None and not 0 <= walker_id <= _MAX_WALKER_ID: raise ValueError(_INVALID_WALKER_ID.format(walker_id)) self._walker_id = walker_id if walker_id is not None: png_bytes = _asset_png_with_background_rgba_bytes( 'digits/%02d.png' % walker_id, marker_rgba) head_texture = self._mjcf_root.asset.add( 'texture', name='head_texture', type='2d', file=mjcf.Asset(png_bytes, '.png')) head_material = self._mjcf_root.asset.add( 'material', name='head_material', texture=head_texture) self._mjcf_root.find('geom', 'head').material = head_material self._mjcf_root.find('geom', 'head').rgba = None self._mjcf_root.find('geom', 'top_down_cam_box').material = head_material self._mjcf_root.find('geom', 'top_down_cam_box').rgba = None self._body_texture = self._mjcf_root.asset.add( 'texture', name='ball_body', type='cube', builtin='checker', rgb1=marker_rgba[:-1] if marker_rgba else '.4 .4 .4', rgb2='.8 .8 .8', width='100', height='100') self._body_material = self._mjcf_root.asset.add( 'material', name='ball_body', texture=self._body_texture) self._mjcf_root.find('geom', 'shell').material = self._body_material # 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 self._camera_resolution = camera_resolution if not camera_control: for name in ('camera_pitch', 'camera_yaw'): self._mjcf_root.find('actuator', name).remove() self._mjcf_root.find('joint', name).remove() self._roll_gear = roll_gear self._steer_gear = steer_gear self._mjcf_root.find('actuator', 'roll').gear[0] = self._roll_gear self._mjcf_root.find('actuator', 'steer').gear[0] = self._steer_gear # Initialize previous action. self._prev_action = np.zeros(shape=self.action_spec.shape, dtype=self.action_spec.dtype) def _build_observables(self): return BoxHeadObservables(self, camera_resolution=self._camera_resolution) @property def marker_geoms(self): geoms = [ self._mjcf_root.find('geom', 'arm_l'), self._mjcf_root.find('geom', 'arm_r'), self._mjcf_root.find('geom', 'eye_l'), self._mjcf_root.find('geom', 'eye_r'), ] if self._walker_id is None: geoms.append(self._mjcf_root.find('geom', 'head')) return geoms 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 set_velocity(self, physics, velocity=None, angular_velocity=None): if velocity is not None: if self._root_joints is not None: physics.bind(self._root_joints).qvel = velocity if angular_velocity is not None: # This walker can only rotate along the z-axis, so we extract only that # component from the angular_velocity. steer_joint = self._mjcf_root.find('joint', 'steer') if isinstance(angular_velocity, float): z_velocity = angular_velocity else: z_velocity = angular_velocity[2] physics.bind(steer_joint).qvel = z_velocity def initialize_episode(self, physics, random_state): if self._camera_control: _compensate_gravity(physics, self._mjcf_root.find('body', 'egocentric_camera')) self._prev_action = np.zeros(shape=self.action_spec.shape, dtype=self.action_spec.dtype) def apply_action(self, physics, action, random_state): super().apply_action(physics, action, random_state) # Updates previous action. self._prev_action[:] = action @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 observable_camera_joints(self): if self._camera_control: return ( self._mjcf_root.find('joint', 'camera_yaw'), self._mjcf_root.find('joint', 'camera_pitch'), ) return () @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'),) @property def prev_action(self): return self._prev_action
dm_control-main
dm_control/locomotion/soccer/boxhead.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 locomotion.tasks.soccer.""" import unittest from absl.testing import absltest from absl.testing import parameterized from dm_control import composer from dm_control import mjcf from dm_control.locomotion import soccer from dm_control.locomotion.soccer import camera from dm_control.locomotion.soccer import initializers from dm_control.mujoco.wrapper import mjbindings import numpy as np RGBA_BLUE = [.1, .1, .8, 1.] RGBA_RED = [.8, .1, .1, 1.] def _walker(name, walker_id, marker_rgba): return soccer.BoxHead( name=name, walker_id=walker_id, marker_rgba=marker_rgba, ) def _team_players(team_size, team, team_name, team_color): team_of_players = [] for i in range(team_size): team_of_players.append( soccer.Player(team, _walker("%s%d" % (team_name, i), i, team_color))) return team_of_players def _home_team(team_size): return _team_players(team_size, soccer.Team.HOME, "home", RGBA_BLUE) def _away_team(team_size): return _team_players(team_size, soccer.Team.AWAY, "away", RGBA_RED) def _env(players, disable_walker_contacts=True, observables=None, random_state=42, **task_kwargs): return composer.Environment( task=soccer.Task( players=players, arena=soccer.Pitch((20, 15)), observables=observables, disable_walker_contacts=disable_walker_contacts, **task_kwargs ), random_state=random_state, time_limit=1) def _observables_adder(observables_adder): if observables_adder == "core": return soccer.CoreObservablesAdder() if observables_adder == "core_interception": return soccer.MultiObservablesAdder( [soccer.CoreObservablesAdder(), soccer.InterceptionObservablesAdder()]) raise ValueError("Unrecognized observable_adder %s" % observables_adder) class TaskTest(parameterized.TestCase): def _assert_all_count_equal(self, list_of_lists): """Check all lists in the list are count equal.""" if not list_of_lists: return first = sorted(list_of_lists[0]) for other in list_of_lists[1:]: self.assertCountEqual(first, other) @parameterized.named_parameters( ("1vs1_core", 1, "core", 33, True), ("2vs2_core", 2, "core", 43, True), ("1vs1_interception", 1, "core_interception", 41, True), ("2vs2_interception", 2, "core_interception", 51, True), ("1vs1_core_contact", 1, "core", 33, False), ("2vs2_core_contact", 2, "core", 43, False), ("1vs1_interception_contact", 1, "core_interception", 41, False), ("2vs2_interception_contact", 2, "core_interception", 51, False), ) def test_step_environment(self, team_size, observables_adder, num_obs, disable_walker_contacts): env = _env( _home_team(team_size) + _away_team(team_size), observables=_observables_adder(observables_adder), disable_walker_contacts=disable_walker_contacts) self.assertLen(env.action_spec(), 2 * team_size) self.assertLen(env.observation_spec(), 2 * team_size) actions = [np.zeros(s.shape, s.dtype) for s in env.action_spec()] timestep = env.reset() for observation, spec in zip(timestep.observation, env.observation_spec()): self.assertLen(spec, num_obs) self.assertCountEqual(list(observation.keys()), list(spec.keys())) for key in observation.keys(): self.assertEqual(observation[key].shape, spec[key].shape) while not timestep.last(): timestep = env.step(actions) # TODO(b/124848293): consolidate environment stepping loop for task tests. @parameterized.named_parameters( ("1vs2", 1, 2, 38), ("2vs1", 2, 1, 38), ("3vs0", 3, 0, 38), ("0vs2", 0, 2, 33), ("2vs2", 2, 2, 43), ("0vs0", 0, 0, None), ) def test_num_players(self, home_size, away_size, num_observations): env = _env(_home_team(home_size) + _away_team(away_size)) self.assertLen(env.action_spec(), home_size + away_size) self.assertLen(env.observation_spec(), home_size + away_size) actions = [np.zeros(s.shape, s.dtype) for s in env.action_spec()] timestep = env.reset() # Members of the same team should have identical specs. self._assert_all_count_equal( [spec.keys() for spec in env.observation_spec()[:home_size]]) self._assert_all_count_equal( [spec.keys() for spec in env.observation_spec()[-away_size:]]) for observation, spec in zip(timestep.observation, env.observation_spec()): self.assertCountEqual(list(observation.keys()), list(spec.keys())) for key in observation.keys(): self.assertEqual(observation[key].shape, spec[key].shape) self.assertLen(spec, num_observations) while not timestep.last(): timestep = env.step(actions) self.assertLen(timestep.observation, home_size + away_size) self.assertLen(timestep.reward, home_size + away_size) for player_spec, player_reward in zip(env.reward_spec(), timestep.reward): player_spec.validate(player_reward) discount_spec = env.discount_spec() discount_spec.validate(timestep.discount) def test_all_contacts(self): env = _env(_home_team(1) + _away_team(1)) def _all_contact_configuration(physics, unused_random_state): walkers = [p.walker for p in env.task.players] ball = env.task.ball x, y, rotation = 0., 0., np.pi / 6. ball.set_pose(physics, [x, y, 5.]) ball.set_velocity( physics, velocity=np.zeros(3), angular_velocity=np.zeros(3)) x, y, rotation = 0., 0., np.pi / 3. quat = [np.cos(rotation / 2), 0, 0, np.sin(rotation / 2)] walkers[0].set_pose(physics, [x, y, 3.], quat) walkers[0].set_velocity( physics, velocity=np.zeros(3), angular_velocity=np.zeros(3)) x, y, rotation = 0., 0., np.pi / 3. + np.pi quat = [np.cos(rotation / 2), 0, 0, np.sin(rotation / 2)] walkers[1].set_pose(physics, [x, y, 1.], quat) walkers[1].set_velocity( physics, velocity=np.zeros(3), angular_velocity=np.zeros(3)) env.add_extra_hook("initialize_episode", _all_contact_configuration) actions = [np.zeros(s.shape, s.dtype) for s in env.action_spec()] timestep = env.reset() while not timestep.last(): timestep = env.step(actions) def test_symmetric_observations(self): env = _env(_home_team(1) + _away_team(1)) def _symmetric_configuration(physics, unused_random_state): walkers = [p.walker for p in env.task.players] ball = env.task.ball x, y, rotation = 0., 0., np.pi / 6. ball.set_pose(physics, [x, y, 0.5]) ball.set_velocity( physics, velocity=np.zeros(3), angular_velocity=np.zeros(3)) x, y, rotation = 5., 3., np.pi / 3. quat = [np.cos(rotation / 2), 0, 0, np.sin(rotation / 2)] walkers[0].set_pose(physics, [x, y, 0.], quat) walkers[0].set_velocity( physics, velocity=np.zeros(3), angular_velocity=np.zeros(3)) x, y, rotation = -5., -3., np.pi / 3. + np.pi quat = [np.cos(rotation / 2), 0, 0, np.sin(rotation / 2)] walkers[1].set_pose(physics, [x, y, 0.], quat) walkers[1].set_velocity( physics, velocity=np.zeros(3), angular_velocity=np.zeros(3)) env.add_extra_hook("initialize_episode", _symmetric_configuration) timestep = env.reset() obs_a, obs_b = timestep.observation self.assertCountEqual(list(obs_a.keys()), list(obs_b.keys())) for k in sorted(obs_a.keys()): o_a, o_b = obs_a[k], obs_b[k] self.assertTrue( np.allclose(o_a, o_b) or np.allclose(o_a, -o_b), k + " not equal:" + str(o_a) + ";" + str(o_b)) def test_symmetric_dynamic_observations(self): env = _env(_home_team(1) + _away_team(1)) def _symmetric_configuration(physics, unused_random_state): walkers = [p.walker for p in env.task.players] ball = env.task.ball x, y, rotation = 0., 0., np.pi / 6. ball.set_pose(physics, [x, y, 0.5]) # Ball shooting up. Walkers going tangent. ball.set_velocity(physics, velocity=[0., 0., 1.], angular_velocity=[0., 0., 0.]) x, y, rotation = 5., 3., np.pi / 3. quat = [np.cos(rotation / 2), 0, 0, np.sin(rotation / 2)] walkers[0].set_pose(physics, [x, y, 0.], quat) walkers[0].set_velocity(physics, velocity=[y, -x, 0.], angular_velocity=[0., 0., 0.]) x, y, rotation = -5., -3., np.pi / 3. + np.pi quat = [np.cos(rotation / 2), 0, 0, np.sin(rotation / 2)] walkers[1].set_pose(physics, [x, y, 0.], quat) walkers[1].set_velocity(physics, velocity=[y, -x, 0.], angular_velocity=[0., 0., 0.]) env.add_extra_hook("initialize_episode", _symmetric_configuration) timestep = env.reset() obs_a, obs_b = timestep.observation self.assertCountEqual(list(obs_a.keys()), list(obs_b.keys())) for k in sorted(obs_a.keys()): o_a, o_b = obs_a[k], obs_b[k] self.assertTrue( np.allclose(o_a, o_b) or np.allclose(o_a, -o_b), k + " not equal:" + str(o_a) + ";" + str(o_b)) def test_prev_actions(self): env = _env(_home_team(1) + _away_team(1)) actions = [] for i, player in enumerate(env.task.players): spec = player.walker.action_spec actions.append((i + 1) * np.ones(spec.shape, dtype=spec.dtype)) env.reset() timestep = env.step(actions) for walker_idx, obs in enumerate(timestep.observation): np.testing.assert_allclose( np.squeeze(obs["prev_action"], axis=0), actions[walker_idx], err_msg="Walker {}: incorrect previous action.".format(walker_idx)) @parameterized.named_parameters( dict(testcase_name="1vs2_draw", home_size=1, away_size=2, ball_vel_x=0, expected_home_score=0), dict(testcase_name="1vs2_home_score", home_size=1, away_size=2, ball_vel_x=50, expected_home_score=1), dict(testcase_name="2vs1_away_score", home_size=2, away_size=1, ball_vel_x=-50, expected_home_score=-1), dict(testcase_name="3vs0_home_score", home_size=3, away_size=0, ball_vel_x=50, expected_home_score=1), dict(testcase_name="0vs2_home_score", home_size=0, away_size=2, ball_vel_x=50, expected_home_score=1), dict(testcase_name="2vs2_away_score", home_size=2, away_size=2, ball_vel_x=-50, expected_home_score=-1), ) def test_scoring_rewards( self, home_size, away_size, ball_vel_x, expected_home_score): env = _env(_home_team(home_size) + _away_team(away_size)) def _score_configuration(physics, random_state): del random_state # Unused. # Send the ball shooting towards either the home or away goal. env.task.ball.set_pose(physics, [0., 0., 0.5]) env.task.ball.set_velocity(physics, velocity=[ball_vel_x, 0., 0.], angular_velocity=[0., 0., 0.]) env.add_extra_hook("initialize_episode", _score_configuration) actions = [np.zeros(s.shape, s.dtype) for s in env.action_spec()] # Disable contacts and gravity so that the ball follows a straight path. with env.physics.model.disable("contact", "gravity"): timestep = env.reset() with self.subTest("Reward and discount are None on the first timestep"): self.assertTrue(timestep.first()) self.assertIsNone(timestep.reward) self.assertIsNone(timestep.discount) # Step until the episode ends. timestep = env.step(actions) while not timestep.last(): self.assertTrue(timestep.mid()) # For non-terminal timesteps, the reward should always be 0 and the # discount should always be 1. np.testing.assert_array_equal(np.hstack(timestep.reward), 0.) self.assertEqual(timestep.discount, 1.) timestep = env.step(actions) # If a goal was scored then the epsiode should have ended with a discount of # 0. If neither team scored and the episode ended due to hitting the time # limit then the discount should be 1. with self.subTest("Correct terminal discount"): if expected_home_score != 0: expected_discount = 0. else: expected_discount = 1. self.assertEqual(timestep.discount, expected_discount) with self.subTest("Correct terminal reward"): reward = np.hstack(timestep.reward) np.testing.assert_array_equal(reward[:home_size], expected_home_score) np.testing.assert_array_equal(reward[home_size:], -expected_home_score) def test_throw_in(self): env = _env(_home_team(1) + _away_team(1)) def _throw_in_configuration(physics, unused_random_state): walkers = [p.walker for p in env.task.players] ball = env.task.ball x, y, rotation = 0., 3., np.pi / 6. ball.set_pose(physics, [x, y, 0.5]) # Ball shooting out of bounds. ball.set_velocity(physics, velocity=[0., 50., 0.], angular_velocity=[0., 0., 0.]) x, y, rotation = 0., -3., np.pi / 3. quat = [np.cos(rotation / 2), 0, 0, np.sin(rotation / 2)] walkers[0].set_pose(physics, [x, y, 0.], quat) walkers[0].set_velocity(physics, velocity=[0., 0., 0.], angular_velocity=[0., 0., 0.]) x, y, rotation = 0., -5., np.pi / 3. quat = [np.cos(rotation / 2), 0, 0, np.sin(rotation / 2)] walkers[1].set_pose(physics, [x, y, 0.], quat) walkers[1].set_velocity(physics, velocity=[0., 0., 0.], angular_velocity=[0., 0., 0.]) env.add_extra_hook("initialize_episode", _throw_in_configuration) actions = [np.zeros(s.shape, s.dtype) for s in env.action_spec()] timestep = env.reset() while not timestep.last(): timestep = env.step(actions) terminal_ball_vel = np.linalg.norm( timestep.observation[0]["ball_ego_linear_velocity"]) self.assertAlmostEqual(terminal_ball_vel, 0.) @parameterized.named_parameters(("score", 50., 0.), ("timeout", 0., 1.)) def test_terminal_discount(self, init_ball_vel_x, expected_terminal_discount): env = _env(_home_team(1) + _away_team(1)) def _initial_configuration(physics, unused_random_state): walkers = [p.walker for p in env.task.players] ball = env.task.ball x, y, rotation = 0., 0., np.pi / 6. ball.set_pose(physics, [x, y, 0.5]) # Ball shooting up. Walkers going tangent. ball.set_velocity(physics, velocity=[init_ball_vel_x, 0., 0.], angular_velocity=[0., 0., 0.]) x, y, rotation = 0., -3., np.pi / 3. quat = [np.cos(rotation / 2), 0, 0, np.sin(rotation / 2)] walkers[0].set_pose(physics, [x, y, 0.], quat) walkers[0].set_velocity(physics, velocity=[0., 0., 0.], angular_velocity=[0., 0., 0.]) x, y, rotation = 0., 3., np.pi / 3. quat = [np.cos(rotation / 2), 0, 0, np.sin(rotation / 2)] walkers[1].set_pose(physics, [x, y, 0.], quat) walkers[1].set_velocity(physics, velocity=[0., 0., 0.], angular_velocity=[0., 0., 0.]) env.add_extra_hook("initialize_episode", _initial_configuration) actions = [np.zeros(s.shape, s.dtype) for s in env.action_spec()] timestep = env.reset() while not timestep.last(): timestep = env.step(actions) self.assertEqual(timestep.discount, expected_terminal_discount) @parameterized.named_parameters(("reset_only", False), ("step", True)) def test_render(self, take_step): height = 100 width = 150 tracking_cameras = [] for min_distance in [1, 1, 2]: tracking_cameras.append( camera.MultiplayerTrackingCamera( min_distance=min_distance, distance_factor=1, smoothing_update_speed=0.1, width=width, height=height, )) env = _env(_home_team(1) + _away_team(1), tracking_cameras=tracking_cameras) env.reset() if take_step: actions = [np.zeros(s.shape, s.dtype) for s in env.action_spec()] env.step(actions) rendered_frames = [cam.render() for cam in tracking_cameras] for frame in rendered_frames: assert frame.shape == (height, width, 3) self.assertTrue(np.array_equal(rendered_frames[0], rendered_frames[1])) self.assertFalse(np.array_equal(rendered_frames[1], rendered_frames[2])) class UniformInitializerTest(parameterized.TestCase): @parameterized.parameters([0.3, 0.7]) def test_walker_position(self, spawn_ratio): initializer = initializers.UniformInitializer(spawn_ratio=spawn_ratio) env = _env(_home_team(2) + _away_team(2), initializer=initializer) root_bodies = [p.walker.root_body for p in env.task.players] xy_bounds = np.asarray(env.task.arena.size) * spawn_ratio env.reset() xy = env.physics.bind(root_bodies).xpos[:, :2].copy() with self.subTest("X and Y positions within bounds"): if np.any(abs(xy) > xy_bounds): self.fail("Walker(s) spawned out of bounds. Expected abs(xy) " "<= {}, got:\n{}".format(xy_bounds, xy)) env.reset() xy2 = env.physics.bind(root_bodies).xpos[:, :2].copy() with self.subTest("X and Y positions change after reset"): if np.any(xy == xy2): self.fail("Walker(s) have the same X and/or Y coordinates before and " "after reset. Before: {}, after: {}.".format(xy, xy2)) def test_walker_rotation(self): initializer = initializers.UniformInitializer() env = _env(_home_team(2) + _away_team(2), initializer=initializer) def quats_to_eulers(quats): eulers = np.empty((len(quats), 3), dtype=np.double) dt = 1. for i, quat in enumerate(quats): mjbindings.mjlib.mju_quat2Vel(eulers[i], quat, dt) return eulers # TODO(b/132671988): Switch to using `get_pose` to get the quaternion once # `BoxHead.get_pose` and `BoxHead.set_pose` are # implemented in a consistent way. def get_quat(walker): return env.physics.bind(walker.root_body).xquat env.reset() quats = [get_quat(p.walker) for p in env.task.players] eulers = quats_to_eulers(quats) with self.subTest("Rotation is about the Z-axis only"): np.testing.assert_array_equal(eulers[:, :2], 0.) env.reset() quats2 = [get_quat(p.walker) for p in env.task.players] eulers2 = quats_to_eulers(quats2) with self.subTest("Rotation about Z changes after reset"): if np.any(eulers[:, 2] == eulers2[:, 2]): self.fail("Walker(s) have the same rotation about Z before and " "after reset. Before: {}, after: {}." .format(eulers[:, 2], eulers2[:, 2])) # TODO(b/132759890): Remove `expectedFailure` decorator once `set_velocity` # works correctly for the `BoxHead` walker. @unittest.expectedFailure def test_walker_velocity(self): initializer = initializers.UniformInitializer() env = _env(_home_team(2) + _away_team(2), initializer=initializer) root_joints = [] non_root_joints = [] for player in env.task.players: attachment_frame = mjcf.get_attachment_frame(player.walker.mjcf_model) root_joints.extend( attachment_frame.find_all("joint", immediate_children_only=True)) non_root_joints.extend(player.walker.mjcf_model.find_all("joint")) # Assign a non-zero sentinel value to the velocities of all root and # non-root joints. sentinel_velocity = 3.14 env.physics.bind(root_joints + non_root_joints).qvel = sentinel_velocity # The initializer should zero the velocities of the root joints, but not the # non-root joints. initializer(env.task, env.physics, env.random_state) np.testing.assert_array_equal(env.physics.bind(non_root_joints).qvel, sentinel_velocity) np.testing.assert_array_equal(env.physics.bind(root_joints).qvel, 0.) @parameterized.parameters([ dict(spawn_ratio=0.3, init_ball_z=0.4), dict(spawn_ratio=0.5, init_ball_z=0.6), ]) def test_ball_position(self, spawn_ratio, init_ball_z): initializer = initializers.UniformInitializer( spawn_ratio=spawn_ratio, init_ball_z=init_ball_z) env = _env(_home_team(2) + _away_team(2), initializer=initializer) xy_bounds = np.asarray(env.task.arena.size) * spawn_ratio env.reset() position, _ = env.task.ball.get_pose(env.physics) xyz = position.copy() with self.subTest("X and Y positions within bounds"): if np.any(abs(xyz[:2]) > xy_bounds): self.fail("Ball spawned out of bounds. Expected abs(xy) " "<= {}, got:\n{}".format(xy_bounds, xyz[:2])) with self.subTest("Z position equal to `init_ball_z`"): self.assertEqual(xyz[2], init_ball_z) env.reset() position, _ = env.task.ball.get_pose(env.physics) xyz2 = position.copy() with self.subTest("X and Y positions change after reset"): if np.any(xyz[:2] == xyz2[:2]): self.fail("Ball has the same XY position before and after reset. " "Before: {}, after: {}.".format(xyz[:2], xyz2[:2])) def test_ball_velocity(self): initializer = initializers.UniformInitializer() env = _env(_home_team(1) + _away_team(1), initializer=initializer) ball_root_joint = mjcf.get_frame_freejoint(env.task.ball.mjcf_model) # Set the velocities of the ball root joint to a non-zero sentinel value. env.physics.bind(ball_root_joint).qvel = 3.14 initializer(env.task, env.physics, env.random_state) # The initializer should set the ball velocity to zero. ball_velocity = env.physics.bind(ball_root_joint).qvel np.testing.assert_array_equal(ball_velocity, 0.) class _ScoringInitializer(soccer.Initializer): """Initialize the ball for home team to repeatedly score goals.""" def __init__(self): self._num_calls = 0 @property def num_calls(self): return self._num_calls def __call__(self, task, physics, random_state): # Initialize `ball` along the y-axis with a positive y-velocity. task.ball.set_pose(physics, [2.0, 0.0, 1.5]) task.ball.set_velocity( physics, velocity=[100.0, 0.0, 0.0], angular_velocity=0.) for i, player in enumerate(task.players): player.walker.reinitialize_pose(physics, random_state) (_, _, z), quat = player.walker.get_pose(physics) player.walker.set_pose(physics, [-i * 5, 0.0, z], quat) player.walker.set_velocity(physics, velocity=0., angular_velocity=0.) self._num_calls += 1 class MultiturnTaskTest(parameterized.TestCase): def test_multiple_goals(self): initializer = _ScoringInitializer() time_limit = 1.0 control_timestep = 0.025 env = composer.Environment( task=soccer.MultiturnTask( players=_home_team(1) + _away_team(1), arena=soccer.Pitch((20, 15), field_box=True), # disable throw-in. initializer=initializer, control_timestep=control_timestep), time_limit=time_limit) timestep = env.reset() num_steps = 0 rewards = [np.zeros(s.shape, s.dtype) for s in env.reward_spec()] while not timestep.last(): timestep = env.step([spec.generate_value() for spec in env.action_spec()]) for reward, r_t in zip(rewards, timestep.reward): reward += r_t num_steps += 1 self.assertEqual(num_steps, time_limit / control_timestep) num_scores = initializer.num_calls - 1 # discard initialization. self.assertEqual(num_scores, 6) self.assertEqual(rewards, [ np.full((), num_scores, np.float32), np.full((), -num_scores, np.float32) ]) if __name__ == "__main__": absltest.main()
dm_control-main
dm_control/locomotion/soccer/task_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.soccer.boxhead.""" from absl.testing import absltest from absl.testing import parameterized from dm_control.locomotion.soccer import boxhead class BoxheadTest(parameterized.TestCase): @parameterized.parameters( dict(camera_control=True, walker_id=None), dict(camera_control=False, walker_id=None), dict(camera_control=True, walker_id=0), dict(camera_control=False, walker_id=10)) def test_instantiation(self, camera_control, walker_id): boxhead.BoxHead(marker_rgba=[.8, .1, .1, 1.], camera_control=camera_control, walker_id=walker_id) @parameterized.parameters(-1, 11) def test_invalid_walker_id(self, walker_id): with self.assertRaisesWithLiteralMatch( ValueError, boxhead._INVALID_WALKER_ID.format(walker_id)): boxhead.BoxHead(walker_id=walker_id) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/soccer/boxhead_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.soccer.soccer_ball.""" from absl.testing import absltest from dm_control import composer from dm_control import mjcf from dm_control.entities import props from dm_control.locomotion.soccer import soccer_ball from dm_control.locomotion.soccer import team import numpy as np class SoccerBallTest(absltest.TestCase): def test_detect_hit(self): arena = composer.Arena() ball = soccer_ball.SoccerBall(radius=0.35, mass=0.045, name='test_ball') player = team.Player( team=team.Team.HOME, walker=props.Primitive(geom_type='sphere', size=(0.1,), name='home')) arena.add_free_entity(player.walker) ball.register_player(player) arena.add_free_entity(ball) random_state = np.random.RandomState(42) physics = mjcf.Physics.from_mjcf_model(arena.mjcf_model) physics.step() ball.initialize_episode(physics, random_state) ball.before_step(physics, random_state) self.assertEqual(ball.hit, False) self.assertEqual(ball.repossessed, False) self.assertEqual(ball.intercepted, False) self.assertIsNone(ball.last_hit) self.assertIsNone(ball.dist_between_last_hits) ball.after_substep(physics, random_state) ball.after_step(physics, random_state) self.assertEqual(ball.hit, True) self.assertEqual(ball.repossessed, True) self.assertEqual(ball.intercepted, True) self.assertEqual(ball.last_hit, player) # Only one hit registered. self.assertIsNone(ball.dist_between_last_hits) def test_has_tracking_cameras(self): ball = soccer_ball.SoccerBall(radius=0.35, mass=0.045, name='test_ball') expected_camera_names = ['ball_cam_near', 'ball_cam', 'ball_cam_far'] camera_names = [cam.name for cam in ball.mjcf_model.find_all('camera')] self.assertCountEqual(expected_camera_names, camera_names) def test_damp_ratio_is_valid(self): with self.assertRaisesRegex(ValueError, 'Invalid `damp_ratio`.*'): soccer_ball.SoccerBall(damp_ratio=-0.5) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/locomotion/soccer/soccer_ball_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. # ============================================================================ """Interactive viewer for MuJoCo soccer enviornmnet.""" import functools from absl import app from absl import flags from dm_control import viewer from dm_control.locomotion import soccer FLAGS = flags.FLAGS flags.DEFINE_enum("walker_type", "BOXHEAD", ["BOXHEAD", "ANT", "HUMANOID"], "The type of walker to explore with.") flags.DEFINE_bool( "enable_field_box", True, "If `True`, enable physical bounding box enclosing the ball" " (but not the players).") flags.DEFINE_bool("disable_walker_contacts", False, "If `True`, disable walker-walker contacts.") flags.DEFINE_bool( "terminate_on_goal", False, "If `True`, the episode terminates upon a goal being scored.") def main(argv): if len(argv) > 1: raise app.UsageError("Too many command-line arguments.") viewer.launch( environment_loader=functools.partial( soccer.load, team_size=2, walker_type=soccer.WalkerType[FLAGS.walker_type], disable_walker_contacts=FLAGS.disable_walker_contacts, enable_field_box=FLAGS.enable_field_box, keep_aspect_ratio=True, terminate_on_goal=FLAGS.terminate_on_goal)) if __name__ == "__main__": app.run(main)
dm_control-main
dm_control/locomotion/soccer/explore.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. # ============================================================================ """A soccer pitch with home/away goals and one field with position detection.""" import colorsys import os from absl import logging from dm_control import composer from dm_control import mjcf from dm_control.composer.variation import distributions from dm_control.entities import props from dm_control.locomotion.soccer import team import numpy as np from dm_control.utils import io as resources _ASSETS_PATH = os.path.join(os.path.dirname(__file__), 'assets', 'pitch') def _get_texture(name): contents = resources.GetResource( os.path.join(_ASSETS_PATH, '{}.png'.format(name))) return mjcf.Asset(contents, '.png') _TOP_CAMERA_Y_PADDING_FACTOR = 1.1 _TOP_CAMERA_DISTANCE = 95. _WALL_HEIGHT = 10. _WALL_THICKNESS = .5 _SIDE_WIDTH = 32. / 6. _GROUND_GEOM_GRID_RATIO = 1. / 100 # Grid size for lighting. _FIELD_BOX_CONTACT_BIT = 1 << 7 # Use a higher bit to prevent potential clash. _DEFAULT_PITCH_SIZE = (12, 9) _DEFAULT_GOAL_LENGTH_RATIO = 0.33 # Goal length / pitch width. _GOALPOST_RELATIVE_SIZE = 0.07 # Ratio of the goalpost radius to goal size. _NET_RELATIVE_SIZE = 0.01 # Ratio of the net thickness to goal size. _SUPPORT_POST_RATIO = 0.75 # Ratio of support post to goalpost radius. # Goalposts defined in the unit box [-1, 1]**3 facing to the positive X. _GOALPOSTS = {'right_post': (1, -1, -1, 1, -1, 1), 'left_post': (1, 1, -1, 1, 1, 1), 'top_post': (1, -1, 1, 1, 1, 1), 'right_base': (1, -1, -1, -1, -1, -1), 'left_base': (1, 1, -1, -1, 1, -1), 'back_base': (-1, -1, -1, -1, 1, -1), 'right_support': (-1, -1, -1, .2, -1, 1), 'right_top_support': (.2, -1, 1, 1, -1, 1), 'left_support': (-1, 1, -1, .2, 1, 1), 'left_top_support': (.2, 1, 1, 1, 1, 1)} # Vertices of net polygons, reshaped to 4x3 arrays. _NET = {'top': _GOALPOSTS['right_top_support'] + _GOALPOSTS['left_top_support'], 'back': _GOALPOSTS['right_support'] + _GOALPOSTS['left_support'], 'left': _GOALPOSTS['left_base'] + _GOALPOSTS['left_top_support'], 'right': _GOALPOSTS['right_base'] + _GOALPOSTS['right_top_support']} _NET = {key: np.array(value).reshape(4, 3) for key, value in _NET.items()} # Number of visual hoarding boxes per side of the pitch. _NUM_HOARDING = 30 def _top_down_cam_fovy(size, top_camera_distance): return (360 / np.pi) * np.arctan2(_TOP_CAMERA_Y_PADDING_FACTOR * max(size), top_camera_distance) def _wall_pos_xyaxes(size): """Infers position and size of bounding walls given pitch size. Walls are placed around `ground_geom` that represents the pitch. Note that the ball cannot travel beyond `field` but walkers can walk outside of the `field` but not the surrounding walls. Args: size: a tuple of (length, width) of the pitch. Returns: a list of 4 tuples, each representing the position and xyaxes of a wall plane. In order, walls are placed along x-negative, x-positive, y-negative, y-positive relative the center of the pitch. """ return [ ((0., -size[1], 0.), (-1, 0, 0, 0, 0, 1)), ((0., size[1], 0.), (1, 0, 0, 0, 0, 1)), ((-size[0], 0., 0.), (0, 1, 0, 0, 0, 1)), ((size[0], 0., 0.), (0, -1, 0, 0, 0, 1)), ] def _fieldbox_pos_size(field_size, goal_size): """Infers position and size of fieldbox given pitch size. Walls are placed around the field so that the ball cannot travel beyond `field` but walkers can walk outside of the `field` but not the surrounding pitch. Holes are left in the fieldbox at the goal positions to enable scoring. Args: field_size: a tuple of (length, width) of the field. goal_size: a tuple of (unused_depth, width, height) of the goal. Returns: a list of 8 tuples, each representing the position and size of a wall box. """ box_half_height = 20. corner_pos_y = 0.5 * (field_size[1] + goal_size[1]) corner_size_y = 0.5 * (field_size[1] - goal_size[1]) thickness = 1.0 top_pos_z = box_half_height + goal_size[2] top_size_z = box_half_height - goal_size[2] wall_offset_x = field_size[0] + thickness wall_offset_y = field_size[1] + thickness return [ ((0., -wall_offset_y, box_half_height), (field_size[0], thickness, box_half_height)), # near side ((0., wall_offset_y, box_half_height), (field_size[0], thickness, box_half_height)), # far side ((-wall_offset_x, -corner_pos_y, box_half_height), (thickness, corner_size_y, box_half_height)), # left near corner ((-wall_offset_x, 0., top_pos_z), (thickness, goal_size[1], top_size_z)), # left top corner ((-wall_offset_x, corner_pos_y, box_half_height), (thickness, corner_size_y, box_half_height)), # left far corner ((wall_offset_x, -corner_pos_y, box_half_height), (thickness, corner_size_y, box_half_height)), # right near corner ((wall_offset_x, 0., top_pos_z), (thickness, goal_size[1], top_size_z)), # right top corner ((wall_offset_x, corner_pos_y, box_half_height), (thickness, corner_size_y, box_half_height)), # right far corner ] def _roof_size(size): return (size[0], size[1], _WALL_THICKNESS) def _reposition_corner_lights(lights, size): """Place four lights at the corner of the pitch.""" mean_size = 0.5 * sum(size) height = mean_size * 2/3 counter = 0 for x in [-size[0], size[0]]: for y in [-size[1], size[1]]: position = np.array((x, y, height)) direction = -np.array((x, y, height*2)) lights[counter].pos = position lights[counter].dir = direction counter += 1 def _goalpost_radius(size): """Compute goal post radius as scaled average goal size.""" return _GOALPOST_RELATIVE_SIZE * sum(size) / 3. def _post_radius(goalpost_name, goalpost_radius): """Compute the radius of a specific goalpost.""" radius = goalpost_radius if 'top' in goalpost_name: radius *= 1.01 # Prevent z-fighting at the corners. if 'support' in goalpost_name: radius *= _SUPPORT_POST_RATIO # Suport posts are a bit narrower. return radius def _goalpost_fromto(unit_fromto, size, pos, direction): """Rotate, scale and translate the `fromto` attribute of a goalpost. The goalposts are defined in the unit cube [-1, 1]**3 using MuJoCo fromto specifier for capsules, they are then flipped according to whether they face in the +x or -x, scaled and moved. Args: unit_fromto: two concatenated 3-vectors in the unit cube in xyzxyz order. size: a 3-vector, scaling of the goal. pos: a 3-vector, goal position. direction: a 3-vector, either (1,1,1) or (-1,-1,1), direction of the goal along the x-axis. Returns: two concatenated 3-vectors, the `fromto` of a goal geom. """ fromto = np.array(unit_fromto) * np.hstack((direction, direction)) return fromto*np.array(size+size) + np.array(pos+pos) class Goal(props.PositionDetector): """Goal for soccer-like games: A PositionDetector with goalposts.""" def _make_net_vertices(self, size=(1, 1, 1)): """Make vertices for the four net meshes by offsetting net polygons.""" thickness = _NET_RELATIVE_SIZE * sum(size) / 3 # Get mesh offsets, compensate for mesh.scale deformation. dx = np.array((thickness / size[0], 0, 0)) dy = np.array((0, thickness / size[1], 0)) dz = np.array((0, 0, thickness / size[2])) # Make mesh vertices with specified thickness. top = [v+dz for v in _NET['top']] + [v-dz for v in _NET['top']] right = [v+dy for v in _NET['right']] + [v-dy for v in _NET['right']] left = [v+dy for v in _NET['left']] + [v-dy for v in _NET['left']] back = ([v+dz for v in _NET['back'] if v[2] == 1] + [v-dz for v in _NET['back'] if v[2] == 1] + [v+dx for v in _NET['back'] if v[2] == -1] + [v-dx for v in _NET['back'] if v[2] == -1]) vertices = {'top': top, 'back': back, 'left': left, 'right': right} return {key: (val*self._direction).flatten() for key, val in vertices.items()} def _move_goal(self, pos, size): """Translate and scale the goal.""" for geom in self._goal_geoms: unit_fromto = _GOALPOSTS[geom.name] geom.fromto = _goalpost_fromto(unit_fromto, size, pos, self._direction) geom.size = (_post_radius(geom.name, self._goalpost_radius),) if self._make_net: net_vertices = self._make_net_vertices(size) for geom in self._net_geoms: geom.pos = pos geom.mesh.vertex = net_vertices[geom.mesh.name] geom.mesh.scale = size def _build(self, direction, net_rgba=(1, 1, 1, .15), make_net=True, **kwargs): """Builds the goalposts and net. Args: direction: Is the goal oriented towards positive or negative x-axis. net_rgba: rgba value of the net geoms. make_net: Where to add net geoms. **kwargs: arguments of PositionDetector superclass, see therein. Raises: ValueError: If either `pos` or `size` arrays are not of length 3. ValueError: If direction in not 1 or -1. """ if len(kwargs['size']) != 3 or len(kwargs['pos']) != 3: raise ValueError('Only 3D Goals are supported.') if direction not in [1, -1]: raise ValueError('direction must be either 1 or -1.') # Flip both x and y, to maintain left / right name correctness. self._direction = np.array((direction, direction, 1)) self._make_net = make_net # Force the underlying PositionDetector to a non visible site group. kwargs['visible'] = False # Make a Position_Detector. super()._build(retain_substep_detections=True, **kwargs) # Add goalpost geoms. size = kwargs['size'] pos = kwargs['pos'] self._goalpost_radius = _goalpost_radius(size) self._goal_geoms = [] for geom_name, unit_fromto in _GOALPOSTS.items(): geom_fromto = _goalpost_fromto(unit_fromto, size, pos, self._direction) geom_size = (_post_radius(geom_name, self._goalpost_radius),) self._goal_geoms.append( self._mjcf_root.worldbody.add( 'geom', type='capsule', name=geom_name, size=geom_size, fromto=geom_fromto, rgba=self.goalpost_rgba)) # Add net meshes and geoms. if self._make_net: net_vertices = self._make_net_vertices() self._net_geoms = [] for name, vertex in net_vertices.items(): mesh = self._mjcf_root.asset.add('mesh', name=name, vertex=vertex) geom = self._mjcf_root.worldbody.add('geom', type='mesh', mesh=mesh, name=name, rgba=net_rgba, contype=0, conaffinity=0) self._net_geoms.append(geom) def resize(self, pos, size): """Call PositionDetector.resize(), move the goal.""" super().resize(pos, size) self._goalpost_radius = _goalpost_radius(size) self._move_goal(pos, size) def set_position(self, physics, pos): """Call PositionDetector.set_position(), move the goal.""" super().set_position(pos) size = 0.5*(self.upper - self.lower) self._move_goal(pos, size) def _update_detection(self, physics): """Call PositionDetector._update_detection(), then recolor the goalposts.""" super()._update_detection(physics) if self._detected and not self._previously_detected: physics.bind(self._goal_geoms).rgba = self.goalpost_detected_rgba elif self._previously_detected and not self._detected: physics.bind(self._goal_geoms).rgba = self.goalpost_rgba @property def goalpost_rgba(self): """Goalposts are always opaque.""" rgba = self._rgba.copy() rgba[3] = 1 return rgba @property def goalpost_detected_rgba(self): """Goalposts are always opaque.""" detected_rgba = self._detected_rgba.copy() detected_rgba[3] = 1 return detected_rgba class Pitch(composer.Arena): """A pitch with a plane, two goals and a field with position detection.""" def _build(self, size=_DEFAULT_PITCH_SIZE, goal_size=None, top_camera_distance=_TOP_CAMERA_DISTANCE, field_box=False, field_box_offset=0.0, hoarding_color_scheme_id=0, name='pitch'): """Construct a pitch with walls and position detectors. Args: size: a tuple of (length, width) of the pitch. goal_size: optional (depth, width, height) indicating the goal size. If not specified, the goal size is inferred from pitch size with a fixed default ratio. top_camera_distance: the distance of the top-down camera to the pitch. field_box: adds a "field box" that collides with the ball but not the walkers. field_box_offset: offset for the fieldbox if used. hoarding_color_scheme_id: An integer with value 0, 1, 2, or 3, specifying a preset scheme for the hoarding colors. name: the name of this arena. """ super()._build(name=name) self._size = size self._goal_size = goal_size self._top_camera_distance = top_camera_distance self._hoarding_color_scheme_id = hoarding_color_scheme_id self._top_camera = self._mjcf_root.worldbody.add( 'camera', name='top_down', pos=[0, 0, top_camera_distance], zaxis=[0, 0, 1], fovy=_top_down_cam_fovy(self._size, top_camera_distance)) # Set the `extent`, an "average distance" to 0.1 * pitch length. extent = 0.1 * max(self._size) self._mjcf_root.statistic.extent = extent self._mjcf_root.statistic.center = (0, 0, extent) # The near and far clipping planes are scaled by `extent`. self._mjcf_root.visual.map.zfar = 50 # 5 pitch lengths self._mjcf_root.visual.map.znear = 0.1 / extent # 10 centimeters # Add skybox. self._mjcf_root.asset.add( 'texture', name='skybox', type='skybox', builtin='gradient', rgb1=(.7, .9, .9), rgb2=(.03, .09, .27), width=400, height=400) # Add and position corner lights. self._corner_lights = [self._mjcf_root.worldbody.add('light', cutoff=60) for _ in range(4)] _reposition_corner_lights(self._corner_lights, size) # Increase shadow resolution, (default is 1024). self._mjcf_root.visual.quality.shadowsize = 8192 # Build groundplane. if len(self._size) != 2: raise ValueError('`size` should be a sequence of length 2: got {!r}' .format(self._size)) self._field_texture = self._mjcf_root.asset.add( 'texture', type='2d', file=_get_texture('pitch_nologo_l'), name='fieldplane') self._field_material = self._mjcf_root.asset.add( 'material', name='fieldplane', texture=self._field_texture) self._ground_geom = self._mjcf_root.worldbody.add( 'geom', name='ground', type='plane', material=self._field_material, size=list(self._size) + [max(self._size) * _GROUND_GEOM_GRID_RATIO]) # Build walls. self._walls = [] for wall_pos, wall_xyaxes in _wall_pos_xyaxes(self._size): self._walls.append( self._mjcf_root.worldbody.add( 'geom', type='plane', rgba=[.1, .1, .1, .8], pos=wall_pos, size=[1e-7, 1e-7, 1e-7], xyaxes=wall_xyaxes)) # Build goal position detectors. # If field_box is enabled, offset goal by 1.0 such that ball reaches the # goal position detector before bouncing off the field_box. self._fb_offset = field_box_offset if field_box else 0.0 goal_size = self._get_goal_size() self._home_goal = Goal( direction=1, make_net=False, pos=(-self._size[0] + goal_size[0] + self._fb_offset, 0, goal_size[2]), size=goal_size, rgba=(.2, .2, 1, 0.5), visible=True, name='home_goal') self.attach(self._home_goal) self._away_goal = Goal( direction=-1, make_net=False, pos=(self._size[0] - goal_size[0] - self._fb_offset, 0, goal_size[2]), size=goal_size, rgba=(1, .2, .2, 0.5), visible=True, name='away_goal') self.attach(self._away_goal) # Build inverted field position detectors. self._field = props.PositionDetector( pos=(0, 0), size=(self._size[0] - 2 * goal_size[0], self._size[1] - 2 * goal_size[0]), inverted=True, visible=False, name='field') self.attach(self._field) # Build field perimeter. def _visual_plane(): return self._mjcf_root.worldbody.add( 'geom', type='plane', size=(1, 1, 1), rgba=(0.306, 0.682, 0.223, 1), contype=0, conaffinity=0) self._perimeter = [_visual_plane() for _ in range(8)] self._update_perimeter() # Build field box. self._field_box = [] if field_box: for box_pos, box_size in _fieldbox_pos_size( (self._field.upper - self._field.lower) / 2.0, goal_size): self._field_box.append( self._mjcf_root.worldbody.add( 'geom', type='box', rgba=[.3, .3, .3, .0], pos=box_pos, size=box_size)) # Build hoarding sites. def _box_site(): return self._mjcf_root.worldbody.add('site', type='box', size=(1, 1, 1)) self._hoarding = [_box_site() for _ in range(4 * _NUM_HOARDING)] self._update_hoarding() def _update_hoarding(self): # Resize, reposition and re-color visual perimeter box geoms. num_boxes = _NUM_HOARDING counter = 0 for dim in [0, 1]: # Semantics are [x, y] width = self._get_goal_size()[2] / 8 # Eighth of the goal height. height = self._get_goal_size()[2] / 2 # Half of the goal height. length = self._size[dim] if dim == 1: # Stretch the y-dim length in order to cover the corners. length += 2 * width box_size = height * np.ones(3) box_size[dim] = length / num_boxes box_size[1-dim] = width dim_pos = np.linspace(-length, length, num_boxes, endpoint=False) dim_pos += length / num_boxes # Offset to center. for sign in [-1, 1]: alt_pos = sign * (self._size[1-dim] * np.ones(num_boxes) + width) dim_alt = (dim_pos, alt_pos) for box in range(num_boxes): box_pos = np.array((dim_alt[dim][box], dim_alt[1-dim][box], width)) if self._hoarding_color_scheme_id == 0: # Red to blue through green + blue hoarding behind blue goal angle = np.pi + np.arctan2(box_pos[0], -np.abs(box_pos[1])) elif self._hoarding_color_scheme_id == 1: # Red to blue through green + blue hoarding behind red goal angle = np.arctan2(box_pos[0], np.abs(box_pos[1])) elif self._hoarding_color_scheme_id == 2: # Red to blue through purple + blue hoarding behind red goal angle = np.arctan2(box_pos[0], -np.abs(box_pos[1])) elif self._hoarding_color_scheme_id == 3: # Red to blue through purple + blue hoarding behind blue goal angle = np.pi + np.arctan2(box_pos[0], np.abs(box_pos[1])) hue = 0.5 + angle / (2*np.pi) # In [0, 1] hue_offset = .25 hue = (hue - hue_offset) % 1.0 # Apply offset and wrap back to [0, 1] saturation = .7 value = 1.0 col_r, col_g, col_b = colorsys.hsv_to_rgb(hue, saturation, value) self._hoarding[counter].pos = box_pos self._hoarding[counter].size = box_size self._hoarding[counter].rgba = (col_r, col_g, col_b, 1.) counter += 1 def _update_perimeter(self): # Resize and reposition visual perimeter plane geoms. width = self._get_goal_size()[0] counter = 0 for x in [-1, 0, 1]: for y in [-1, 0, 1]: if x == 0 and y == 0: continue size_0 = self._size[0]-2*width if x == 0 else width size_1 = self._size[1]-2*width if y == 0 else width size = [size_0, size_1, max(self._size) * _GROUND_GEOM_GRID_RATIO] pos = (x*(self._size[0]-width), y*(self._size[1]-width), 0) self._perimeter[counter].size = size self._perimeter[counter].pos = pos counter += 1 def _get_goal_size(self): goal_size = self._goal_size if goal_size is None: goal_size = ( _SIDE_WIDTH / 2, self._size[1] * _DEFAULT_GOAL_LENGTH_RATIO, _SIDE_WIDTH / 2, ) return goal_size def register_ball(self, ball): self._home_goal.register_entities(ball) self._away_goal.register_entities(ball) if self._field_box: # Geoms a and b collides if: # (a.contype & b.conaffinity) || (b.contype & a.conaffinity) != 0. # See: http://www.mujoco.org/book/computation.html#Collision ball.geom.contype = (ball.geom.contype or 1) | _FIELD_BOX_CONTACT_BIT for wall in self._field_box: wall.conaffinity = _FIELD_BOX_CONTACT_BIT wall.contype = _FIELD_BOX_CONTACT_BIT else: self._field.register_entities(ball) def detected_goal(self): """Returning the team that scored a goal.""" if self._home_goal.detected_entities: return team.Team.AWAY if self._away_goal.detected_entities: return team.Team.HOME return None def detected_off_court(self): return self._field.detected_entities @property def size(self): return self._size @property def home_goal(self): return self._home_goal @property def away_goal(self): return self._away_goal @property def field(self): return self._field @property def ground_geom(self): return self._ground_geom class RandomizedPitch(Pitch): """RandomizedPitch that randomizes its size between (min_size, max_size).""" def __init__(self, min_size, max_size, randomizer=None, keep_aspect_ratio=False, goal_size=None, field_box=False, field_box_offset=0.0, top_camera_distance=_TOP_CAMERA_DISTANCE, name='randomized_pitch'): """Construct a randomized pitch. Args: min_size: a tuple of minimum (length, width) of the pitch. max_size: a tuple of maximum (length, width) of the pitch. randomizer: a callable that returns ratio between [0., 1.] that scales between min_size, max_size. keep_aspect_ratio: if `True`, keep the aspect ratio constant during randomization. goal_size: optional (depth, width, height) indicating the goal size. If not specified, the goal size is inferred from pitch size with a fixed default ratio. field_box: optional indicating if we should construct field box containing the ball (but not the walkers). field_box_offset: offset for the fieldbox if used. top_camera_distance: the distance of the top-down camera to the pitch. name: the name of this arena. """ super().__init__( size=max_size, goal_size=goal_size, top_camera_distance=top_camera_distance, field_box=field_box, field_box_offset=field_box_offset, name=name) self._min_size = min_size self._max_size = max_size self._randomizer = randomizer or distributions.Uniform() self._keep_aspect_ratio = keep_aspect_ratio # Sample a new size and regenerate the soccer pitch. logging.info('%s between (%s, %s) with %s', self.__class__.__name__, min_size, max_size, self._randomizer) def _resize_goals(self, goal_size): self._home_goal.resize( pos=(-self._size[0] + goal_size[0] + self._fb_offset, 0, goal_size[2]), size=goal_size) self._away_goal.resize( pos=(self._size[0] - goal_size[0] - self._fb_offset, 0, goal_size[2]), size=goal_size) def initialize_episode_mjcf(self, random_state): super().initialize_episode_mjcf(random_state) min_len, min_wid = self._min_size max_len, max_wid = self._max_size if self._keep_aspect_ratio: len_ratio = self._randomizer(random_state=random_state) wid_ratio = len_ratio else: len_ratio = self._randomizer(random_state=random_state) wid_ratio = self._randomizer(random_state=random_state) self._size = (min_len + len_ratio * (max_len - min_len), min_wid + wid_ratio * (max_wid - min_wid)) # Reset top_down camera field of view. self._top_camera.fovy = _top_down_cam_fovy(self._size, self._top_camera_distance) # Resize ground perimeter. self._update_perimeter() # Resize and reposition walls and roof geoms. for i, (wall_pos, _) in enumerate(_wall_pos_xyaxes(self._size)): self._walls[i].pos = wall_pos goal_size = self._get_goal_size() self._resize_goals(goal_size) # Resize inverted field position detectors. field_size = (self._size[0] -2*goal_size[0], self._size[1] -2*goal_size[0]) self._field.resize(pos=(0, 0), size=field_size) # Resize ground geom size. self._ground_geom.size = list( field_size) + [max(self._size) * _GROUND_GEOM_GRID_RATIO] # Resize and reposition field box geoms. if self._field_box: for i, (pos, size) in enumerate( _fieldbox_pos_size((self._field.upper - self._field.lower) / 2.0, goal_size)): self._field_box[i].pos = pos self._field_box[i].size = size # Reposition corner lights. _reposition_corner_lights( self._corner_lights, size=(self._size[0] - 2 * goal_size[0], self._size[1] - 2 * goal_size[0])) # Resize, reposition and recolor hoarding geoms. self._update_hoarding() # Mini-football (5v5) dimensions. _GOAL_LENGTH = 3.66 _GOAL_SIDE = 1.22 MINI_FOOTBALL_MIN_AREA_PER_HUMANOID = 100.0 MINI_FOOTBALL_MAX_AREA_PER_HUMANOID = 350.0 MINI_FOOTBALL_GOAL_SIZE = (_GOAL_SIDE / 2, _GOAL_LENGTH / 2, _GOAL_SIDE / 2)
dm_control-main
dm_control/locomotion/soccer/pitch.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.soccer.load.""" from absl import logging from absl.testing import absltest from absl.testing import parameterized from dm_control.locomotion import soccer import numpy as np class LoadTest(parameterized.TestCase): @parameterized.named_parameters( ("2vs2_nocontacts", 2, True), ("2vs2_contacts", 2, False), ("1vs1_nocontacts", 1, True), ("1vs1_contacts", 1, False)) def test_load_env(self, team_size, disable_walker_contacts): env = soccer.load(team_size=team_size, time_limit=2., disable_walker_contacts=disable_walker_contacts) action_specs = env.action_spec() random_state = np.random.RandomState(0) time_step = env.reset() while not time_step.last(): actions = [] for action_spec in action_specs: action = random_state.uniform( action_spec.minimum, action_spec.maximum, size=action_spec.shape) actions.append(action) time_step = env.step(actions) for i in range(len(action_specs)): logging.info( "Player %d: reward = %s, discount = %s, observations = %s.", i, time_step.reward[i], time_step.discount, time_step.observation[i]) def assertSameObservation(self, expected_observation, actual_observation): self.assertLen(actual_observation, len(expected_observation)) for player_id in range(len(expected_observation)): expected_player_observations = expected_observation[player_id] actual_player_observations = actual_observation[player_id] expected_keys = expected_player_observations.keys() actual_keys = actual_player_observations.keys() msg = ("Observation keys differ for player {}.\nExpected: {}.\nActual: {}" .format(player_id, expected_keys, actual_keys)) self.assertEqual(expected_keys, actual_keys, msg) for key in expected_player_observations: expected_array = expected_player_observations[key] actual_array = actual_player_observations[key] msg = ("Observation {!r} differs for player {}.\nExpected:\n{}\n" "Actual:\n{}" .format(key, player_id, expected_array, actual_array)) np.testing.assert_array_equal(expected_array, actual_array, err_msg=msg) @parameterized.parameters(True, False) def test_same_first_observation_if_same_seed(self, disable_walker_contacts): seed = 42 timestep_1 = soccer.load( team_size=2, random_state=seed, disable_walker_contacts=disable_walker_contacts).reset() timestep_2 = soccer.load( team_size=2, random_state=seed, disable_walker_contacts=disable_walker_contacts).reset() self.assertSameObservation(timestep_1.observation, timestep_2.observation) @parameterized.parameters(True, False) def test_different_first_observation_if_different_seed( self, disable_walker_contacts): timestep_1 = soccer.load( team_size=2, random_state=1, disable_walker_contacts=disable_walker_contacts).reset() timestep_2 = soccer.load( team_size=2, random_state=2, disable_walker_contacts=disable_walker_contacts).reset() try: self.assertSameObservation(timestep_1.observation, timestep_2.observation) except AssertionError: pass else: self.fail("Observations are unexpectedly identical.") if __name__ == "__main__": absltest.main()
dm_control-main
dm_control/locomotion/soccer/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. # ============================================================================ """Soccer observables modules.""" import abc from dm_control.composer.observation import observable as base_observable from dm_control.locomotion.soccer import team as team_lib import numpy as np class ObservablesAdder(metaclass=abc.ABCMeta): """A callable that adds a set of per-player observables for a task.""" @abc.abstractmethod def __call__(self, task, player): """Adds observables to a player for the given task. Args: task: A `soccer.Task` instance. player: A `Walker` instance to which observables will be added. """ class MultiObservablesAdder(ObservablesAdder): """Applies multiple `ObservablesAdder`s to a soccer task and player.""" def __init__(self, observables): """Initializes a `MultiObservablesAdder` instance. Args: observables: A list of `ObservablesAdder` instances. """ self._observables = observables def __call__(self, task, player): """Adds observables to a player for the given task. Args: task: A `soccer.Task` instance. player: A `Walker` instance to which observables will be added. """ for observable in self._observables: observable(task, player) class CoreObservablesAdder(ObservablesAdder): """Core set of per player observables.""" def __call__(self, task, player): """Adds observables to a player for the given task. Args: task: A `soccer.Task` instance. player: A `Walker` instance to which observables will be added. """ # Enable proprioceptive observables. self._add_player_proprio_observables(player) # Add egocentric observations of soccer ball. self._add_player_observables_on_ball(player, task.ball) # Add egocentric observations of others. teammate_id = 0 opponent_id = 0 for other in task.players: if other is player: continue # Infer team prefix for `other` conditioned on `player.team`. if player.team != other.team: prefix = 'opponent_{}'.format(opponent_id) opponent_id += 1 else: prefix = 'teammate_{}'.format(teammate_id) teammate_id += 1 self._add_player_observables_on_other(player, other, prefix) self._add_player_arena_observables(player, task.arena) # Add per player game statistics. self._add_player_stats_observables(task, player) def _add_player_observables_on_other(self, player, other, prefix): """Add observables of another player in this player's egocentric frame. Args: player: A `Walker` instance, the player we are adding observables to. other: A `Walker` instance corresponding to a different player. prefix: A string specifying a prefix to apply to the names of observables belonging to `player`. """ if player is other: raise ValueError('Cannot add egocentric observables of player on itself.') sensors = [] for effector in other.walker.end_effectors: name = effector.name + '_' + prefix + '_end_effector' sensors.append(player.walker.mjcf_model.sensor.add( 'framepos', name=name, objtype=effector.tag, objname=effector, reftype='body', refname=player.walker.root_body)) def _egocentric_end_effectors_xpos(physics): return np.reshape(physics.bind(sensors).sensordata, -1) # Adds end effectors of the other agents in the player's egocentric frame. name = '{}_ego_end_effectors_pos'.format(prefix) player.walker.obs_on_other[name] = sensors player.walker.observables.add_observable( name, base_observable.Generic(_egocentric_end_effectors_xpos)) ego_linvel_name = '{}_ego_linear_velocity'.format(prefix) ego_linvel_sensor = player.walker.mjcf_model.sensor.add( 'framelinvel', name=ego_linvel_name, objtype='body', objname=other.walker.root_body, reftype='body', refname=player.walker.root_body) player.walker.obs_on_other[ego_linvel_name] = [ego_linvel_sensor] player.walker.observables.add_observable( ego_linvel_name, base_observable.MJCFFeature('sensordata', ego_linvel_sensor)) ego_pos_name = '{}_ego_position'.format(prefix) ego_pos_sensor = player.walker.mjcf_model.sensor.add( 'framepos', name=ego_pos_name, objtype='body', objname=other.walker.root_body, reftype='body', refname=player.walker.root_body) player.walker.obs_on_other[ego_pos_name] = [ego_pos_sensor] player.walker.observables.add_observable( ego_pos_name, base_observable.MJCFFeature('sensordata', ego_pos_sensor)) sensors_rot = [] obsname = '{}_ego_orientation'.format(prefix) for direction in ['x', 'y', 'z']: sensorname = obsname + '_' + direction sensors_rot.append(player.walker.mjcf_model.sensor.add( 'frame'+direction+'axis', name=sensorname, objtype='body', objname=other.walker.root_body, reftype='body', refname=player.walker.root_body)) def _egocentric_orientation(physics): return np.reshape(physics.bind(sensors_rot).sensordata, -1) player.walker.obs_on_other[obsname] = sensors_rot player.walker.observables.add_observable( obsname, base_observable.Generic(_egocentric_orientation)) # Adds end effectors of the other agents in the other's egocentric frame. # A is seeing B's hand extended to B's right. player.walker.observables.add_observable( '{}_end_effectors_pos'.format(prefix), other.walker.observables.end_effectors_pos) def _add_player_observables_on_ball(self, player, ball): """Add observables of the soccer ball in this player's egocentric frame. Args: player: A `Walker` instance, the player we are adding observations for. ball: A `SoccerBall` instance. """ # Add egocentric ball observations. player.walker.ball_ego_angvel_sensor = player.walker.mjcf_model.sensor.add( 'frameangvel', name='ball_ego_angvel', objtype='body', objname=ball.root_body, reftype='body', refname=player.walker.root_body) player.walker.observables.add_observable( 'ball_ego_angular_velocity', base_observable.MJCFFeature('sensordata', player.walker.ball_ego_angvel_sensor)) player.walker.ball_ego_pos_sensor = player.walker.mjcf_model.sensor.add( 'framepos', name='ball_ego_pos', objtype='body', objname=ball.root_body, reftype='body', refname=player.walker.root_body) player.walker.observables.add_observable( 'ball_ego_position', base_observable.MJCFFeature('sensordata', player.walker.ball_ego_pos_sensor)) player.walker.ball_ego_linvel_sensor = player.walker.mjcf_model.sensor.add( 'framelinvel', name='ball_ego_linvel', objtype='body', objname=ball.root_body, reftype='body', refname=player.walker.root_body) player.walker.observables.add_observable( 'ball_ego_linear_velocity', base_observable.MJCFFeature('sensordata', player.walker.ball_ego_linvel_sensor)) def _add_player_proprio_observables(self, player): """Add proprioceptive observables to the given player. Args: player: A `Walker` instance, the player we are adding observations for. """ for observable in (player.walker.observables.proprioception + player.walker.observables.kinematic_sensors): observable.enabled = True # Also enable previous action observable as part of proprioception. player.walker.observables.prev_action.enabled = True def _add_player_arena_observables(self, player, arena): """Add observables of the arena. Args: player: A `Walker` instance to which observables will be added. arena: A `Pitch` instance. """ # Enable egocentric view of position detectors (goal, field). # Corners named according to walker *facing towards opponent goal*. clockwise_names = [ 'team_goal_back_right', 'team_goal_mid', 'team_goal_front_left', 'field_front_left', 'opponent_goal_back_left', 'opponent_goal_mid', 'opponent_goal_front_right', 'field_back_right', ] clockwise_features = [ lambda _: arena.home_goal.lower[:2], lambda _: arena.home_goal.mid, lambda _: arena.home_goal.upper[:2], lambda _: arena.field.upper, lambda _: arena.away_goal.upper[:2], lambda _: arena.away_goal.mid, lambda _: arena.away_goal.lower[:2], lambda _: arena.field.lower, ] xpos_xyz_callable = lambda p: p.bind(player.walker.root_body).xpos xpos_xy_callable = lambda p: p.bind(player.walker.root_body).xpos[:2] # A list of egocentric reference origin for each one of clockwise_features. clockwise_origins = [ xpos_xy_callable, xpos_xyz_callable, xpos_xy_callable, xpos_xy_callable, xpos_xy_callable, xpos_xyz_callable, xpos_xy_callable, xpos_xy_callable, ] if player.team != team_lib.Team.HOME: half = len(clockwise_features) // 2 clockwise_features = clockwise_features[half:] + clockwise_features[:half] clockwise_origins = clockwise_origins[half:] + clockwise_origins[:half] for name, feature, origin in zip(clockwise_names, clockwise_features, clockwise_origins): player.walker.observables.add_egocentric_vector( name, base_observable.Generic(feature), origin_callable=origin) def _add_player_stats_observables(self, task, player): """Add observables corresponding to game statistics. Args: task: A `soccer.Task` instance. player: A `Walker` instance to which observables will be added. """ def _stats_vel_to_ball(physics): dir_ = ( physics.bind(task.ball.geom).xpos - physics.bind(player.walker.root_body).xpos) vel_to_ball = np.dot(dir_[:2] / (np.linalg.norm(dir_[:2]) + 1e-7), physics.bind(player.walker.root_body).cvel[3:5]) return np.sum(vel_to_ball) player.walker.observables.add_observable( 'stats_vel_to_ball', base_observable.Generic(_stats_vel_to_ball)) def _stats_closest_vel_to_ball(physics): """Velocity to the ball if this walker is the team's closest.""" closest = None min_team_dist_to_ball = np.inf for player_ in task.players: if player_.team == player.team: dist_to_ball = np.linalg.norm( physics.bind(task.ball.geom).xpos - physics.bind(player_.walker.root_body).xpos) if dist_to_ball < min_team_dist_to_ball: min_team_dist_to_ball = dist_to_ball closest = player_ if closest is player: return _stats_vel_to_ball(physics) return 0. player.walker.observables.add_observable( 'stats_closest_vel_to_ball', base_observable.Generic(_stats_closest_vel_to_ball)) def _stats_veloc_forward(physics): """Player's forward velocity.""" return player.walker.observables.veloc_forward(physics) player.walker.observables.add_observable( 'stats_veloc_forward', base_observable.Generic(_stats_veloc_forward)) def _stats_vel_ball_to_goal(physics): """Ball velocity towards opponents' goal.""" if player.team == team_lib.Team.HOME: goal = task.arena.away_goal else: goal = task.arena.home_goal goal_center = (goal.upper + goal.lower) / 2. direction = goal_center - physics.bind(task.ball.geom).xpos ball_vel_observable = task.ball.observables.linear_velocity ball_vel = ball_vel_observable.observation_callable(physics)() norm_dir = np.linalg.norm(direction) normalized_dir = direction / norm_dir if norm_dir else direction return np.sum(np.dot(normalized_dir, ball_vel)) player.walker.observables.add_observable( 'stats_vel_ball_to_goal', base_observable.Generic(_stats_vel_ball_to_goal)) def _stats_avg_teammate_dist(physics): """Compute average distance from `walker` to its teammates.""" teammate_dists = [] for other in task.players: if player is other: continue if other.team != player.team: continue dist = np.linalg.norm( physics.bind(player.walker.root_body).xpos - physics.bind(other.walker.root_body).xpos) teammate_dists.append(dist) return np.mean(teammate_dists) if teammate_dists else 0. player.walker.observables.add_observable( 'stats_home_avg_teammate_dist', base_observable.Generic(_stats_avg_teammate_dist)) def _stats_teammate_spread_out(physics): """Compute average distance from `walker` to its teammates.""" return _stats_avg_teammate_dist(physics) > 5. player.walker.observables.add_observable( 'stats_teammate_spread_out', base_observable.Generic(_stats_teammate_spread_out)) def _stats_home_score(unused_physics): if (task.arena.detected_goal() and task.arena.detected_goal() == player.team): return 1. return 0. player.walker.observables.add_observable( 'stats_home_score', base_observable.Generic(_stats_home_score)) has_opponent = any([p.team != player.team for p in task.players]) def _stats_away_score(unused_physics): if (has_opponent and task.arena.detected_goal() and task.arena.detected_goal() != player.team): return 1. return 0. player.walker.observables.add_observable( 'stats_away_score', base_observable.Generic(_stats_away_score)) # TODO(b/124848293): add unit-test interception observables. class InterceptionObservablesAdder(ObservablesAdder): """Adds obervables representing interception events. These observables represent events where this player received the ball from another player, or when an opponent intercepted the ball from this player's team. For each type of event there are three different thresholds applied to the distance travelled by the ball since it last made contact with a player (5, 10, or 15 meters). For example, on a given timestep `stats_i_received_ball_10m` will be 1 if * This player just made contact with the ball * The last player to have made contact with the ball was a different player * The ball travelled for at least 10 m since it last hit a player and 0 otherwise. Conversely, `stats_opponent_intercepted_ball_10m` will be 1 if: * An opponent just made contact with the ball * The last player to have made contact with the ball was on this player's team * The ball travelled for at least 10 m since it last hit a player """ def __call__(self, task, player): """Adds observables to a player for the given task. Args: task: A `soccer.Task` instance. player: A `Walker` instance to which observables will be added. """ def _stats_i_received_ball(unused_physics): if (task.ball.hit and task.ball.repossessed and task.ball.last_hit is player): return 1. return 0. player.walker.observables.add_observable( 'stats_i_received_ball', base_observable.Generic(_stats_i_received_ball)) def _stats_opponent_intercepted_ball(unused_physics): """Indicator on if an opponent intercepted the ball.""" if (task.ball.hit and task.ball.intercepted and task.ball.last_hit.team != player.team): return 1. return 0. player.walker.observables.add_observable( 'stats_opponent_intercepted_ball', base_observable.Generic(_stats_opponent_intercepted_ball)) for dist in [5, 10, 15]: def _stats_i_received_ball_dist(physics, dist=dist): if (_stats_i_received_ball(physics) and task.ball.dist_between_last_hits is not None and task.ball.dist_between_last_hits > dist): return 1. return 0. player.walker.observables.add_observable( 'stats_i_received_ball_%dm' % dist, base_observable.Generic(_stats_i_received_ball_dist)) def _stats_opponent_intercepted_ball_dist(physics, dist=dist): if (_stats_opponent_intercepted_ball(physics) and task.ball.dist_between_last_hits is not None and task.ball.dist_between_last_hits > dist): return 1. return 0. player.walker.observables.add_observable( 'stats_opponent_intercepted_ball_%dm' % dist, base_observable.Generic(_stats_opponent_intercepted_ball_dist))
dm_control-main
dm_control/locomotion/soccer/observables.py