python_code
stringlengths
0
780k
repo_name
stringlengths
7
38
file_path
stringlengths
5
103
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests of the decorators module.""" from absl.testing import absltest from dm_control.mujoco.testing import decorators import mock class RunThreadedTest(absltest.TestCase): @mock.patch(decorators.__name__ + ".threading") def test_number_of_threads(self, mock_threading): num_threads = 5 mock_threads = [mock.MagicMock() for _ in range(num_threads)] for thread in mock_threads: thread.start = mock.MagicMock() thread.join = mock.MagicMock() mock_threading.Thread = mock.MagicMock(side_effect=mock_threads) test_decorator = decorators.run_threaded(num_threads=num_threads) tested_method = mock.MagicMock() tested_method.__name__ = "foo" test_runner = test_decorator(tested_method) test_runner(self) for thread in mock_threads: thread.start.assert_called_once() thread.join.assert_called_once() def test_number_of_iterations(self): calls_per_thread = 5 tested_method = mock.MagicMock() tested_method.__name__ = "foo" test_decorator = decorators.run_threaded( num_threads=1, calls_per_thread=calls_per_thread) test_runner = test_decorator(tested_method) test_runner(self) self.assertEqual(calls_per_thread, tested_method.call_count) @mock.patch(decorators.__name__ + ".threading") def test_using_the_main_thread(self, mock_threading): mock_thread = mock.MagicMock() mock_thread.start = mock.MagicMock() mock_thread.join = mock.MagicMock() mock_threading.current_thread = mock.MagicMock(return_value=mock_thread) test_decorator = decorators.run_threaded(num_threads=None, calls_per_thread=1) tested_method = mock.MagicMock() tested_method.__name__ = "foo" test_runner = test_decorator(tested_method) test_runner(self) tested_method.assert_called_once() mock_thread.start.assert_not_called() mock_thread.join.assert_not_called() if __name__ == "__main__": absltest.main()
dm_control-main
dm_control/mujoco/testing/decorators_test.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================
dm_control-main
dm_control/mujoco/testing/__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. # ============================================================================ """Script for generating pre-rendered frames used in integration tests.""" from absl import app from dm_control.mujoco.testing import image_utils def main(argv): del argv # Unused. for sequence in image_utils.SEQUENCES.values(): sequence.save() if __name__ == '__main__': app.run(main)
dm_control-main
dm_control/mujoco/testing/generate_frames.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. # ============================================================================ """Decorators used in MuJoCo tests.""" import functools import threading def run_threaded(num_threads=4, calls_per_thread=10): """A decorator that executes the same test repeatedly in multiple threads. Note: `setUp` and `tearDown` methods will only be called once from the main thread, so all thread-local setup must be done within the test method. Args: num_threads: Number of concurrent threads to spawn. If None then the wrapped method will be executed in the main thread instead. calls_per_thread: Number of times each thread should call the test method. Returns: Decorated test method. """ def decorator(test_method): """Decorator around the test method.""" @functools.wraps(test_method) # Needed for `named_parameters` to work. def decorated_method(self, *args, **kwargs): """Actual method this factory will return.""" exceptions = [] def worker(): try: for _ in range(calls_per_thread): test_method(self, *args, **kwargs) except Exception as exc: # pylint: disable=broad-except # Appending to Python list is thread-safe: # http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm exceptions.append(exc) if num_threads is not None: threads = [threading.Thread(target=worker, name='thread_{}'.format(i)) for i in range(num_threads)] for thread in threads: thread.start() for thread in threads: thread.join() else: worker() for exc in exceptions: raise exc return decorated_method return decorator
dm_control-main
dm_control/mujoco/testing/decorators.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. # ============================================================================ """Assets used for testing the MuJoCo bindings.""" import os from dm_control.utils import io as resources _ASSETS_DIR = os.path.dirname(__file__) def get_contents(filename): """Returns the contents of an asset as a string.""" return resources.GetResource(os.path.join(_ASSETS_DIR, filename), mode='rb') def get_path(filename): """Returns the path to an asset.""" return resources.GetResourceFilename(os.path.join(_ASSETS_DIR, filename))
dm_control-main
dm_control/mujoco/testing/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 dm_control.locomotion.tasks.transformations.""" import itertools from absl.testing import absltest from absl.testing import parameterized from dm_control.mujoco.wrapper import mjbindings from dm_control.utils import transformations import numpy as np mjlib = mjbindings.mjlib _NUM_RANDOM_SAMPLES = 1000 class TransformationsTest(parameterized.TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._random_state = np.random.RandomState() @parameterized.parameters( { 'quat': [-0.41473841, 0.59483601, -0.45089078, 0.52044181], 'truemat': np.array([[0.05167565, -0.10471773, 0.99315851], [-0.96810656, -0.24937912, 0.02407785], [0.24515162, -0.96272751, -0.11426475]]) }, { 'quat': [0.08769298, 0.69897558, 0.02516888, 0.7093022], 'truemat': np.array([[-0.00748615, -0.08921678, 0.9959841], [0.15958651, -0.98335294, -0.08688582], [0.98715556, 0.15829519, 0.02159933]]) }, { 'quat': [0.58847272, 0.44682507, 0.51443343, -0.43520737], 'truemat': np.array([[0.09190557, 0.97193884, 0.21653695], [-0.05249182, 0.22188379, -0.97365918], [-0.99438321, 0.07811829, 0.07141119]]) }, ) def test_quat_to_mat(self, quat, truemat): """Tests hard-coded quat-mat pairs generated from mujoco if mj not avail.""" mat = transformations.quat_to_mat(quat) np.testing.assert_allclose(mat[0:3, 0:3], truemat, atol=1e-7) def test_quat_to_mat_mujoco_special(self): # Test for special values that often cause numerical issues. rng = [-np.pi, np.pi / 2, 0, np.pi / 2, np.pi] for euler_tup in itertools.product(rng, rng, rng): euler_vec = np.array(euler_tup, dtype=float) mat = transformations.euler_to_rmat(euler_vec, ordering='XYZ') quat = transformations.mat_to_quat(mat) tr_mat = transformations.quat_to_mat(quat) mj_mat = np.zeros(9) mjlib.mju_quat2Mat(mj_mat, quat) mj_mat = mj_mat.reshape(3, 3) np.testing.assert_allclose(tr_mat[0:3, 0:3], mj_mat, atol=1e-10) np.testing.assert_allclose(tr_mat[0:3, 0:3], mat, atol=1e-10) def test_quat_to_mat_mujoco_random(self): for _ in range(_NUM_RANDOM_SAMPLES): quat = self._random_quaternion() tr_mat = transformations.quat_to_mat(quat) mj_mat = np.zeros(9) mjlib.mju_quat2Mat(mj_mat, quat) mj_mat = mj_mat.reshape(3, 3) np.testing.assert_allclose(tr_mat[0:3, 0:3], mj_mat) def test_mat_to_quat_mujoco(self): subsamps = 10 rng = np.linspace(-np.pi, np.pi, subsamps) for euler_tup in itertools.product(rng, rng, rng): euler_vec = np.array(euler_tup, dtype=float) mat = transformations.euler_to_rmat(euler_vec, ordering='XYZ') mj_quat = np.empty(4, dtype=euler_vec.dtype) mjlib.mju_mat2Quat(mj_quat, mat.flatten()) tr_quat = transformations.mat_to_quat(mat) self.assertTrue( np.allclose(mj_quat, tr_quat) or np.allclose(mj_quat, -tr_quat)) @parameterized.parameters( {'angles': (0, 0, 0)}, {'angles': (-0.1, 0.4, -1.3)} ) def test_euler_to_rmat_special(self, angles): # Test for special values that often cause numerical issues. r1, r2, r3 = angles for ordering in transformations._eulermap.keys(): r = transformations.euler_to_rmat(np.array([r1, r2, r3]), ordering) euler_angles = transformations.rmat_to_euler(r, ordering) np.testing.assert_allclose(euler_angles, [r1, r2, r3]) def test_quat_mul_vs_mat_mul_random(self): for _ in range(_NUM_RANDOM_SAMPLES): quat1 = self._random_quaternion() quat2 = self._random_quaternion() rmat1 = transformations.quat_to_mat(quat1)[0:3, 0:3] rmat2 = transformations.quat_to_mat(quat2)[0:3, 0:3] quat_prod = transformations.quat_mul(quat1, quat2) rmat_prod_q = transformations.quat_to_mat(quat_prod)[0:3, 0:3] rmat_prod = rmat1.dot(rmat2) np.testing.assert_allclose(rmat_prod, rmat_prod_q) def test_quat_mul_vs_mat_mul_random_batched(self): quat1 = np.stack( [self._random_quaternion() for _ in range(_NUM_RANDOM_SAMPLES)], axis=0) quat2 = np.stack( [self._random_quaternion() for _ in range(_NUM_RANDOM_SAMPLES)], axis=0) quat_prod = transformations.quat_mul(quat1, quat2) for k in range(_NUM_RANDOM_SAMPLES): rmat1 = transformations.quat_to_mat(quat1[k])[0:3, 0:3] rmat2 = transformations.quat_to_mat(quat2[k])[0:3, 0:3] rmat_prod_q = transformations.quat_to_mat(quat_prod[k])[0:3, 0:3] rmat_prod = rmat1.dot(rmat2) np.testing.assert_allclose(rmat_prod, rmat_prod_q) def test_quat_mul_mujoco_special(self): # Test for special values that often cause numerical issues. rng = [-np.pi, np.pi / 2, 0, np.pi / 2, np.pi] quat1 = np.array([1, 0, 0, 0], dtype=np.float64) for euler_tup in itertools.product(rng, rng, rng): euler_vec = np.array(euler_tup, dtype=np.float64) quat2 = transformations.euler_to_quat(euler_vec, ordering='XYZ') quat_prod_tr = transformations.quat_mul(quat1, quat2) quat_prod_mj = np.zeros(4) mjlib.mju_mulQuat(quat_prod_mj, quat1, quat2) np.testing.assert_allclose(quat_prod_tr, quat_prod_mj, atol=1e-14) quat1 = quat2 def test_quat_mul_mujoco_special_batched(self): # Test for special values that often cause numerical issues. rng = [-np.pi, np.pi / 2, 0, np.pi / 2, np.pi] q1, q2, qmj = [], [], [] quat1 = np.array([1, 0, 0, 0], dtype=np.float64) for euler_tup in itertools.product(rng, rng, rng): euler_vec = np.array(euler_tup, dtype=np.float64) quat2 = transformations.euler_to_quat(euler_vec, ordering='XYZ') quat_prod_mj = np.zeros(4) mjlib.mju_mulQuat(quat_prod_mj, quat1, quat2) q1.append(quat1) q2.append(quat2) qmj.append(quat_prod_mj) quat1 = quat2 q1 = np.stack(q1, axis=0) q2 = np.stack(q2, axis=0) qmj = np.stack(qmj, axis=0) qtr = transformations.quat_mul(q1, q2) np.testing.assert_allclose(qtr, qmj, atol=1e-14) def test_quat_mul_mujoco_random(self): for _ in range(_NUM_RANDOM_SAMPLES): quat1 = self._random_quaternion() quat2 = self._random_quaternion() quat_prod_tr = transformations.quat_mul(quat1, quat2) quat_prod_mj = np.zeros(4) mjlib.mju_mulQuat(quat_prod_mj, quat1, quat2) np.testing.assert_allclose(quat_prod_tr, quat_prod_mj) def test_quat_mul_mujoco_random_batched(self): quat1 = np.stack( [self._random_quaternion() for _ in range(_NUM_RANDOM_SAMPLES)], axis=0) quat2 = np.stack( [self._random_quaternion() for _ in range(_NUM_RANDOM_SAMPLES)], axis=0) quat_prod_tr = transformations.quat_mul(quat1, quat2) for k in range(quat1.shape[0]): quat_prod_mj = np.zeros(4) mjlib.mju_mulQuat(quat_prod_mj, quat1[k], quat2[k]) np.testing.assert_allclose(quat_prod_tr[k], quat_prod_mj) def test_quat_rotate_mujoco_special(self): # Test for special values that often cause numerical issues. rng = [-np.pi, np.pi / 2, 0, np.pi / 2, np.pi] vec = np.array([1, 0, 0], dtype=np.float64) for euler_tup in itertools.product(rng, rng, rng): euler_vec = np.array(euler_tup, dtype=np.float64) quat = transformations.euler_to_quat(euler_vec, ordering='XYZ') rotated_vec_tr = transformations.quat_rotate(quat, vec) rotated_vec_mj = np.zeros(3) mjlib.mju_rotVecQuat(rotated_vec_mj, vec, quat) np.testing.assert_allclose(rotated_vec_tr, rotated_vec_mj, atol=1e-14) def test_quat_rotate_mujoco_random(self): for _ in range(_NUM_RANDOM_SAMPLES): quat = self._random_quaternion() vec = self._random_state.rand(3) rotated_vec_tr = transformations.quat_rotate(quat, vec) rotated_vec_mj = np.zeros(3) mjlib.mju_rotVecQuat(rotated_vec_mj, vec, quat) np.testing.assert_allclose(rotated_vec_tr, rotated_vec_mj) def test_quat_diff_random(self): for _ in range(_NUM_RANDOM_SAMPLES): source = self._random_quaternion() target = self._random_quaternion() np.testing.assert_allclose( transformations.quat_diff(source, target), transformations.quat_mul(transformations.quat_conj(source), target)) def test_quat_diff_random_batched(self): source = np.stack( [self._random_quaternion() for _ in range(_NUM_RANDOM_SAMPLES)], axis=0) target = np.stack( [self._random_quaternion() for _ in range(_NUM_RANDOM_SAMPLES)], axis=0) np.testing.assert_allclose( transformations.quat_diff(source, target), transformations.quat_mul(transformations.quat_conj(source), target)) def test_quat_dist_random(self): for _ in range(_NUM_RANDOM_SAMPLES): # test with normalized quaternions for stability of test source = self._random_quaternion() target = self._random_quaternion() source /= np.linalg.norm(source) target /= np.linalg.norm(target) self.assertGreater(transformations.quat_dist(source, target), 0) np.testing.assert_allclose( transformations.quat_dist(source, source), 0, atol=1e-9) def test_quat_dist_random_batched(self): # Test batched quat dist source_quats = np.stack( [self._random_quaternion() for _ in range(_NUM_RANDOM_SAMPLES)], axis=0) target_quats = np.stack( [self._random_quaternion() for _ in range(_NUM_RANDOM_SAMPLES)], axis=0) source_quats /= np.linalg.norm(source_quats, axis=-1, keepdims=True) target_quats /= np.linalg.norm(target_quats, axis=-1, keepdims=True) np.testing.assert_allclose( transformations.quat_dist(source_quats, source_quats), 0, atol=1e-9) np.testing.assert_equal( transformations.quat_dist(source_quats, target_quats) > 0, 1) def _random_quaternion(self): rand = self._random_state.rand(3) r1 = np.sqrt(1.0 - rand[0]) r2 = np.sqrt(rand[0]) pi2 = np.pi * 2.0 t1 = pi2 * rand[1] t2 = pi2 * rand[2] return np.array( (np.cos(t2) * r2, np.sin(t1) * r1, np.cos(t1) * r1, np.sin(t2) * r2), dtype=np.float64) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/utils/transformations_test.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for dm_control.utils.containers.""" from absl.testing import absltest from absl.testing import parameterized from dm_control.utils import containers class TaggedTaskTest(parameterized.TestCase): def test_registration(self): tasks = containers.TaggedTasks() @tasks.add() def test_factory1(): # pylint: disable=unused-variable return 'executed 1' @tasks.add('basic', 'stable') def test_factory2(): # pylint: disable=unused-variable return 'executed 2' @tasks.add('expert', 'stable') def test_factory3(): # pylint: disable=unused-variable return 'executed 3' @tasks.add('expert', 'unstable') def test_factory4(): # pylint: disable=unused-variable return 'executed 4' self.assertLen(tasks, 4) self.assertEqual(set(['basic', 'expert', 'stable', 'unstable']), set(tasks.tags())) self.assertLen(tasks.tagged('basic'), 1) self.assertLen(tasks.tagged('expert'), 2) self.assertLen(tasks.tagged('stable'), 2) self.assertLen(tasks.tagged('unstable'), 1) self.assertEqual('executed 2', tasks['test_factory2']()) self.assertEqual('executed 3', tasks.tagged('expert')['test_factory3']()) self.assertNotIn('test_factory4', tasks.tagged('stable')) def test_iteration_order(self): tasks = containers.TaggedTasks() @tasks.add() def first(): # pylint: disable=unused-variable pass @tasks.add() def second(): # pylint: disable=unused-variable pass @tasks.add() def third(): # pylint: disable=unused-variable pass @tasks.add() def fourth(): # pylint: disable=unused-variable pass expected_order = ['first', 'second', 'third', 'fourth'] actual_order = list(tasks) self.assertEqual(expected_order, actual_order) def test_override_behavior(self): tasks = containers.TaggedTasks(allow_overriding_keys=False) @tasks.add() def some_func(): pass expected_message = containers._NAME_ALREADY_EXISTS.format(name='some_func') with self.assertRaisesWithLiteralMatch(ValueError, expected_message): tasks.add()(some_func) tasks.allow_overriding_keys = True tasks.add()(some_func) # Override should now succeed. @parameterized.parameters( {'query': ['a'], 'expected_keys': frozenset(['f1', 'f2', 'f3'])}, {'query': ['b', 'c'], 'expected_keys': frozenset(['f2'])}, {'query': ['c'], 'expected_keys': frozenset(['f2', 'f3'])}, {'query': ['b', 'd'], 'expected_keys': frozenset()}, {'query': ['e'], 'expected_keys': frozenset()}, {'query': [], 'expected_keys': frozenset()}) def test_query_tag_intersection(self, query, expected_keys): tasks = containers.TaggedTasks() # pylint: disable=unused-variable @tasks.add('a', 'b') def f1(): pass @tasks.add('a', 'b', 'c') def f2(): pass @tasks.add('a', 'c', 'd') def f3(): pass # pylint: enable=unused-variable result = tasks.tagged(*query) self.assertSetEqual(frozenset(result.keys()), expected_keys) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/utils/containers_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. # ============================================================================ """Rigid-body transformations including velocities and static forces.""" from absl import logging import numpy as np # Constants used to determine when a rotation is close to a pole. _POLE_LIMIT = (1.0 - 1e-6) _TOL = 1e-10 def _clip_within_precision(number, low, high, precision=_TOL): """Clips input to provided range, checking precision. Args: number: (float) number to be clipped. low: (float) lower bound. high: (float) upper bound. precision: (float) tolerance. Returns: Input clipped to given range. Raises: ValueError: If number is outside given range by more than given precision. """ if (number < low - precision).any() or (number > high + precision).any(): raise ValueError( 'Input {:.12f} not inside range [{:.12f}, {:.12f}] with precision {}'. format(number, low, high, precision)) return np.clip(number, low, high) def _batch_mm(m1, m2): """Batch matrix multiply. Args: m1: input lhs matrix with shape (batch, n, m). m2: input rhs matrix with shape (batch, m, o). Returns: product matrix with shape (batch, n, o). """ return np.einsum('bij,bjk->bik', m1, m2) def _rmat_to_euler_xyz(rmat): """Converts a 3x3 rotation matrix to XYZ euler angles.""" # | r00 r01 r02 | | cy*cz -cy*sz sy | # | r10 r11 r12 | = | cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx | # | r20 r21 r22 | | -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy | if rmat[0, 2] > _POLE_LIMIT: logging.log_every_n_seconds(logging.WARNING, 'Angle at North Pole', 60) z = np.arctan2(rmat[1, 0], rmat[1, 1]) y = np.pi/2 x = 0.0 return np.array([x, y, z]) if rmat[0, 2] < -_POLE_LIMIT: logging.log_every_n_seconds(logging.WARNING, 'Angle at South Pole', 60) z = np.arctan2(rmat[1, 0], rmat[1, 1]) y = -np.pi/2 x = 0.0 return np.array([x, y, z]) z = -np.arctan2(rmat[0, 1], rmat[0, 0]) y = np.arcsin(rmat[0, 2]) x = -np.arctan2(rmat[1, 2], rmat[2, 2]) # order of return is the order of input return np.array([x, y, z]) def _rmat_to_euler_xyx(rmat): """Converts a 3x3 rotation matrix to XYX euler angles.""" # | r00 r01 r02 | | cy sy*sx1 sy*cx1 | # | r10 r11 r12 | = | sy*sx0 cx0*cx1-cy*sx0*sx1 -cy*cx1*sx0-cx0*sx1 | # | r20 r21 r22 | | -sy*cx0 cx1*sx0+cy*cx0*sx1 cy*cx0*cx1-sx0*sx1 | if rmat[0, 0] < 1.0: if rmat[0, 0] > -1.0: y = np.arccos(_clip_within_precision(rmat[0, 0], -1., 1.)) x0 = np.arctan2(rmat[1, 0], -rmat[2, 0]) x1 = np.arctan2(rmat[0, 1], rmat[0, 2]) return np.array([x0, y, x1]) else: # Not a unique solution: x1_angle - x0_angle = atan2(-r12,r11) y = np.pi x0 = -np.arctan2(-rmat[1, 2], rmat[1, 1]) x1 = 0.0 return np.array([x0, y, x1]) else: # Not a unique solution: x1_angle + x0_angle = atan2(-r12,r11) y = 0.0 x0 = -np.arctan2(-rmat[1, 2], rmat[1, 1]) x1 = 0.0 return np.array([x0, y, x1]) def _rmat_to_euler_zyx(rmat): """Converts a 3x3 rotation matrix to ZYX euler angles.""" if rmat[2, 0] > _POLE_LIMIT: logging.warning('Angle at North Pole') x = np.arctan2(rmat[0, 1], rmat[0, 2]) y = -np.pi/2 z = 0.0 return np.array([z, y, x]) if rmat[2, 0] < -_POLE_LIMIT: logging.warning('Angle at South Pole') x = np.arctan2(rmat[0, 1], rmat[0, 2]) y = np.pi/2 z = 0.0 return np.array([z, y, x]) x = np.arctan2(rmat[2, 1], rmat[2, 2]) y = -np.arcsin(rmat[2, 0]) z = np.arctan2(rmat[1, 0], rmat[0, 0]) # order of return is the order of input return np.array([z, y, x]) def _rmat_to_euler_xzy(rmat): """Converts a 3x3 rotation matrix to XZY euler angles.""" if rmat[0, 1] > _POLE_LIMIT: logging.warning('Angle at North Pole') y = np.arctan2(rmat[1, 2], rmat[1, 0]) z = -np.pi/2 x = 0.0 return np.array([x, z, y]) if rmat[0, 1] < -_POLE_LIMIT: logging.warning('Angle at South Pole') y = np.arctan2(rmat[1, 2], rmat[1, 0]) z = np.pi/2 x = 0.0 return np.array([x, z, y]) y = np.arctan2(rmat[0, 2], rmat[0, 0]) z = -np.arcsin(rmat[0, 1]) x = np.arctan2(rmat[2, 1], rmat[1, 1]) # order of return is the order of input return np.array([x, z, y]) def _rmat_to_euler_yzx(rmat): """Converts a 3x3 rotation matrix to YZX euler angles.""" if rmat[1, 0] > _POLE_LIMIT: logging.warning('Angle at North Pole') x = -np.arctan2(rmat[0, 2], rmat[0, 1]) z = np.pi/2 y = 0.0 return np.array([y, z, x]) if rmat[1, 0] < -_POLE_LIMIT: logging.warning('Angle at South Pole') x = -np.arctan2(rmat[0, 2], rmat[0, 1]) z = -np.pi/2 y = 0.0 return np.array([y, z, x]) x = -np.arctan2(rmat[1, 2], rmat[1, 1]) z = np.arcsin(rmat[1, 0]) y = -np.arctan2(rmat[2, 0], rmat[0, 0]) # order of return is the order of input return np.array([y, z, x]) def _rmat_to_euler_zxy(rmat): """Converts a 3x3 rotation matrix to ZXY euler angles.""" if rmat[2, 1] > _POLE_LIMIT: logging.warning('Angle at North Pole') y = np.arctan2(rmat[0, 2], rmat[0, 0]) x = np.pi/2 z = 0.0 return np.array([z, x, y]) if rmat[2, 1] < -_POLE_LIMIT: logging.warning('Angle at South Pole') y = np.arctan2(rmat[0, 2], rmat[0, 0]) x = -np.pi/2 z = 0.0 return np.array([z, x, y]) y = -np.arctan2(rmat[2, 0], rmat[2, 2]) x = np.arcsin(rmat[2, 1]) z = -np.arctan2(rmat[0, 1], rmat[1, 1]) # order of return is the order of input return np.array([z, x, y]) def _rmat_to_euler_yxz(rmat): """Converts a 3x3 rotation matrix to YXZ euler angles.""" if rmat[1, 2] > _POLE_LIMIT: logging.warning('Angle at North Pole') z = -np.arctan2(rmat[0, 1], rmat[0, 0]) x = -np.pi/2 y = 0.0 return np.array([y, x, z]) if rmat[1, 2] < -_POLE_LIMIT: logging.warning('Angle at South Pole') z = -np.arctan2(rmat[0, 1], rmat[0, 0]) x = np.pi/2 y = 0.0 return np.array([y, x, z]) z = np.arctan2(rmat[1, 0], rmat[1, 1]) x = -np.arcsin(rmat[1, 2]) y = np.arctan2(rmat[0, 2], rmat[2, 2]) # order of return is the order of input return np.array([y, x, z]) def _axis_rotation(theta, full): """Returns the theta dim, cos and sin, and blank matrix for axis rotation.""" n = 1 if np.isscalar(theta) else len(theta) ct = np.cos(theta) st = np.sin(theta) if full: rmat = np.zeros((n, 4, 4)) rmat[:, 3, 3] = 1. else: rmat = np.zeros((n, 3, 3)) return n, ct, st, rmat # map from full rotation orderings to euler conversion functions _eulermap = { 'XYZ': _rmat_to_euler_xyz, 'XYX': _rmat_to_euler_xyx, 'ZYX': _rmat_to_euler_zyx, 'XZY': _rmat_to_euler_xzy, 'YZX': _rmat_to_euler_yzx, 'ZXY': _rmat_to_euler_zxy, 'YXZ': _rmat_to_euler_yxz } def euler_to_quat(euler_vec, ordering='XYZ'): """Returns the quaternion corresponding to the provided euler angles. Args: euler_vec: The euler angle rotations. ordering: (str) Desired euler angle ordering. Returns: quat: A quaternion [w, i, j, k] """ mat = euler_to_rmat(euler_vec, ordering=ordering) return mat_to_quat(mat) def euler_to_rmat(euler_vec, ordering='ZXZ', full=False): """Returns rotation matrix (or transform) for the given Euler rotations. Euler*** methods compose a Rotation matrix corresponding to the given rotations r1, r2, r3 following the given rotation ordering. Ordering specifies the order of rotation matrices in matrix multiplication order. E.g. for XYZ we return rotX(r1) * rotY(r2) * rotZ(r3). Args: euler_vec: The euler angle rotations. ordering: euler angle ordering string (see _euler_orderings). full: If true, returns a full 4x4 transfom. Returns: The rotation matrix or homogenous transform corresponding to the given Euler rotation. """ # map from partial rotation orderings to rotation functions rotmap = {'X': rotation_x_axis, 'Y': rotation_y_axis, 'Z': rotation_z_axis} rotations = [rotmap[c] for c in ordering] euler_vec = np.atleast_2d(euler_vec) rots = [] for i in range(len(rotations)): rots.append(rotations[i](euler_vec[:, i], full)) if rots[0].ndim == 3: result = _batch_mm(_batch_mm(rots[0], rots[1]), rots[2]) return result.squeeze() else: return (rots[0].dot(rots[1])).dot(rots[2]) def quat_conj(quat): """Return conjugate of quaternion. This function supports inputs with or without leading batch dimensions. Args: quat: A quaternion [w, i, j, k]. Returns: A quaternion [w, -i, -j, -k] representing the inverse of the rotation defined by `quat` (not assuming normalization). """ # Ensure quat is an np.array in case a tuple or a list is passed quat = np.asarray(quat) return np.stack( [quat[..., 0], -quat[..., 1], -quat[..., 2], -quat[..., 3]], axis=-1).astype(np.float64) def quat_inv(quat): """Return inverse of quaternion. This function supports inputs with or without leading batch dimensions. Args: quat: A quaternion [w, i, j, k]. Returns: A quaternion representing the inverse of the original rotation. """ # Ensure quat is an np.array in case a tuple or a list is passed quat = np.asarray(quat) return quat_conj(quat) / np.sum(quat * quat, axis=-1, keepdims=True) def _get_qmat_indices_and_signs(): """Precomputes index and sign arrays for constructing `qmat` in `quat_mul`.""" w, x, y, z = range(4) qmat_idx_and_sign = np.array([ [w, -x, -y, -z], [x, w, -z, y], [y, z, w, -x], [z, -y, x, w], ]) indices = np.abs(qmat_idx_and_sign) signs = 2 * (qmat_idx_and_sign >= 0) - 1 # Prevent array constants from being modified in place. indices.flags.writeable = False signs.flags.writeable = False return indices, signs _qmat_idx, _qmat_sign = _get_qmat_indices_and_signs() def quat_mul(quat1, quat2): """Computes the Hamilton product of two quaternions. Any number of leading batch dimensions is supported. Args: quat1: A quaternion [w, i, j, k]. quat2: A quaternion [w, i, j, k]. Returns: The quaternion product quat1 * quat2. """ # Construct a (..., 4, 4) matrix to multiply with quat2 as shown below. qmat = quat1[..., _qmat_idx] * _qmat_sign # Compute the batched Hamilton product: # |w1 -i1 -j1 -k1| |w2| |w1w2 - i1i2 - j1j2 - k1k2| # |i1 w1 -k1 j1| . |i2| = |w1i2 + i1w2 + j1k2 - k1j2| # |j1 k1 w1 -i1| |j2| |w1j2 - i1k2 + j1w2 + k1i2| # |k1 -j1 i1 w1| |k2| |w1k2 + i1j2 - j1i2 + k1w2| return (qmat @ quat2[..., None])[..., 0] def quat_diff(source, target): """Computes quaternion difference between source and target quaternions. This function supports inputs with or without leading batch dimensions. Args: source: A quaternion [w, i, j, k]. target: A quaternion [w, i, j, k]. Returns: A quaternion representing the rotation from source to target. """ return quat_mul(quat_conj(source), target) def quat_log(quat, tol=_TOL): """Log of a quaternion. This function supports inputs with or without leading batch dimensions. Args: quat: A quaternion [w, i, j, k]. tol: numerical tolerance to prevent nan. Returns: 4D array representing the log of `quat`. This is analogous to `rmat_to_axisangle`. """ # Ensure quat is an np.array in case a tuple or a list is passed quat = np.asarray(quat) q_norm = np.linalg.norm(quat + tol, axis=-1, keepdims=True) a = quat[..., 0:1] v = np.stack([quat[..., 1], quat[..., 2], quat[..., 3]], axis=-1) # Clip to 2*tol because we subtract it here v_new = v / np.linalg.norm(v + tol, axis=-1, keepdims=True) * np.arccos( _clip_within_precision(a - tol, -1., 1., precision=2.*tol)) / q_norm return np.stack( [np.log(q_norm[..., 0]), v_new[..., 0], v_new[..., 1], v_new[..., 2]], axis=-1) def quat_dist(source, target): """Computes distance between source and target quaternions. This function assumes that both input arguments are unit quaternions. This function supports inputs with or without leading batch dimensions. Args: source: A quaternion [w, i, j, k]. target: A quaternion [w, i, j, k]. Returns: Scalar representing the rotational distance from source to target. """ quat_product = quat_mul(source, quat_inv(target)) quat_product /= np.linalg.norm(quat_product, axis=-1, keepdims=True) return np.linalg.norm(quat_log(quat_product), axis=-1, keepdims=True) def quat_rotate(quat, vec): """Rotate a vector by a quaternion. Args: quat: A quaternion [w, i, j, k]. vec: A 3-vector representing a position. Returns: The rotated vector. """ qvec = np.hstack([[0], vec]) return quat_mul(quat_mul(quat, qvec), quat_conj(quat))[1:] def quat_to_axisangle(quat): """Returns the axis-angle corresponding to the provided quaternion. Args: quat: A quaternion [w, i, j, k]. Returns: axisangle: A 3x1 numpy array describing the axis of rotation, with angle encoded by its length. """ angle = 2 * np.arccos(_clip_within_precision(quat[0], -1., 1.)) if angle < _TOL: return np.zeros(3) else: qn = np.sin(angle/2) angle = (angle + np.pi) % (2 * np.pi) - np.pi axis = quat[1:4] / qn return axis * angle def quat_to_euler(quat, ordering='XYZ'): """Returns the euler angles corresponding to the provided quaternion. Args: quat: A quaternion [w, i, j, k]. ordering: (str) Desired euler angle ordering. Returns: euler_vec: The euler angle rotations. """ mat = quat_to_mat(quat) return rmat_to_euler(mat[0:3, 0:3], ordering=ordering) def quat_to_mat(quat): """Return homogeneous rotation matrix from quaternion. Args: quat: A quaternion [w, i, j, k]. Returns: A 4x4 homogeneous matrix with the rotation corresponding to `quat`. """ q = np.array(quat, dtype=np.float64, copy=True) nq = np.dot(q, q) if nq < _TOL: return np.identity(4) q *= np.sqrt(2.0 / nq) q = np.outer(q, q) return np.array( ((1.0 - q[2, 2] - q[3, 3], q[1, 2] - q[3, 0], q[1, 3] + q[2, 0], 0.0), (q[1, 2] + q[3, 0], 1.0 - q[1, 1] - q[3, 3], q[2, 3] - q[1, 0], 0.0), (q[1, 3] - q[2, 0], q[2, 3] + q[1, 0], 1.0 - q[1, 1] - q[2, 2], 0.0), (0.0, 0.0, 0.0, 1.0)), dtype=np.float64) def rotation_x_axis(theta, full=False): """Returns a rotation matrix of a rotation about the X-axis. Supports vector-valued theta, in which case the returned array is of shape (len(t), 3, 3), or (len(t), 4, 4) if full=True. If theta is scalar the batch dimension is squeezed out. Args: theta: The rotation amount. full: (bool) If true, returns a full 4x4 transform. """ n, ct, st, rmat = _axis_rotation(theta, full) rmat[:, 0, 0:3] = np.array([[1, 0, 0]]) rmat[:, 1, 0:3] = np.vstack([np.zeros(n), ct, -st]).T rmat[:, 2, 0:3] = np.vstack([np.zeros(n), st, ct]).T return rmat.squeeze() def rotation_y_axis(theta, full=False): """Returns a rotation matrix of a rotation about the Y-axis. Supports vector-valued theta, in which case the returned array is of shape (len(t), 3, 3), or (len(t), 4, 4) if full=True. If theta is scalar the batch dimension is squeezed out. Args: theta: The rotation amount. full: (bool) If true, returns a full 4x4 transfom. """ n, ct, st, rmat = _axis_rotation(theta, full) rmat[:, 0, 0:3] = np.vstack([ct, np.zeros(n), st]).T rmat[:, 1, 0:3] = np.array([[0, 1, 0]]) rmat[:, 2, 0:3] = np.vstack([-st, np.zeros(n), ct]).T return rmat.squeeze() def rotation_z_axis(theta, full=False): """Returns a rotation matrix of a rotation about the z-axis. Supports vector-valued theta, in which case the returned array is of shape (len(t), 3, 3), or (len(t), 4, 4) if full=True. If theta is scalar the batch dimension is squeezed out. Args: theta: The rotation amount. full: (bool) If true, returns a full 4x4 transfom. """ n, ct, st, rmat = _axis_rotation(theta, full) rmat[:, 0, 0:3] = np.vstack([ct, -st, np.zeros(n)]).T rmat[:, 1, 0:3] = np.vstack([st, ct, np.zeros(n)]).T rmat[:, 2, 0:3] = np.array([[0, 0, 1]]) return rmat.squeeze() def rmat_to_euler(rmat, ordering='ZXZ'): """Returns the euler angles corresponding to the provided rotation matrix. Args: rmat: The rotation matrix. ordering: (str) Desired euler angle ordering. Returns: Euler angles corresponding to the provided rotation matrix. """ return _eulermap[ordering](rmat) def mat_to_quat(mat): """Return quaternion from homogeneous or rotation matrix. Args: mat: A homogeneous transform or rotation matrix Returns: A quaternion [w, i, j, k]. """ if mat.shape == (3, 3): tmp = np.eye(4) tmp[0:3, 0:3] = mat mat = tmp q = np.empty((4,), dtype=np.float64) t = np.trace(mat) if t > mat[3, 3]: q[0] = t q[3] = mat[1, 0] - mat[0, 1] q[2] = mat[0, 2] - mat[2, 0] q[1] = mat[2, 1] - mat[1, 2] else: i, j, k = 0, 1, 2 if mat[1, 1] > mat[0, 0]: i, j, k = 1, 2, 0 if mat[2, 2] > mat[i, i]: i, j, k = 2, 0, 1 t = mat[i, i] - (mat[j, j] + mat[k, k]) + mat[3, 3] q[i + 1] = t q[j + 1] = mat[i, j] + mat[j, i] q[k + 1] = mat[k, i] + mat[i, k] q[0] = mat[k, j] - mat[j, k] q *= 0.5 / np.sqrt(t * mat[3, 3]) return q # ################ # # 2D Functions # # ################ def rotation_matrix_2d(theta): ct = np.cos(theta) st = np.sin(theta) return np.array([ [ct, -st], [st, ct] ])
dm_control-main
dm_control/utils/transformations.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. # ============================================================================ """Container classes used in control domains.""" import collections _NAME_ALREADY_EXISTS = ( "A function named {name!r} already exists in the container and " "`allow_overriding_keys` is False.") class TaggedTasks(collections.abc.Mapping): """Maps task names to their corresponding factory functions with tags. To store a function in a `TaggedTasks` container, we can use its `.add` decorator: ```python tasks = TaggedTasks() @tasks.add('easy', 'stable') def example_task(): ... return environment environment_factory = tasks['example_task'] # Or to restrict to a given tag: environment_factory = tasks.tagged('easy')['example_task'] ``` """ def __init__(self, allow_overriding_keys=False): """Initializes a new `TaggedTasks` container. Args: allow_overriding_keys: Boolean, whether `add` can override existing keys within the container. If False (default), calling `add` multiple times with the same function name will result in a `ValueError`. """ self._tasks = collections.OrderedDict() self._tags = collections.defaultdict(dict) self.allow_overriding_keys = allow_overriding_keys def add(self, *tags): """Decorator that adds a factory function to the container with tags. Args: *tags: Strings specifying the tags for this function. Returns: The same function. Raises: ValueError: if a function with the same name already exists within the container and `allow_overriding_keys` is False. """ def wrap(factory_func): name = factory_func.__name__ if name in self and not self.allow_overriding_keys: raise ValueError(_NAME_ALREADY_EXISTS.format(name=name)) self._tasks[name] = factory_func for tag in tags: self._tags[tag][name] = factory_func return factory_func return wrap def tagged(self, *tags): """Returns a (possibly empty) dict of functions matching all the given tags. Args: *tags: Strings specifying tags to query by. Returns: A dict of `{name: function}` containing all the functions that are tagged by all of the strings in `tags`. """ if not tags: return {} tags = set(tags) if not tags.issubset(self._tags.keys()): return {} names = self._tags[tags.pop()].keys() while tags: names &= self._tags[tags.pop()].keys() return {name: self._tasks[name] for name in names} def tags(self): """Returns a list of all the tags in this container.""" return list(self._tags.keys()) def __getitem__(self, k): return self._tasks[k] def __iter__(self): return iter(self._tasks) def __len__(self): return len(self._tasks) def __repr__(self): return "{}({})".format(self.__class__.__name__, str(self._tasks))
dm_control-main
dm_control/utils/containers.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for utils.xml_tools.""" import io from absl.testing import absltest from dm_control.utils import xml_tools import lxml etree = lxml.etree class XmlHelperTest(absltest.TestCase): def test_nested(self): element = etree.Element('inserted') xml_tools.nested_element(element, depth=2) level_1 = element.find('inserted') self.assertIsNotNone(level_1) level_2 = level_1.find('inserted') self.assertIsNotNone(level_2) def test_tostring(self): xml_str = """ <root> <head> <content></content> </head> </root>""" tree = xml_tools.parse(io.StringIO(xml_str)) self.assertEqual(b'<root>\n <head>\n <content/>\n </head>\n</root>\n', etree.tostring(tree, pretty_print=True)) def test_find_element(self): xml_str = """ <root> <option name='option_name'> <content></content> </option> <world name='world_name'> <geom name='geom_name'/> </world> </root>""" tree = xml_tools.parse(io.StringIO(xml_str)) world = xml_tools.find_element(root=tree, tag='world', name='world_name') self.assertEqual(world.tag, 'world') self.assertEqual(world.attrib['name'], 'world_name') geom = xml_tools.find_element(root=tree, tag='geom', name='geom_name') self.assertEqual(geom.tag, 'geom') self.assertEqual(geom.attrib['name'], 'geom_name') with self.assertRaisesRegex(ValueError, 'Element with tag'): xml_tools.find_element(root=tree, tag='does_not_exist', name='name') with self.assertRaisesRegex(ValueError, 'Element with tag'): xml_tools.find_element(root=tree, tag='world', name='does_not_exist') if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/utils/xml_tools_test.py
# Copyright 2017-2018 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """IO functions.""" import os def GetResource(name, mode='rb'): with open(name, mode=mode) as f: return f.read() def GetResourceFilename(name, mode='rb'): del mode # Unused. return name def WalkResources(path): return os.walk(path) GetResourceAsFile = open # pylint: disable=invalid-name
dm_control-main
dm_control/utils/io.py
# Copyright 2017-2018 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Functions for computing inverse kinematics on MuJoCo models.""" import collections from absl import logging from dm_control.mujoco.wrapper import mjbindings import numpy as np mjlib = mjbindings.mjlib _INVALID_JOINT_NAMES_TYPE = ( '`joint_names` must be either None, a list, a tuple, or a numpy array; ' 'got {}.') _REQUIRE_TARGET_POS_OR_QUAT = ( 'At least one of `target_pos` or `target_quat` must be specified.') IKResult = collections.namedtuple( 'IKResult', ['qpos', 'err_norm', 'steps', 'success']) def qpos_from_site_pose(physics, site_name, target_pos=None, target_quat=None, joint_names=None, tol=1e-14, rot_weight=1.0, regularization_threshold=0.1, regularization_strength=3e-2, max_update_norm=2.0, progress_thresh=20.0, max_steps=100, inplace=False): """Find joint positions that satisfy a target site position and/or rotation. Args: physics: A `mujoco.Physics` instance. site_name: A string specifying the name of the target site. target_pos: A (3,) numpy array specifying the desired Cartesian position of the site, or None if the position should be unconstrained (default). One or both of `target_pos` or `target_quat` must be specified. target_quat: A (4,) numpy array specifying the desired orientation of the site as a quaternion, or None if the orientation should be unconstrained (default). One or both of `target_pos` or `target_quat` must be specified. joint_names: (optional) A list, tuple or numpy array specifying the names of one or more joints that can be manipulated in order to achieve the target site pose. If None (default), all joints may be manipulated. tol: (optional) Precision goal for `qpos` (the maximum value of `err_norm` in the stopping criterion). rot_weight: (optional) Determines the weight given to rotational error relative to translational error. regularization_threshold: (optional) L2 regularization will be used when inverting the Jacobian whilst `err_norm` is greater than this value. regularization_strength: (optional) Coefficient of the quadratic penalty on joint movements. max_update_norm: (optional) The maximum L2 norm of the update applied to the joint positions on each iteration. The update vector will be scaled such that its magnitude never exceeds this value. progress_thresh: (optional) If `err_norm` divided by the magnitude of the joint position update is greater than this value then the optimization will terminate prematurely. This is a useful heuristic to avoid getting stuck in local minima. max_steps: (optional) The maximum number of iterations to perform. inplace: (optional) If True, `physics.data` will be modified in place. Default value is False, i.e. a copy of `physics.data` will be made. Returns: An `IKResult` namedtuple with the following fields: qpos: An (nq,) numpy array of joint positions. err_norm: A float, the weighted sum of L2 norms for the residual translational and rotational errors. steps: An int, the number of iterations that were performed. success: Boolean, True if we converged on a solution within `max_steps`, False otherwise. Raises: ValueError: If both `target_pos` and `target_quat` are None, or if `joint_names` has an invalid type. """ dtype = physics.data.qpos.dtype if target_pos is not None and target_quat is not None: jac = np.empty((6, physics.model.nv), dtype=dtype) err = np.empty(6, dtype=dtype) jac_pos, jac_rot = jac[:3], jac[3:] err_pos, err_rot = err[:3], err[3:] else: jac = np.empty((3, physics.model.nv), dtype=dtype) err = np.empty(3, dtype=dtype) if target_pos is not None: jac_pos, jac_rot = jac, None err_pos, err_rot = err, None elif target_quat is not None: jac_pos, jac_rot = None, jac err_pos, err_rot = None, err else: raise ValueError(_REQUIRE_TARGET_POS_OR_QUAT) update_nv = np.zeros(physics.model.nv, dtype=dtype) if target_quat is not None: site_xquat = np.empty(4, dtype=dtype) neg_site_xquat = np.empty(4, dtype=dtype) err_rot_quat = np.empty(4, dtype=dtype) if not inplace: physics = physics.copy(share_model=True) # Ensure that the Cartesian position of the site is up to date. mjlib.mj_fwdPosition(physics.model.ptr, physics.data.ptr) # Convert site name to index. site_id = physics.model.name2id(site_name, 'site') # These are views onto the underlying MuJoCo buffers. mj_fwdPosition will # update them in place, so we can avoid indexing overhead in the main loop. site_xpos = physics.named.data.site_xpos[site_name] site_xmat = physics.named.data.site_xmat[site_name] # This is an index into the rows of `update` and the columns of `jac` # that selects DOFs associated with joints that we are allowed to manipulate. if joint_names is None: dof_indices = slice(None) # Update all DOFs. elif isinstance(joint_names, (list, np.ndarray, tuple)): if isinstance(joint_names, tuple): joint_names = list(joint_names) # Find the indices of the DOFs belonging to each named joint. Note that # these are not necessarily the same as the joint IDs, since a single joint # may have >1 DOF (e.g. ball joints). indexer = physics.named.model.dof_jntid.axes.row # `dof_jntid` is an `(nv,)` array indexed by joint name. We use its row # indexer to map each joint name to the indices of its corresponding DOFs. dof_indices = indexer.convert_key_item(joint_names) else: raise ValueError(_INVALID_JOINT_NAMES_TYPE.format(type(joint_names))) steps = 0 success = False for steps in range(max_steps): err_norm = 0.0 if target_pos is not None: # Translational error. err_pos[:] = target_pos - site_xpos err_norm += np.linalg.norm(err_pos) if target_quat is not None: # Rotational error. mjlib.mju_mat2Quat(site_xquat, site_xmat) mjlib.mju_negQuat(neg_site_xquat, site_xquat) mjlib.mju_mulQuat(err_rot_quat, target_quat, neg_site_xquat) mjlib.mju_quat2Vel(err_rot, err_rot_quat, 1) err_norm += np.linalg.norm(err_rot) * rot_weight if err_norm < tol: logging.debug('Converged after %i steps: err_norm=%3g', steps, err_norm) success = True break else: # TODO(b/112141670): Generalize this to other entities besides sites. mjlib.mj_jacSite( physics.model.ptr, physics.data.ptr, jac_pos, jac_rot, site_id) jac_joints = jac[:, dof_indices] # TODO(b/112141592): This does not take joint limits into consideration. reg_strength = ( regularization_strength if err_norm > regularization_threshold else 0.0) update_joints = nullspace_method( jac_joints, err, regularization_strength=reg_strength) update_norm = np.linalg.norm(update_joints) # Check whether we are still making enough progress, and halt if not. progress_criterion = err_norm / update_norm if progress_criterion > progress_thresh: logging.debug('Step %2i: err_norm / update_norm (%3g) > ' 'tolerance (%3g). Halting due to insufficient progress', steps, progress_criterion, progress_thresh) break if update_norm > max_update_norm: update_joints *= max_update_norm / update_norm # Write the entries for the specified joints into the full `update_nv` # vector. update_nv[dof_indices] = update_joints # Update `physics.qpos`, taking quaternions into account. mjlib.mj_integratePos(physics.model.ptr, physics.data.qpos, update_nv, 1) # Compute the new Cartesian position of the site. mjlib.mj_fwdPosition(physics.model.ptr, physics.data.ptr) logging.debug('Step %2i: err_norm=%-10.3g update_norm=%-10.3g', steps, err_norm, update_norm) if not success and steps == max_steps - 1: logging.warning('Failed to converge after %i steps: err_norm=%3g', steps, err_norm) if not inplace: # Our temporary copy of physics.data is about to go out of scope, and when # it does the underlying mjData pointer will be freed and physics.data.qpos # will be a view onto a block of deallocated memory. We therefore need to # make a copy of physics.data.qpos while physics.data is still alive. qpos = physics.data.qpos.copy() else: # If we're modifying physics.data in place then it's fine to return a view. qpos = physics.data.qpos return IKResult(qpos=qpos, err_norm=err_norm, steps=steps, success=success) def nullspace_method(jac_joints, delta, regularization_strength=0.0): """Calculates the joint velocities to achieve a specified end effector delta. Args: jac_joints: The Jacobian of the end effector with respect to the joints. A numpy array of shape `(ndelta, nv)`, where `ndelta` is the size of `delta` and `nv` is the number of degrees of freedom. delta: The desired end-effector delta. A numpy array of shape `(3,)` or `(6,)` containing either position deltas, rotation deltas, or both. regularization_strength: (optional) Coefficient of the quadratic penalty on joint movements. Default is zero, i.e. no regularization. Returns: An `(nv,)` numpy array of joint velocities. Reference: Buss, S. R. S. (2004). Introduction to inverse kinematics with jacobian transpose, pseudoinverse and damped least squares methods. https://www.math.ucsd.edu/~sbuss/ResearchWeb/ikmethods/iksurvey.pdf """ hess_approx = jac_joints.T.dot(jac_joints) joint_delta = jac_joints.T.dot(delta) if regularization_strength > 0: # L2 regularization hess_approx += np.eye(hess_approx.shape[0]) * regularization_strength return np.linalg.solve(hess_approx, joint_delta) else: return np.linalg.lstsq(hess_approx, joint_delta, rcond=-1)[0]
dm_control-main
dm_control/utils/inverse_kinematics.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. # ============================================================================
dm_control-main
dm_control/utils/__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. # ============================================================================ """Helper functions for model xml creation and modification.""" import copy from lxml import etree def find_element(root, tag, name): """Finds and returns the first element of specified tag and name. Args: root: `etree.Element` to be searched recursively. tag: The `tag` property of the sought element. name: The `name` attribute of the sought element. Returns: An `etree.Element` with the specified properties. Raises: ValueError: If no matching element is found. """ result = root.find('.//{}[@name={!r}]'.format(tag, name)) if result is None: raise ValueError( 'Element with tag {!r} and name {!r} not found'.format(tag, name)) return result def nested_element(element, depth): """Makes a nested `tree.Element` given a single element. If `depth=2`, the new tree will look like ```xml <element> <element> <element> </element> </element> </element> ``` Args: element: The `etree.Element` used to create a nested structure. depth: An `int` denoting the nesting depth. The resulting will contain `element` nested `depth` times. Returns: A nested `etree.Element`. """ if depth > 0: child = nested_element(copy.deepcopy(element), depth=(depth - 1)) element.append(child) return element def parse(file_obj): """Reads xml from a file and returns an `etree.Element`. Compared to the `etree.fromstring()`, this function removes the whitespace in the xml file. This means later on, a user can pretty print the `etree.Element` with `etree.tostring(element, pretty_print=True)`. Args: file_obj: A file or file-like object. Returns: `etree.Element` of the xml file. """ parser = etree.XMLParser(remove_blank_text=True) return etree.parse(file_obj, parser)
dm_control-main
dm_control/utils/xml_tools.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. # ============================================================================ """Soft indicator function evaluating whether a number is within bounds.""" import warnings import numpy as np # The value returned by tolerance() at `margin` distance from `bounds` interval. _DEFAULT_VALUE_AT_MARGIN = 0.1 def _sigmoids(x, value_at_1, sigmoid): """Returns 1 when `x` == 0, between 0 and 1 otherwise. Args: x: A scalar or numpy array. value_at_1: A float between 0 and 1 specifying the output when `x` == 1. sigmoid: String, choice of sigmoid type. Returns: A numpy array with values between 0.0 and 1.0. Raises: ValueError: If not 0 < `value_at_1` < 1, except for `linear`, `cosine` and `quadratic` sigmoids which allow `value_at_1` == 0. ValueError: If `sigmoid` is of an unknown type. """ if sigmoid in ('cosine', 'linear', 'quadratic'): if not 0 <= value_at_1 < 1: raise ValueError('`value_at_1` must be nonnegative and smaller than 1, ' 'got {}.'.format(value_at_1)) else: if not 0 < value_at_1 < 1: raise ValueError('`value_at_1` must be strictly between 0 and 1, ' 'got {}.'.format(value_at_1)) if sigmoid == 'gaussian': scale = np.sqrt(-2 * np.log(value_at_1)) return np.exp(-0.5 * (x*scale)**2) elif sigmoid == 'hyperbolic': scale = np.arccosh(1/value_at_1) return 1 / np.cosh(x*scale) elif sigmoid == 'long_tail': scale = np.sqrt(1/value_at_1 - 1) return 1 / ((x*scale)**2 + 1) elif sigmoid == 'reciprocal': scale = 1/value_at_1 - 1 return 1 / (abs(x)*scale + 1) elif sigmoid == 'cosine': scale = np.arccos(2*value_at_1 - 1) / np.pi scaled_x = x*scale with warnings.catch_warnings(): warnings.filterwarnings( action='ignore', message='invalid value encountered in cos') cos_pi_scaled_x = np.cos(np.pi*scaled_x) return np.where(abs(scaled_x) < 1, (1 + cos_pi_scaled_x)/2, 0.0) elif sigmoid == 'linear': scale = 1-value_at_1 scaled_x = x*scale return np.where(abs(scaled_x) < 1, 1 - scaled_x, 0.0) elif sigmoid == 'quadratic': scale = np.sqrt(1-value_at_1) scaled_x = x*scale return np.where(abs(scaled_x) < 1, 1 - scaled_x**2, 0.0) elif sigmoid == 'tanh_squared': scale = np.arctanh(np.sqrt(1-value_at_1)) return 1 - np.tanh(x*scale)**2 else: raise ValueError('Unknown sigmoid type {!r}.'.format(sigmoid)) def tolerance(x, bounds=(0.0, 0.0), margin=0.0, sigmoid='gaussian', value_at_margin=_DEFAULT_VALUE_AT_MARGIN): """Returns 1 when `x` falls inside the bounds, between 0 and 1 otherwise. Args: x: A scalar or numpy array. bounds: A tuple of floats specifying inclusive `(lower, upper)` bounds for the target interval. These can be infinite if the interval is unbounded at one or both ends, or they can be equal to one another if the target value is exact. margin: Float. Parameter that controls how steeply the output decreases as `x` moves out-of-bounds. * If `margin == 0` then the output will be 0 for all values of `x` outside of `bounds`. * If `margin > 0` then the output will decrease sigmoidally with increasing distance from the nearest bound. sigmoid: String, choice of sigmoid type. Valid values are: 'gaussian', 'linear', 'hyperbolic', 'long_tail', 'cosine', 'tanh_squared'. value_at_margin: A float between 0 and 1 specifying the output value when the distance from `x` to the nearest bound is equal to `margin`. Ignored if `margin == 0`. Returns: A float or numpy array with values between 0.0 and 1.0. Raises: ValueError: If `bounds[0] > bounds[1]`. ValueError: If `margin` is negative. """ lower, upper = bounds if lower > upper: raise ValueError('Lower bound must be <= upper bound.') if margin < 0: raise ValueError('`margin` must be non-negative.') in_bounds = np.logical_and(lower <= x, x <= upper) if margin == 0: value = np.where(in_bounds, 1.0, 0.0) else: d = np.where(x < lower, lower - x, x - upper) / margin value = np.where(in_bounds, 1.0, _sigmoids(d, value_at_margin, sigmoid)) return float(value) if np.isscalar(x) else value
dm_control-main
dm_control/utils/rewards.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for dm_control.utils.rewards.""" from absl.testing import absltest from absl.testing import parameterized from dm_control.utils import rewards import numpy as np _INPUT_VECTOR_SIZE = 10 EPS = np.finfo(np.double).eps INF = float("inf") class ToleranceTest(parameterized.TestCase): @parameterized.parameters((0.5, 0.95), (1e12, 1-EPS), (1e12, EPS), (EPS, 1-EPS), (EPS, EPS)) def test_tolerance_sigmoid_parameterisation(self, margin, value_at_margin): actual = rewards.tolerance(x=margin, bounds=(0, 0), margin=margin, value_at_margin=value_at_margin) self.assertAlmostEqual(actual, value_at_margin) @parameterized.parameters(("gaussian",), ("hyperbolic",), ("long_tail",), ("cosine",), ("tanh_squared",), ("linear",), ("quadratic",), ("reciprocal",)) def test_tolerance_sigmoids(self, sigmoid): margins = [0.01, 1.0, 100, 10000] values_at_margin = [0.1, 0.5, 0.9] bounds_list = [(0, 0), (-1, 1), (-np.pi, np.pi), (-100, 100)] for bounds in bounds_list: for margin in margins: for value_at_margin in values_at_margin: upper_margin = bounds[1]+margin value = rewards.tolerance(x=upper_margin, bounds=bounds, margin=margin, value_at_margin=value_at_margin, sigmoid=sigmoid) self.assertAlmostEqual(value, value_at_margin, delta=np.sqrt(EPS)) lower_margin = bounds[0]-margin value = rewards.tolerance(x=lower_margin, bounds=bounds, margin=margin, value_at_margin=value_at_margin, sigmoid=sigmoid) self.assertAlmostEqual(value, value_at_margin, delta=np.sqrt(EPS)) @parameterized.parameters((-1, 0), (-0.5, 0.1), (0, 1), (0.5, 0.1), (1, 0)) def test_tolerance_margin_loss_shape(self, x, expected): actual = rewards.tolerance(x=x, bounds=(0, 0), margin=0.5, value_at_margin=0.1) self.assertAlmostEqual(actual, expected, delta=1e-3) def test_tolerance_vectorization(self): bounds = (-.1, .1) margin = 0.2 x_array = np.random.randn(2, 3, 4) value_array = rewards.tolerance(x=x_array, bounds=bounds, margin=margin) self.assertEqual(x_array.shape, value_array.shape) for i, x in enumerate(x_array.ravel()): value = rewards.tolerance(x=x, bounds=bounds, margin=margin) self.assertEqual(value, value_array.ravel()[i]) # pylint: disable=bad-whitespace @parameterized.parameters( # Exact target. (0, (0, 0), 1), (EPS, (0, 0), 0), (-EPS, (0, 0), 0), # Interval with one open end. (0, (0, INF), 1), (EPS, (0, INF), 1), (-EPS, (0, INF), 0), # Closed interval. (0, (0, 1), 1), (EPS, (0, 1), 1), (-EPS, (0, 1), 0), (1, (0, 1), 1), (1+EPS, (0, 1), 0)) def test_tolerance_bounds(self, x, bounds, expected): actual = rewards.tolerance(x, bounds=bounds, margin=0) self.assertEqual(actual, expected) # Should be exact, since margin == 0. def test_tolerance_incorrect_bounds_order(self): with self.assertRaisesWithLiteralMatch( ValueError, "Lower bound must be <= upper bound."): rewards.tolerance(0, bounds=(1, 0), margin=0.05) def test_tolerance_negative_margin(self): with self.assertRaisesWithLiteralMatch( ValueError, "`margin` must be non-negative."): rewards.tolerance(0, bounds=(0, 1), margin=-0.05) def test_tolerance_bad_value_at_margin(self): with self.assertRaisesWithLiteralMatch( ValueError, "`value_at_1` must be strictly between 0 and 1, got 0."): rewards.tolerance(0, bounds=(0, 1), margin=1, value_at_margin=0) def test_tolerance_unknown_sigmoid(self): with self.assertRaisesWithLiteralMatch( ValueError, "Unknown sigmoid type 'unsupported_sigmoid'."): rewards.tolerance(0, bounds=(0, 1), margin=.1, sigmoid="unsupported_sigmoid") if __name__ == "__main__": absltest.main()
dm_control-main
dm_control/utils/rewards_test.py
# Copyright 2017-2018 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for inverse_kinematics.""" import itertools from absl.testing import absltest from absl.testing import parameterized from dm_control import mujoco from dm_control.mujoco.testing import assets from dm_control.mujoco.wrapper import mjbindings from dm_control.utils import inverse_kinematics as ik import numpy as np mjlib = mjbindings.mjlib _ARM_XML = assets.get_contents('arm.xml') _MODEL_WITH_BALL_JOINTS_XML = assets.get_contents('model_with_ball_joints.xml') _SITE_NAME = 'gripsite' _JOINTS = ['joint_1', 'joint_2', 'joint_3', 'joint_4', 'joint_5', 'joint_6'] _TOL = 1.2e-14 _MAX_STEPS = 100 _MAX_RESETS = 10 _TARGETS = [ # target_pos # target_quat (np.array([0., 0., 0.3]), np.array([0., 1., 0., 1.])), (np.array([-0.5, 0., 0.5]), None), (np.array([0., 0., 0.8]), np.array([0., 1., 0., 1.])), (np.array([0., 0., 0.8]), None), (np.array([0., -0.1, 0.5]), None), (np.array([0., -0.1, 0.5]), np.array([1., 1., 0., 0.])), (np.array([0.5, 0., 0.5]), None), (np.array([0.4, 0.1, 0.5]), None), (np.array([0.4, 0.1, 0.5]), np.array([1., 0., 0., 0.])), (np.array([0., 0., 0.3]), None), (np.array([0., 0.5, -0.2]), None), (np.array([0.5, 0., 0.3]), np.array([1., 0., 0., 1.])), (None, np.array([1., 0., 0., 1.])), (None, np.array([0., 1., 0., 1.])), ] _INPLACE = [False, True] class _ResetArm: def __init__(self, seed=None): self._rng = np.random.RandomState(seed) self._lower = None self._upper = None def _cache_bounds(self, physics): self._lower, self._upper = physics.named.model.jnt_range[_JOINTS].T limited = physics.named.model.jnt_limited[_JOINTS].astype(bool) # Positions for hinge joints without limits are sampled between 0 and 2pi self._lower[~limited] = 0 self._upper[~limited] = 2 * np.pi def __call__(self, physics): if self._lower is None: self._cache_bounds(physics) # NB: This won't work for joints with > 1 DOF new_qpos = self._rng.uniform(self._lower, self._upper) physics.named.data.qpos[_JOINTS] = new_qpos class InverseKinematicsTest(parameterized.TestCase): @parameterized.parameters(itertools.product(_TARGETS, _INPLACE)) def testQposFromSitePose(self, target, inplace): physics = mujoco.Physics.from_xml_string(_ARM_XML) target_pos, target_quat = target count = 0 physics2 = physics.copy(share_model=True) resetter = _ResetArm(seed=0) while True: result = ik.qpos_from_site_pose( physics=physics2, site_name=_SITE_NAME, target_pos=target_pos, target_quat=target_quat, joint_names=_JOINTS, tol=_TOL, max_steps=_MAX_STEPS, inplace=inplace, ) if result.success: break elif count < _MAX_RESETS: resetter(physics2) count += 1 else: raise RuntimeError( 'Failed to find a solution within %i attempts.' % _MAX_RESETS) self.assertLessEqual(result.steps, _MAX_STEPS) self.assertLessEqual(result.err_norm, _TOL) physics.data.qpos[:] = result.qpos mjlib.mj_fwdPosition(physics.model.ptr, physics.data.ptr) if target_pos is not None: pos = physics.named.data.site_xpos[_SITE_NAME] np.testing.assert_array_almost_equal(pos, target_pos) if target_quat is not None: xmat = physics.named.data.site_xmat[_SITE_NAME] quat = np.empty_like(target_quat) mjlib.mju_mat2Quat(quat, xmat) quat /= quat.ptp() # Normalize xquat so that its max-min range is 1 np.testing.assert_array_almost_equal(quat, target_quat) def testNamedJointsWithMultipleDOFs(self): """Regression test for b/77506142.""" physics = mujoco.Physics.from_xml_string(_MODEL_WITH_BALL_JOINTS_XML) site_name = 'gripsite' joint_names = ['joint_1', 'joint_2'] # This target position can only be achieved by rotating both ball joints. If # DOFs are incorrectly indexed by joint index then only the first two DOFs # in the first ball joint can change, and IK will fail to find a solution. target_pos = (0.05, 0.05, 0) result = ik.qpos_from_site_pose( physics=physics, site_name=site_name, target_pos=target_pos, joint_names=joint_names, tol=_TOL, max_steps=_MAX_STEPS, inplace=True) self.assertTrue(result.success) self.assertLessEqual(result.steps, _MAX_STEPS) self.assertLessEqual(result.err_norm, _TOL) pos = physics.named.data.site_xpos[site_name] np.testing.assert_array_almost_equal(pos, target_pos) # IK should fail to converge if only the first joint is allowed to move. physics.reset() result = ik.qpos_from_site_pose( physics=physics, site_name=site_name, target_pos=target_pos, joint_names=joint_names[:1], tol=_TOL, max_steps=_MAX_STEPS, inplace=True) self.assertFalse(result.success) @parameterized.named_parameters( ('None', None), ('list', ['joint_1', 'joint_2']), ('tuple', ('joint_1', 'joint_2')), ('numpy.array', np.array(['joint_1', 'joint_2']))) def testAllowedJointNameTypes(self, joint_names): """Test allowed types for joint_names parameter.""" physics = mujoco.Physics.from_xml_string(_ARM_XML) site_name = 'gripsite' target_pos = (0.05, 0.05, 0) ik.qpos_from_site_pose( physics=physics, site_name=site_name, target_pos=target_pos, joint_names=joint_names, tol=_TOL, max_steps=_MAX_STEPS, inplace=True) @parameterized.named_parameters( ('int', 1), ('dict', {'joint_1': 1, 'joint_2': 2}), ('function', lambda x: x), ) def testDisallowedJointNameTypes(self, joint_names): physics = mujoco.Physics.from_xml_string(_ARM_XML) site_name = 'gripsite' target_pos = (0.05, 0.05, 0) expected_message = ik._INVALID_JOINT_NAMES_TYPE.format(type(joint_names)) with self.assertRaisesWithLiteralMatch(ValueError, expected_message): ik.qpos_from_site_pose( physics=physics, site_name=site_name, target_pos=target_pos, joint_names=joint_names, tol=_TOL, max_steps=_MAX_STEPS, inplace=True) def testNoTargetPosOrQuat(self): physics = mujoco.Physics.from_xml_string(_ARM_XML) site_name = 'gripsite' with self.assertRaisesWithLiteralMatch( ValueError, ik._REQUIRE_TARGET_POS_OR_QUAT): ik.qpos_from_site_pose( physics=physics, site_name=site_name, tol=_TOL, max_steps=_MAX_STEPS, inplace=True) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/utils/inverse_kinematics_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 the views.py module.""" from absl.testing import absltest from dm_control.viewer import views import mock import numpy as np class ColumnTextViewTest(absltest.TestCase): def setUp(self): super().setUp() self.model = mock.MagicMock() self.view = views.ColumnTextView(self.model) self.context = mock.MagicMock() self.viewport = mock.MagicMock() self.location = views.PanelLocation.TOP_LEFT def test_rendering_empty_columns(self): self.model.get_columns.return_value = [] with mock.patch(views.__name__ + '.mujoco') as mjlib_mock: self.view.render(self.context, self.viewport, self.location) self.assertEqual(0, mjlib_mock.mjr_overlay.call_count) def test_rendering(self): self.model.get_columns.return_value = [('', '')] with mock.patch(views.__name__ + '.mujoco') as mjlib_mock: self.view.render(self.context, self.viewport, self.location) mjlib_mock.mjr_overlay.assert_called_once() class MujocoDepthBufferTests(absltest.TestCase): def setUp(self): super().setUp() self.component = views.MujocoDepthBuffer() self.context = mock.MagicMock() self.viewport = mock.MagicMock() def test_updating_buffer_size_after_viewport_resize(self): self.component._depth_buffer = np.zeros((1, 1), np.float32) self.viewport.width = 10 self.viewport.height = 10 with mock.patch(views.__name__ + '.mujoco'): self.component.render(context=self.context, viewport=self.viewport) self.assertEqual((10, 10), self.component._depth_buffer.shape) def test_reading_depth_data(self): with mock.patch(views.__name__ + '.mujoco') as mjlib_mock: self.component.render(context=self.context, viewport=self.viewport) mjlib_mock.mjr_readPixels.assert_called_once() self.assertIsNone(mjlib_mock.mjr_readPixels.call_args[0][0]) @absltest.skip('b/222664582') def test_rendering_position_fixed_to_bottom_right_quarter_of_viewport(self): self.viewport.width = 100 self.viewport.height = 100 expected_rect = [75, 0, 25, 25] with mock.patch(views.__name__ + '.mujoco') as mjlib_mock: self.component.render(context=self.context, viewport=self.viewport) mjlib_mock.mjr_drawPixels.assert_called_once() render_rect = mjlib_mock.mjr_drawPixels.call_args[0][2] self.assertEqual(expected_rect[0], render_rect.left) self.assertEqual(expected_rect[1], render_rect.bottom) self.assertEqual(expected_rect[2], render_rect.width) self.assertEqual(expected_rect[3], render_rect.height) class ViewportLayoutTest(absltest.TestCase): def setUp(self): super().setUp() self.layout = views.ViewportLayout() self.context = mock.MagicMock() self.viewport = mock.MagicMock() def test_added_elements_need_to_be_a_view(self): self.element = mock.MagicMock() with self.assertRaises(TypeError): self.layout.add(self.element, views.PanelLocation.TOP_LEFT) def test_adding_component(self): self.element = mock.MagicMock(spec=views.BaseViewportView) self.layout.add(self.element, views.PanelLocation.TOP_LEFT) self.assertLen(self.layout, 1) def test_adding_same_component_twice_updates_location(self): self.element = mock.MagicMock(spec=views.BaseViewportView) self.layout.add(self.element, views.PanelLocation.TOP_LEFT) self.layout.add(self.element, views.PanelLocation.TOP_RIGHT) self.assertEqual( views.PanelLocation.TOP_RIGHT, self.layout._views[self.element]) def test_removing_component(self): self.element = mock.MagicMock(spec=views.BaseViewportView) self.layout._views[self.element] = views.PanelLocation.TOP_LEFT self.layout.remove(self.element) self.assertEmpty(self.layout) def test_removing_unregistered_component(self): self.element = mock.MagicMock(spec=views.BaseViewportView) self.layout.remove(self.element) # No error is raised def test_clearing_layout(self): pos = views.PanelLocation.TOP_LEFT self.layout._views = {mock.MagicMock(spec=views.BaseViewportView): pos for _ in range(3)} self.layout.clear() self.assertEmpty(self.layout) def test_rendering_layout(self): positions = [ views.PanelLocation.TOP_LEFT, views.PanelLocation.TOP_RIGHT, views.PanelLocation.BOTTOM_LEFT] self.layout._views = {mock.MagicMock(spec=views.BaseViewportView): pos for pos in positions} self.layout.render(self.context, self.viewport) for view, location in self.layout._views.items(): view.render.assert_called_once() self.assertEqual(location, view.render.call_args[0][2]) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/viewer/views_test.py
# Copyright 2018 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Utilities for handling keyboard events.""" import collections # Mapped input values, so that we don't have to reference glfw everywhere. RELEASE = 0 PRESS = 1 REPEAT = 2 KEY_UNKNOWN = -1 KEY_SPACE = 32 KEY_APOSTROPHE = 39 KEY_COMMA = 44 KEY_MINUS = 45 KEY_PERIOD = 46 KEY_SLASH = 47 KEY_0 = 48 KEY_1 = 49 KEY_2 = 50 KEY_3 = 51 KEY_4 = 52 KEY_5 = 53 KEY_6 = 54 KEY_7 = 55 KEY_8 = 56 KEY_9 = 57 KEY_SEMICOLON = 59 KEY_EQUAL = 61 KEY_A = 65 KEY_B = 66 KEY_C = 67 KEY_D = 68 KEY_E = 69 KEY_F = 70 KEY_G = 71 KEY_H = 72 KEY_I = 73 KEY_J = 74 KEY_K = 75 KEY_L = 76 KEY_M = 77 KEY_N = 78 KEY_O = 79 KEY_P = 80 KEY_Q = 81 KEY_R = 82 KEY_S = 83 KEY_T = 84 KEY_U = 85 KEY_V = 86 KEY_W = 87 KEY_X = 88 KEY_Y = 89 KEY_Z = 90 KEY_LEFT_BRACKET = 91 KEY_BACKSLASH = 92 KEY_RIGHT_BRACKET = 93 KEY_GRAVE_ACCENT = 96 KEY_ESCAPE = 256 KEY_ENTER = 257 KEY_TAB = 258 KEY_BACKSPACE = 259 KEY_INSERT = 260 KEY_DELETE = 261 KEY_RIGHT = 262 KEY_LEFT = 263 KEY_DOWN = 264 KEY_UP = 265 KEY_PAGE_UP = 266 KEY_PAGE_DOWN = 267 KEY_HOME = 268 KEY_END = 269 KEY_CAPS_LOCK = 280 KEY_SCROLL_LOCK = 281 KEY_NUM_LOCK = 282 KEY_PRINT_SCREEN = 283 KEY_PAUSE = 284 KEY_F1 = 290 KEY_F2 = 291 KEY_F3 = 292 KEY_F4 = 293 KEY_F5 = 294 KEY_F6 = 295 KEY_F7 = 296 KEY_F8 = 297 KEY_F9 = 298 KEY_F10 = 299 KEY_F11 = 300 KEY_F12 = 301 KEY_KP_0 = 320 KEY_KP_1 = 321 KEY_KP_2 = 322 KEY_KP_3 = 323 KEY_KP_4 = 324 KEY_KP_5 = 325 KEY_KP_6 = 326 KEY_KP_7 = 327 KEY_KP_8 = 328 KEY_KP_9 = 329 KEY_KP_DECIMAL = 330 KEY_KP_DIVIDE = 331 KEY_KP_MULTIPLY = 332 KEY_KP_SUBTRACT = 333 KEY_KP_ADD = 334 KEY_KP_ENTER = 335 KEY_KP_EQUAL = 336 KEY_LEFT_SHIFT = 340 KEY_LEFT_CONTROL = 341 KEY_LEFT_ALT = 342 KEY_LEFT_SUPER = 343 KEY_RIGHT_SHIFT = 344 KEY_RIGHT_CONTROL = 345 KEY_RIGHT_ALT = 346 KEY_RIGHT_SUPER = 347 MOD_NONE = 0 MOD_SHIFT = 0x0001 MOD_CONTROL = 0x0002 MOD_ALT = 0x0004 MOD_SUPER = 0x0008 MOD_SHIFT_CONTROL = MOD_SHIFT | MOD_CONTROL MOUSE_BUTTON_LEFT = 0 MOUSE_BUTTON_RIGHT = 1 MOUSE_BUTTON_MIDDLE = 2 _NO_EXCLUSIVE_KEY = (None, lambda _: None) _NO_CALLBACK = (None, None) class Exclusive(collections.namedtuple('Exclusive', 'combination')): """Defines an exclusive action. Exclusive actions can be invoked in response to single key clicks only. The callback will be called twice. The first time when the key combination is pressed, passing True as the argument to the callback. The second time when the key is released (the modifiers don't have to be present then), passing False as the callback argument. Attributes: combination: A list of integers interpreted as key codes, or tuples in format (keycode, modifier). """ pass class DoubleClick(collections.namedtuple('DoubleClick', 'combination')): """Defines a mouse double click action. It will define a requirement to double click the mouse button specified in the combination in order to be triggered. Attributes: combination: A list of integers interpreted as key codes, or tuples in format (keycode, modifier). The keycodes are limited only to mouse button codes. """ pass class Range(collections.namedtuple('Range', 'collection')): """Binds a number of key combinations to a callback. When triggered, the index of the triggering key combination will be passed as an argument to the callback. Attributes: callback: A callable accepting a single argument - an integer index of the triggered callback. collection: A collection of combinations. Combinations may either be raw key codes, tuples in format (keycode, modifier), or one of the Exclusive or DoubleClick instances. """ pass class InputMap: """Provides ability to alias key combinations and map them to actions.""" def __init__(self, mouse, keyboard): """Instance initializer. Args: mouse: GlfwMouse instance. keyboard: GlfwKeyboard instance. """ self._keyboard = keyboard self._mouse = mouse self._keyboard.on_key += self._handle_key self._mouse.on_click += self._handle_key self._mouse.on_double_click += self._handle_double_click self._mouse.on_move += self._handle_mouse_move self._mouse.on_scroll += self._handle_mouse_scroll self.clear_bindings() def __del__(self): """Instance deleter.""" self._keyboard.on_key -= self._handle_key self._mouse.on_click -= self._handle_key self._mouse.on_double_click -= self._handle_double_click self._mouse.on_move -= self._handle_mouse_move self._mouse.on_scroll -= self._handle_mouse_scroll def clear_bindings(self): """Clears registered action bindings, while keeping key aliases.""" self._action_callbacks = {} self._double_click_callbacks = {} self._plane_callback = [] self._z_axis_callback = [] self._active_exclusive = _NO_EXCLUSIVE_KEY def bind(self, callback, key_binding): """Binds a key combination to a callback. Args: callback: An argument-less callable. key_binding: A integer with a key code, a tuple (keycode, modifier) or one of the actions Exclusive|DoubleClick|Range carrying the key combination. """ def build_callback(index, callback): def indexed_callback(): callback(index) return indexed_callback if isinstance(key_binding, Range): for index, binding in enumerate(key_binding.collection): self._add_binding(build_callback(index, callback), binding) else: self._add_binding(callback, key_binding) def _add_binding(self, callback, key_binding): key_combination = self._extract_key_combination(key_binding) if isinstance(key_binding, Exclusive): self._action_callbacks[key_combination] = (True, callback) elif isinstance(key_binding, DoubleClick): self._double_click_callbacks[key_combination] = callback else: self._action_callbacks[key_combination] = (False, callback) def _extract_key_combination(self, key_binding): if isinstance(key_binding, Exclusive): key_binding = key_binding.combination elif isinstance(key_binding, DoubleClick): key_binding = key_binding.combination if not isinstance(key_binding, tuple): key_binding = (key_binding, MOD_NONE) return key_binding def bind_plane(self, callback): """Binds a callback to a planar motion action (mouse movement).""" self._plane_callback.append(callback) def bind_z_axis(self, callback): """Binds a callback to a z-axis motion action (mouse scroll).""" self._z_axis_callback.append(callback) def _handle_key(self, key, action, modifiers): """Handles a single key press (mouse and keyboard).""" alias_key = (key, modifiers) exclusive_key, exclusive_callback = self._active_exclusive if exclusive_key is not None: if action == RELEASE and key == exclusive_key: exclusive_callback(False) self._active_exclusive = _NO_EXCLUSIVE_KEY else: is_exclusive, callback = self._action_callbacks.get( alias_key, _NO_CALLBACK) if callback: if action == PRESS: if is_exclusive: callback(True) self._active_exclusive = (key, callback) else: callback() def _handle_double_click(self, key, modifiers): """Handles a double mouse click.""" alias_key = (key, modifiers) callback = self._double_click_callbacks.get(alias_key, None) if callback is not None: callback() def _handle_mouse_move(self, position, translation): """Handles mouse move.""" for callback in self._plane_callback: callback(position, translation) def _handle_mouse_scroll(self, value): """Handles mouse wheel scroll.""" for callback in self._z_axis_callback: callback(value)
dm_control-main
dm_control/viewer/user_input.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 of the application.py module.""" from absl.testing import absltest from absl.testing import parameterized from dm_control.viewer import application import dm_env from dm_env import specs import mock import numpy as np class ApplicationTest(parameterized.TestCase): def setUp(self): super().setUp() with mock.patch(application.__name__ + '.gui'): self.app = application.Application() self.app._viewer = mock.MagicMock() self.app._keyboard_action = mock.MagicMock() self.environment = mock.MagicMock(spec=dm_env.Environment) self.environment.action_spec.return_value = specs.BoundedArray( (1,), np.float64, -1, 1) self.environment.physics = mock.MagicMock() self.app._environment = self.environment self.agent = mock.MagicMock() self.loader = lambda: self.environment def test_on_reload_defers_viewer_initialization_until_tick(self): self.app._on_reload(zoom_to_scene=True) self.assertEqual(0, self.app._viewer.initialize.call_count) self.assertIsNotNone(self.app._deferred_reload_request) def test_deferred_on_reload_parameters(self): self.app._on_reload(zoom_to_scene=True) self.assertTrue(self.app._deferred_reload_request.zoom_to_scene) self.app._on_reload(zoom_to_scene=False) self.assertFalse(self.app._deferred_reload_request.zoom_to_scene) def test_executing_deferred_initialization(self): self.app._deferred_reload_request = application.ReloadParams(False) self.app._tick() self.app._viewer.initialize.assert_called_once() def test_processing_zoom_to_scene_request(self): self.app._perform_deferred_reload(application.ReloadParams(True)) self.app._viewer.zoom_to_scene.assert_called_once() def test_skipping_zoom_to_scene(self): self.app._perform_deferred_reload(application.ReloadParams(False)) self.app._viewer.zoom_to_scene.assert_not_called() def test_on_reload_deinitializes_viewer_instantly(self): self.app._on_reload() self.app._viewer.deinitialize.assert_called_once() def test_zoom_to_scene_after_launch(self): self.app.launch(self.loader, self.agent) self.app._viewer.zoom_to_scene() def test_tick_runtime(self): self.app._runtime = mock.MagicMock() self.app._pause_subject.value = False self.app._tick() self.app._runtime.tick.assert_called_once() def test_restart_runtime(self): self.app._load_environment = mock.MagicMock() self.app._runtime = mock.MagicMock() self.app._restart_runtime() self.app._runtime.stop.assert_called_once() self.app._load_environment.assert_called_once() if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/viewer/application_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. # ============================================================================ """Mujoco Physics viewer, with custom input controllers.""" from dm_control.mujoco.wrapper import mjbindings from dm_control.viewer import renderer from dm_control.viewer import user_input from dm_control.viewer import util import mujoco functions = mjbindings.functions _NUM_GROUP_KEYS = 10 _PAN_CAMERA_VERTICAL_MOUSE = user_input.Exclusive( user_input.MOUSE_BUTTON_RIGHT) _PAN_CAMERA_HORIZONTAL_MOUSE = user_input.Exclusive( (user_input.MOUSE_BUTTON_RIGHT, user_input.MOD_SHIFT)) _ROTATE_OBJECT_MOUSE = user_input.Exclusive( (user_input.MOUSE_BUTTON_LEFT, user_input.MOD_CONTROL)) _MOVE_OBJECT_VERTICAL_MOUSE = user_input.Exclusive( (user_input.MOUSE_BUTTON_RIGHT, user_input.MOD_CONTROL)) _MOVE_OBJECT_HORIZONTAL_MOUSE = user_input.Exclusive( (user_input.MOUSE_BUTTON_RIGHT, user_input.MOD_SHIFT_CONTROL)) _PAN_CAMERA_VERTICAL_TOUCHPAD = user_input.Exclusive( (user_input.MOUSE_BUTTON_LEFT, user_input.MOD_ALT)) _PAN_CAMERA_HORIZONTAL_TOUCHPAD = user_input.Exclusive( (user_input.MOUSE_BUTTON_RIGHT, user_input.MOD_ALT)) _ROTATE_OBJECT_TOUCHPAD = user_input.Exclusive( user_input.MOUSE_BUTTON_RIGHT) _MOVE_OBJECT_VERTICAL_TOUCHPAD = user_input.Exclusive( (user_input.MOUSE_BUTTON_LEFT, user_input.MOD_CONTROL)) _MOVE_OBJECT_HORIZONTAL_TOUCHPAD = user_input.Exclusive( (user_input.MOUSE_BUTTON_LEFT, user_input.MOD_SHIFT_CONTROL)) _ROTATE_CAMERA = user_input.Exclusive(user_input.MOUSE_BUTTON_LEFT) _CENTER_CAMERA = user_input.DoubleClick(user_input.MOUSE_BUTTON_RIGHT) _SELECT_OBJECT = user_input.DoubleClick(user_input.MOUSE_BUTTON_LEFT) _TRACK_OBJECT = user_input.DoubleClick( (user_input.MOUSE_BUTTON_RIGHT, user_input.MOD_CONTROL)) _FREE_LOOK = user_input.KEY_ESCAPE _NEXT_CAMERA = user_input.KEY_RIGHT_BRACKET _PREVIOUS_CAMERA = user_input.KEY_LEFT_BRACKET _ZOOM_TO_SCENE = (user_input.KEY_A, user_input.MOD_CONTROL) _DOUBLE_BUFFERING = user_input.KEY_F5 _PREV_RENDERING_MODE = (user_input.KEY_F6, user_input.MOD_SHIFT) _NEXT_RENDERING_MODE = user_input.KEY_F6 _PREV_LABELING_MODE = (user_input.KEY_F7, user_input.MOD_SHIFT) _NEXT_LABELING_MODE = user_input.KEY_F7 _PRINT_CAMERA = user_input.KEY_F11 _VISUALIZATION_FLAGS = user_input.Range([ ord(functions.mjVISSTRING[i][2]) if functions.mjVISSTRING[i][2] else 0 for i in range(0, mujoco.mjtVisFlag.mjNVISFLAG) ]) _GEOM_GROUPS = user_input.Range( [i + ord('0') for i in range(min(_NUM_GROUP_KEYS, mujoco.mjNGROUP))]) _SITE_GROUPS = user_input.Range([ (i + ord('0'), user_input.MOD_SHIFT) for i in range(min(_NUM_GROUP_KEYS, mujoco.mjNGROUP)) ]) _RENDERING_FLAGS = user_input.Range([ ord(functions.mjRNDSTRING[i][2]) if functions.mjRNDSTRING[i][2] else 0 for i in range(0, mujoco.mjtRndFlag.mjNRNDFLAG) ]) _CAMERA_MOVEMENT_ACTIONS = [ mujoco.mjtMouse.mjMOUSE_MOVE_V, mujoco.mjtMouse.mjMOUSE_ROTATE_H ] # Translates mouse wheel rotations to zoom speed. _SCROLL_SPEED_FACTOR = 0.05 # Distance, in meters, at which to focus on the clicked object. _LOOK_AT_DISTANCE = 1.5 # Zoom factor used when zooming in on the entire scene. _FULL_SCENE_ZOOM_FACTOR = 1.5 class Viewer: """Viewport displaying the contents of a physics world.""" def __init__(self, viewport, mouse, keyboard, camera_settings=None, zoom_factor=_FULL_SCENE_ZOOM_FACTOR, scene_callback=None): """Instance initializer. Args: viewport: Render viewport, instance of renderer.Viewport. mouse: A mouse device. keyboard: A keyboard device. camera_settings: Properties of the scene MjvCamera. zoom_factor: Initial scale factor for zooming into the scene. scene_callback: Scene callback. This is a callable of the form: `my_callable(MjModel, MjData, MjvScene)` that gets applied to every rendered scene. """ self._viewport = viewport self._mouse = mouse self._null_perturbation = renderer.NullPerturbation() self._render_settings = renderer.RenderSettings() self._input_map = user_input.InputMap(mouse, keyboard) self._camera = None self._camera_settings = camera_settings self._renderer = None self._manipulator = None self._free_camera = None self._camera_select = None self._zoom_factor = zoom_factor self._scene_callback = scene_callback def __del__(self): del self._camera del self._renderer del self._manipulator del self._free_camera del self._camera_select def initialize(self, physics, renderer_instance, touchpad): """Initialize the viewer. Args: physics: Physics instance. renderer_instance: A renderer.Base instance. touchpad: A boolean, use input dedicated to touchpad. """ self._camera = renderer.SceneCamera( physics.model, physics.data, self._render_settings, settings=self._camera_settings, zoom_factor=self._zoom_factor, scene_callback=self._scene_callback) self._manipulator = ManipulationController( self._viewport, self._camera, self._mouse) self._free_camera = FreeCameraController( self._viewport, self._camera, self._mouse, self._manipulator) self._camera_select = CameraSelector( physics.model, self._camera, self._free_camera) self._renderer = renderer_instance self._input_map.clear_bindings() if touchpad: self._input_map.bind( self._manipulator.set_move_vertical_mode, _MOVE_OBJECT_VERTICAL_TOUCHPAD) self._input_map.bind( self._manipulator.set_move_horizontal_mode, _MOVE_OBJECT_HORIZONTAL_TOUCHPAD) self._input_map.bind( self._manipulator.set_rotate_mode, _ROTATE_OBJECT_TOUCHPAD) self._input_map.bind( self._free_camera.set_pan_vertical_mode, _PAN_CAMERA_VERTICAL_TOUCHPAD) self._input_map.bind( self._free_camera.set_pan_horizontal_mode, _PAN_CAMERA_HORIZONTAL_TOUCHPAD) else: self._input_map.bind( self._manipulator.set_move_vertical_mode, _MOVE_OBJECT_VERTICAL_MOUSE) self._input_map.bind( self._manipulator.set_move_horizontal_mode, _MOVE_OBJECT_HORIZONTAL_MOUSE) self._input_map.bind( self._manipulator.set_rotate_mode, _ROTATE_OBJECT_MOUSE) self._input_map.bind( self._free_camera.set_pan_vertical_mode, _PAN_CAMERA_VERTICAL_MOUSE) self._input_map.bind( self._free_camera.set_pan_horizontal_mode, _PAN_CAMERA_HORIZONTAL_MOUSE) self._input_map.bind(self._print_camera_transform, _PRINT_CAMERA) self._input_map.bind( self._render_settings.select_prev_rendering_mode, _PREV_RENDERING_MODE) self._input_map.bind( self._render_settings.select_next_rendering_mode, _NEXT_RENDERING_MODE) self._input_map.bind( self._render_settings.select_prev_labeling_mode, _PREV_LABELING_MODE) self._input_map.bind( self._render_settings.select_next_labeling_mode, _NEXT_LABELING_MODE) self._input_map.bind( self._render_settings.select_prev_labeling_mode, _PREV_LABELING_MODE) self._input_map.bind( self._render_settings.toggle_stereo_buffering, _DOUBLE_BUFFERING) self._input_map.bind( self._render_settings.toggle_visualization_flag, _VISUALIZATION_FLAGS) self._input_map.bind( self._render_settings.toggle_site_group, _SITE_GROUPS) self._input_map.bind( self._render_settings.toggle_geom_group, _GEOM_GROUPS) self._input_map.bind( self._render_settings.toggle_rendering_flag, _RENDERING_FLAGS) self._input_map.bind(self._camera.zoom_to_scene, _ZOOM_TO_SCENE) self._input_map.bind(self._camera_select.select_next, _NEXT_CAMERA) self._input_map.bind(self._camera_select.select_previous, _PREVIOUS_CAMERA) self._input_map.bind_z_axis(self._free_camera.zoom) self._input_map.bind_plane(self._free_camera.on_move) self._input_map.bind(self._free_camera.set_rotate_mode, _ROTATE_CAMERA) self._input_map.bind(self._free_camera.center, _CENTER_CAMERA) self._input_map.bind(self._free_camera.track, _TRACK_OBJECT) self._input_map.bind(self._camera_select.escape, _FREE_LOOK) self._input_map.bind(self._manipulator.select, _SELECT_OBJECT) self._input_map.bind_plane(self._manipulator.on_move) def deinitialize(self): """Deinitializes the viewer instance.""" self._input_map.clear_bindings() self._camera_settings = self._camera.settings if self._camera else None del self._camera del self._renderer del self._manipulator del self._free_camera del self._camera_select self._camera = None self._renderer = None self._manipulator = None self._free_camera = None self._camera_select = None def render(self): """Renders the visualized scene.""" if self._camera and self._renderer: # Can be None during env reload. scene = self._camera.render(self.perturbation) self._render_settings.apply_settings(scene) self._renderer.render(self._viewport, scene) def zoom_to_scene(self): """Utility method that set the camera to embrace the entire scene.""" if self._camera: self._camera.zoom_to_scene() def _print_camera_transform(self): if self._camera: rotation_mtx, position = self._camera.transform right, up, _ = rotation_mtx print('<camera pos="%.3f %.3f %.3f" ' 'xyaxes="%.3f %.3f %.3f %.3f %.3f %.3f"/>' % ( position[0], position[1], position[2], right[0], right[1], right[2], up[0], up[1], up[2])) @property def perturbation(self): """Returns an active renderer.Perturbation object.""" if self._manipulator and self._manipulator.perturbation: return self._manipulator.perturbation else: return self._null_perturbation @property def camera(self): """Returns an active renderer.SceneCamera instance.""" return self._camera @property def render_settings(self): """Returns renderer.RenderSettings used by this viewer.""" return self._render_settings class CameraSelector: """Binds camera behavior to user input.""" def __init__(self, model, camera, free_camera, **unused): """Instance initializer. Args: model: Instance of MjModel. camera: Instance of SceneCamera. free_camera: Instance of FreeCameraController. **unused: Other arguments, not used by this class. """ del unused # Unused. self._model = model self._camera = camera self._free_ctrl = free_camera self._camera_idx = -1 self._active_ctrl = self._free_ctrl def select_previous(self): """Cycles to the previous scene camera.""" self._camera_idx -= 1 if not self._model.ncam or self._camera_idx < -1: self._camera_idx = self._model.ncam - 1 self._commit_selection() def select_next(self): """Cycles to the next scene camera.""" self._camera_idx += 1 if not self._model.ncam or self._camera_idx >= self._model.ncam: self._camera_idx = -1 self._commit_selection() def escape(self) -> None: """Unconditionally switches to the free camera.""" self._camera_idx = -1 self._commit_selection() def _commit_selection(self): """Selects a controller that should go with the selected camera.""" if self._camera_idx < 0: self._activate(self._free_ctrl) else: self._camera.set_fixed_mode(self._camera_idx) self._activate(None) def _activate(self, controller): """Activates a sub-controller.""" if controller == self._active_ctrl: return if self._active_ctrl is not None: self._active_ctrl.deactivate() self._active_ctrl = controller if self._active_ctrl is not None: self._active_ctrl.activate() class FreeCameraController: """Implements the free camera behavior.""" def __init__(self, viewport, camera, pointer, selection_service, **unused): """Instance initializer. Args: viewport: Instance of mujoco_viewer.Viewport. camera: Instance of mujoco_viewer.SceneCamera. pointer: A pointer that moves around the screen and is used to point at bodies. Implements a single attribute - 'position' - that returns a 2-component vector of pointer's screen space position. selection_service: An instance of a class implementing a 'selected_body_id' property. **unused: Other optional parameters not used by this class. """ del unused # Unused. self._viewport = viewport self._camera = camera self._pointer = pointer self._selection_service = selection_service self._active = True self._tracked_body_idx = -1 self._action = util.AtomicAction() def activate(self): """Activates the controller.""" self._active = True self._update_camera_mode() def deactivate(self): """Deactivates the controller.""" self._active = False self._action = util.AtomicAction() def set_pan_vertical_mode(self, enable): """Starts/ends the camera panning action along the vertical plane. Args: enable: A boolean flag, True to start the action, False to end it. """ if self._active: if enable: self._action.begin(mujoco.mjtMouse.mjMOUSE_MOVE_V) else: self._action.end(mujoco.mjtMouse.mjMOUSE_MOVE_V) def set_pan_horizontal_mode(self, enable): """Starts/ends the camera panning action along the horizontal plane. Args: enable: A boolean flag, True to start the action, False to end it. """ if self._active: if enable: self._action.begin(mujoco.mjtMouse.mjMOUSE_MOVE_H) else: self._action.end(mujoco.mjtMouse.mjMOUSE_MOVE_H) def set_rotate_mode(self, enable): """Starts/ends the camera rotation action. Args: enable: A boolean flag, True to start the action, False to end it. """ if self._active: if enable: self._action.begin(mujoco.mjtMouse.mjMOUSE_ROTATE_H) else: self._action.end(mujoco.mjtMouse.mjMOUSE_ROTATE_H) def center(self): """Focuses camera on the object the pointer is currently pointing at.""" if self._active: body_id, world_pos = self._camera.raycast(self._viewport, self._pointer.position) if body_id >= 0: self._camera.look_at(world_pos, _LOOK_AT_DISTANCE) def on_move(self, position, translation): """Translates mouse moves onto camera movements.""" del position if self._action.in_progress: viewport_offset = self._viewport.screen_to_viewport(translation) self._camera.move(self._action.watermark, viewport_offset) def zoom(self, zoom_factor): """Zooms the camera in/out. Args: zoom_factor: A floating point value, by how much to zoom the camera. Positive values zoom the camera in, negative values zoom it out. """ if self._active: offset = [0, _SCROLL_SPEED_FACTOR * zoom_factor * -1.] self._camera.move(mujoco.mjtMouse.mjMOUSE_ZOOM, offset) def track(self): """Makes the camera track the currently selected object. The selection is managed by the selection service. """ if self._active and self._tracked_body_idx < 0: self._tracked_body_idx = self._selection_service.selected_body_id self._update_camera_mode() def free_look(self): """Switches the camera to a free-look mode.""" if self._active: self._tracked_body_idx = -1 self._update_camera_mode() def _update_camera_mode(self): """Sets the camera into a tracking or a free-look mode.""" if self._tracked_body_idx >= 0: self._camera.set_tracking_mode(self._tracked_body_idx) else: self._camera.set_freelook_mode() class ManipulationController: """Binds control over scene objects to user input.""" def __init__(self, viewport, camera, pointer, **unused): """Instance initializer. Args: viewport: Instance of mujoco_viewer.Viewport. camera: Instance of mujoco_viewer.SceneCamera. pointer: A pointer that moves around the screen and is used to point at bodies. Implements a single attribute - 'position' - that returns a 2-component vector of pointer's screen space position. **unused: Other arguments, unused by this class. """ del unused # Unused. self._viewport = viewport self._camera = camera self._pointer = pointer self._action = util.AtomicAction(self._update_action) self._perturb = None def select(self): """Translates mouse double-clicks to object selection action.""" body_id, _ = self._camera.raycast(self._viewport, self._pointer.position) if body_id >= 0: self._perturb = self._camera.new_perturbation(body_id) else: self._perturb = None def set_move_vertical_mode(self, enable): """Begins/ends an object translation action along the vertical plane. Args: enable: A boolean flag, True begins the action, False ends it. """ if enable: self._action.begin(mujoco.mjtMouse.mjMOUSE_MOVE_V) else: self._action.end(mujoco.mjtMouse.mjMOUSE_MOVE_V) def set_move_horizontal_mode(self, enable): """Begins/ends an object translation action along the horizontal plane. Args: enable: A boolean flag, True begins the action, False ends it. """ if enable: self._action.begin(mujoco.mjtMouse.mjMOUSE_MOVE_H) else: self._action.end(mujoco.mjtMouse.mjMOUSE_MOVE_H) def set_rotate_mode(self, enable): """Begins/ends an object rotation action. Args: enable: A boolean flag, True begins the action, False ends it. """ if enable: self._action.begin(mujoco.mjtMouse.mjMOUSE_ROTATE_H) else: self._action.end(mujoco.mjtMouse.mjMOUSE_ROTATE_H) def _update_action(self, action): if self._perturb is not None: if action is not None: _, grab_pos = self._camera.raycast(self._viewport, self._pointer.position) self._perturb.start_move(action, grab_pos) else: self._perturb.end_move() def on_move(self, position, translation): """Translates mouse moves to selected object movements.""" del position if self._perturb is not None and self._action.in_progress: viewport_offset = self._viewport.screen_to_viewport(translation) self._perturb.tick_move(viewport_offset) @property def perturbation(self): """Returns the Perturbation object that represents the manipulated body.""" return self._perturb @property def selected_body_id(self): """Returns the id of the selected body, or -1 if none is selected.""" return self._perturb.body_id if self._perturb is not None else -1
dm_control-main
dm_control/viewer/viewer.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 the user_input module.""" from absl.testing import absltest from dm_control.viewer import user_input import mock class InputMapTests(absltest.TestCase): def setUp(self): super().setUp() self.mouse = mock.MagicMock() self.keyboard = mock.MagicMock() self.input_map = user_input.InputMap(self.mouse, self.keyboard) self.callback = mock.MagicMock() def test_clearing_bindings(self): self.input_map._active_exclusive = 1 self.input_map._action_callbacks = {1: 2} self.input_map._double_click_callbacks = {3: 4} self.input_map._plane_callback = [5] self.input_map._z_axis_callback = [6] self.input_map.clear_bindings() self.assertEmpty(self.input_map._action_callbacks) self.assertEmpty(self.input_map._double_click_callbacks) self.assertEmpty(self.input_map._plane_callback) self.assertEmpty(self.input_map._z_axis_callback) self.assertEqual( user_input._NO_EXCLUSIVE_KEY, self.input_map._active_exclusive) def test_binding(self): self.input_map.bind(self.callback, user_input.KEY_UP) expected_dict = { (user_input.KEY_UP, user_input.MOD_NONE): (False, self.callback)} self.assertDictEqual(expected_dict, self.input_map._action_callbacks) def test_binding_exclusive(self): self.input_map.bind(self.callback, user_input.Exclusive(user_input.KEY_UP)) expected_dict = { (user_input.KEY_UP, user_input.MOD_NONE): (True, self.callback)} self.assertDictEqual(expected_dict, self.input_map._action_callbacks) def test_binding_and_invoking_ranges_of_actions(self): self.input_map.bind(self.callback, user_input.Range( [user_input.KEY_UP, (user_input.KEY_UP, user_input.MOD_ALT)])) self.input_map._handle_key( user_input.KEY_UP, user_input.PRESS, user_input.MOD_NONE) self.callback.assert_called_once_with(0) self.callback.reset_mock() self.input_map._handle_key( user_input.KEY_UP, user_input.PRESS, user_input.MOD_ALT) self.callback.assert_called_once_with(1) def test_binding_planar_action(self): self.input_map.bind_plane(self.callback) self.assertLen(self.input_map._plane_callback, 1) self.assertEqual(self.callback, self.input_map._plane_callback[0]) def test_binding_z_axis_action(self): self.input_map.bind_z_axis(self.callback) self.assertLen(self.input_map._z_axis_callback, 1) self.assertEqual(self.callback, self.input_map._z_axis_callback[0]) def test_invoking_regular_action_in_response_to_click(self): self.input_map._action_callbacks = {(1, 2): (False, self.callback)} self.input_map._handle_key(1, user_input.PRESS, 2) self.callback.assert_called_once() self.callback.reset_mock() self.input_map._handle_key(1, user_input.RELEASE, 2) self.assertEqual(0, self.callback.call_count) def test_invoking_exclusive_action_in_response_to_click(self): self.input_map._action_callbacks = {(1, 2): (True, self.callback)} self.input_map._handle_key(1, user_input.PRESS, 2) self.callback.assert_called_once_with(True) self.callback.reset_mock() self.input_map._handle_key(1, user_input.RELEASE, 2) self.callback.assert_called_once_with(False) def test_exclusive_action_blocks_other_actions_until_its_finished(self): self.input_map._action_callbacks = { (1, 2): (True, self.callback), (3, 4): (False, self.callback)} self.input_map._handle_key(1, user_input.PRESS, 2) self.callback.assert_called_once_with(True) self.callback.reset_mock() # Attempting to start other actions (PRESS) or end them (RELEASE) # amounts to nothing. self.input_map._handle_key(3, user_input.PRESS, 4) self.assertEqual(0, self.callback.call_count) self.input_map._handle_key(3, user_input.RELEASE, 4) self.assertEqual(0, self.callback.call_count) # Even attempting to start the same action for the 2nd time fails. self.input_map._handle_key(1, user_input.PRESS, 2) self.assertEqual(0, self.callback.call_count) # Only finishing the action frees up the resources. self.input_map._handle_key(1, user_input.RELEASE, 2) self.callback.assert_called_once_with(False) self.callback.reset_mock() # Now we can start a new action. self.input_map._handle_key(3, user_input.PRESS, 4) self.callback.assert_called_once() def test_modifiers_required_only_for_exclusive_action_start(self): activation_modifiers = 2 no_modifiers = 0 self.input_map._action_callbacks = { (1, activation_modifiers): (True, self.callback)} self.input_map._handle_key(1, user_input.PRESS, activation_modifiers) self.callback.assert_called_once_with(True) self.callback.reset_mock() self.input_map._handle_key(1, user_input.RELEASE, no_modifiers) self.callback.assert_called_once_with(False) def test_invoking_regular_action_in_response_to_double_click(self): self.input_map._double_click_callbacks = {(1, 2): self.callback} self.input_map._handle_double_click(1, 2) self.callback.assert_called_once() def test_exclusive_actions_dont_respond_to_double_clicks(self): self.input_map._action_callbacks = {(1, 2): (True, self.callback)} self.input_map._handle_double_click(1, 2) self.assertEqual(0, self.callback.call_count) def test_mouse_move(self): position = [1, 2] translation = [3, 4] self.input_map._plane_callback = [self.callback] self.input_map._handle_mouse_move(position, translation) self.callback.assert_called_once_with(position, translation) def test_mouse_scroll(self): value = 5 self.input_map._z_axis_callback = [self.callback] self.input_map._handle_mouse_scroll(value) self.callback.assert_called_once_with(value) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/viewer/user_input_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. # ============================================================================ """Utility classes.""" import collections import contextlib import itertools import sys import time import traceback from absl import logging # Lower bound of the time multiplier set through TimeMultiplier class. _MIN_TIME_MULTIPLIER = 1./32. # Upper bound of the time multiplier set through TimeMultiplier class. _MAX_TIME_MULTIPLIER = 1. def is_scalar(value): """Checks if the supplied value can be converted to a scalar.""" try: float(value) except (TypeError, ValueError): return False else: return True def to_iterable(item): """Converts an item or iterable into an iterable.""" if isinstance(item, str): return [item] elif isinstance(item, collections.abc.Iterable): return item else: return [item] class QuietSet: """A set-like container that quietly processes removals of missing keys.""" def __init__(self): self._items = set() def __iadd__(self, items): """Adds `items`, avoiding duplicates. Args: items: An iterable of items to add, or a single item to add. Returns: This instance of `QuietSet`. """ self._items.update(to_iterable(items)) self._items.discard(None) return self def __isub__(self, items): """Detaches `items`. Args: items: An iterable of items to detach, or a single item to detach. Returns: This instance of `QuietSet`. """ for item in to_iterable(items): self._items.discard(item) return self def __len__(self): return len(self._items) def __iter__(self): return iter(self._items) def interleave(a, b): """Interleaves the contents of two iterables.""" return itertools.chain.from_iterable(zip(a, b)) class TimeMultiplier: """Controls the relative speed of the simulation compared to realtime.""" def __init__(self, initial_time_multiplier): """Instance initializer. Args: initial_time_multiplier: A float scalar specifying the initial speed of the simulation with 1.0 corresponding to realtime. """ self.set(initial_time_multiplier) def get(self): """Returns the current time factor value.""" return self._real_time_multiplier def set(self, value): """Modifies the time factor. Args: value: A float scalar, new value of the time factor. """ self._real_time_multiplier = max( _MIN_TIME_MULTIPLIER, min(_MAX_TIME_MULTIPLIER, value)) def __str__(self): """Returns a formatted string containing the time factor.""" if self._real_time_multiplier >= 1.0: time_factor = '%d' % self._real_time_multiplier else: time_factor = '1/%d' % (1.0 // self._real_time_multiplier) return time_factor def increase(self): """Doubles the current time factor value.""" self.set(self._real_time_multiplier * 2.) def decrease(self): """Halves the current time factor value.""" self.set(self._real_time_multiplier / 2.) class Integrator: """Integrates a value and averages it for the specified period of time.""" def __init__(self, refresh_rate=.5): """Instance initializer. Args: refresh_rate: How often, in seconds, is the integrated value averaged. """ self._value = 0 self._value_acc = 0 self._num_samples = 0 self._sampling_timestamp = time.time() self._refresh_rate = refresh_rate @property def value(self): """Returns the averaged value.""" return self._value @value.setter def value(self, val): """Integrates the new value.""" self._value_acc += val self._num_samples += 1 time_elapsed = time.time() - self._sampling_timestamp if time_elapsed >= self._refresh_rate: self._value = self._value_acc / self._num_samples self._value_acc = 0 self._num_samples = 0 self._sampling_timestamp = time.time() class AtomicAction: """An action that cannot be interrupted.""" def __init__(self, state_change_callback=None): """Instance initializer. Args: state_change_callback: Callable invoked when action changes its state. """ self._state_change_callback = state_change_callback self._watermark = None def begin(self, watermark): """Begins the action, signing it with the specified watermark.""" if self._watermark is None: self._watermark = watermark if self._state_change_callback is not None: self._state_change_callback(watermark) def end(self, watermark): """Ends a started action, provided the watermarks match.""" if self._watermark == watermark: self._watermark = None if self._state_change_callback is not None: self._state_change_callback(None) @property def in_progress(self): """Returns a boolean value to indicate if the being method was called.""" return self._watermark is not None @property def watermark(self): """Returns the watermark passed to begin() method call, or None. None will be returned if the action is not in progress. """ return self._watermark class ObservableFlag(QuietSet): """Observable boolean flag. The QuietState provides necessary functionality for managing listeners. A listener is a callable that takes one boolean parameter. """ def __init__(self, initial_value): """Instance initializer. Args: initial_value: A boolean value with the initial state of the flag. """ self._value = initial_value super().__init__() def toggle(self): """Toggles the value True/False.""" self._value = not self._value for listener in self._items: listener(self._value) def __iadd__(self, value): """Add new listeners and update them about the state.""" listeners = to_iterable(value) super().__iadd__(listeners) for listener in listeners: listener(self._value) return self @property def value(self): """Value of the flag.""" return self._value @value.setter def value(self, val): if self._value != val: for listener in self._items: listener(self._value) self._value = val class Timer: """Measures time elapsed between two ticks.""" def __init__(self): """Instance initializer.""" self._previous_time = time.time() self._measured_time = 0. def tick(self): """Updates the timer. Returns: Time elapsed since the last call to this method. """ curr_time = time.time() self._measured_time = curr_time - self._previous_time self._previous_time = curr_time return self._measured_time @contextlib.contextmanager def measure_time(self): start_time = time.time() yield self._measured_time = time.time() - start_time @property def measured_time(self): return self._measured_time class ErrorLogger: """A context manager that catches and logs all errors.""" def __init__(self, listeners): """Instance initializer. Args: listeners: An iterable of callables, listeners to inform when an error is caught. Each callable should accept a single string argument. """ self._error_found = False self._listeners = listeners def __enter__(self, *args): self._error_found = False def __exit__(self, exception_type, exception_value, tb): if exception_type: self._error_found = True error_message = ('dm_control viewer intercepted an environment error.\n' 'Original message: {}'.format(exception_value)) logging.error(error_message) sys.stderr.write(error_message + '\nTraceback:\n') traceback.print_tb(tb) for listener in self._listeners: listener('{}'.format(exception_value)) return True @property def errors_found(self): """Returns True if any errors were caught.""" return self._error_found class NullErrorLogger: """A context manager that replaces an ErrorLogger. This error logger will pass all thrown errors through. """ def __enter__(self, *args): pass def __exit__(self, error_type, value, tb): pass @property def errors_found(self): """Returns True if any errors were caught.""" return False
dm_control-main
dm_control/viewer/util.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. # ============================================================================ """Renderer module.""" import abc import contextlib import subprocess import sys from dm_control.mujoco import wrapper from dm_control.viewer import util import mujoco import numpy as np # Fixed camera -1 is the free (unfixed) camera, and each fixed camera has # a positive index in range (0, self._model.ncam). _FREE_CAMERA_INDEX = -1 # Index used to distinguish when a camera isn't tracking any particular body. _NO_BODY_TRACKED_INDEX = -1 # Index used to distinguish a non-existing or an invalid body. _INVALID_BODY_INDEX = -1 # Zoom factor used when zooming in on the entire scene. _FULL_SCENE_ZOOM_FACTOR = 1.5 # Default values for `MjvScene.flags`. These are the same as the defaults set by # `mjv_defaultScene`, except that we disable `mjRND_HAZE`. _DEFAULT_RENDER_FLAGS = np.zeros(mujoco.mjtRndFlag.mjNRNDFLAG, dtype=np.ubyte) _DEFAULT_RENDER_FLAGS[mujoco.mjtRndFlag.mjRND_SHADOW.value] = 1 _DEFAULT_RENDER_FLAGS[mujoco.mjtRndFlag.mjRND_REFLECTION.value] = 1 _DEFAULT_RENDER_FLAGS[mujoco.mjtRndFlag.mjRND_SKYBOX.value] = 1 _DEFAULT_RENDER_FLAGS[mujoco.mjtRndFlag.mjRND_CULL_FACE.value] = 1 # Font scale values. _DEFAULT_FONT_SCALE = mujoco.mjtFontScale.mjFONTSCALE_100 _HIDPI_FONT_SCALE = mujoco.mjtFontScale.mjFONTSCALE_200 def _has_high_dpi() -> bool: """Returns True if the display is a high DPI display.""" if sys.platform == 'darwin': # On macOS, we can use the system_profiler command to determine if the # display is retina. return subprocess.call( 'system_profiler SPDisplaysDataType | grep -i "retina"', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) == 0 # TODO(zakka): Figure out how to detect high DPI displays on Linux. return False class BaseRenderer(metaclass=abc.ABCMeta): """A base class for component-based Mujoco Renderers implementations. Attributes: components: A set of RendererComponent the renderer will render in addition to rendering the physics scene. Being a QuietSet instance, it supports adding and removing of components using += and -= operators. screen_capture_components: Components that perform screen capture and need a guarantee to be called when all other elements have been rendered. """ def __init__(self): """Instance initializer.""" self.components = util.QuietSet() self.screen_capture_components = util.QuietSet() def _render_components(self, context, viewport): """Renders the components. Args: context: MjrContext instance. viewport: Viewport instance. """ for component in self.components: component.render(context, viewport) for component in self.screen_capture_components: component.render(context, viewport) class Component(metaclass=abc.ABCMeta): """Components are a way to introduce extra rendering content. They are invoked after the main rendering pass, allowing to draw extra images into the render buffer, such as overlays. """ @abc.abstractmethod def render(self, context, viewport): """Renders the component. Args: context: MjrContext instance. viewport: Viewport instance. """ pass class NullRenderer: """A stub off-screen renderer used when no other renderer is available.""" def __init__(self): """Instance initializer.""" self._black = np.zeros((1, 1, 3), dtype=np.uint8) def release(self): pass @property def pixels(self): """Returns a black pixel map.""" return self._black class OffScreenRenderer(BaseRenderer): """A Mujoco renderer that renders to an off-screen surface.""" def __init__(self, model, surface): """Instance initializer. Args: model: instance of MjModel. surface: instance of dm_control.render.BaseContext. """ super().__init__() self._surface = surface self._surface.increment_refcount() self._model = model self._mujoco_context = None self._prev_viewport = np.ones(2) self._rgb_buffer = np.empty((1, 1, 3), dtype=np.uint8) self._pixels = np.zeros((1, 1, 3), dtype=np.uint8) def render(self, viewport, scene): """Renders the scene to the specified viewport. Args: viewport: Instance of Viewport. scene: Instance of MjvScene. Returns: A 3-dimensional array of shape (viewport.width, viewport.height, 3), with the contents of the front buffer. """ if not np.array_equal(self._prev_viewport, viewport.dimensions): self._prev_viewport = viewport.dimensions if self._mujoco_context: self._mujoco_context.free() self._mujoco_context = None if not self._mujoco_context: # Ensure that MuJoCo's offscreen framebuffer is large enough to # accommodate the viewport. new_offwidth = max(self._model.vis.global_.offwidth, viewport.width) new_offheight = max(self._model.vis.global_.offheight, viewport.height) self._model.vis.global_.offwidth = new_offwidth self._model.vis.global_.offheight = new_offheight font_scale = _HIDPI_FONT_SCALE if _has_high_dpi() else _DEFAULT_FONT_SCALE self._mujoco_context = wrapper.MjrContext( model=self._model, gl_context=self._surface, font_scale=font_scale) self._rgb_buffer = np.empty( (viewport.height, viewport.width, 3), dtype=np.uint8) with self._surface.make_current() as ctx: ctx.call(self._render_on_gl_thread, viewport, scene) self._pixels = np.flipud(self._rgb_buffer) def _render_on_gl_thread(self, viewport, scene): mujoco.mjr_setBuffer(mujoco.mjtFramebuffer.mjFB_OFFSCREEN, self._mujoco_context.ptr) mujoco.mjr_render(viewport.mujoco_rect, scene.ptr, self._mujoco_context.ptr) self._render_components(self._mujoco_context, viewport) mujoco.mjr_readPixels(self._rgb_buffer, None, viewport.mujoco_rect, self._mujoco_context.ptr) def release(self): """Releases the render context and related resources.""" if self._mujoco_context: self._mujoco_context.free() self._mujoco_context = None if self._surface: self._surface.decrement_refcount() self._surface.free() self._surface = None @property def pixels(self): """Returns the rendered image.""" return self._pixels class Perturbation: """A proxy that allows to move a scene object.""" def __init__(self, body_id, model, data, scene): """Instance initializer. Args: body_id: A positive integer, ID of the body to manipulate. model: MjModel instance. data: MjData instance. scene: MjvScene instance. """ self._body_id = body_id self._model = model self._data = data self._scene = scene self._action = mujoco.mjtMouse.mjMOUSE_NONE self._perturb = wrapper.MjvPerturb() self._perturb.select = self._body_id self._perturb.active = 0 mujoco.mjv_initPerturb(self._model.ptr, self._data.ptr, self._scene.ptr, self._perturb.ptr) def start_move(self, action, grab_pos): """Starts a movement action.""" if action is None or grab_pos is None: return mujoco.mjv_initPerturb(self._model.ptr, self._data.ptr, self._scene.ptr, self._perturb.ptr) self._action = action move_actions = np.array( [mujoco.mjtMouse.mjMOUSE_MOVE_V, mujoco.mjtMouse.mjMOUSE_MOVE_H]) if any(move_actions == action): self._perturb.active = mujoco.mjtPertBit.mjPERT_TRANSLATE else: self._perturb.active = mujoco.mjtPertBit.mjPERT_ROTATE body_pos = self._data.xpos[self._body_id] body_mat = self._data.xmat[self._body_id].reshape(3, 3) grab_local_pos = body_mat.T.dot(grab_pos - body_pos) self._perturb.localpos[:] = grab_local_pos def tick_move(self, viewport_offset): """Transforms object's location/rotation by the specified amount.""" if self._action: mujoco.mjv_movePerturb(self._model.ptr, self._data.ptr, self._action, viewport_offset[0], viewport_offset[1], self._scene.ptr, self._perturb.ptr) def end_move(self): """Ends a movement operation.""" self._action = mujoco.mjtMouse.mjMOUSE_NONE self._perturb.active = 0 @contextlib.contextmanager def apply(self, paused): """Applies the modifications introduced by performing the move operation.""" mujoco.mjv_applyPerturbPose(self._model.ptr, self._data.ptr, self._perturb.ptr, int(paused)) if not paused: mujoco.mjv_applyPerturbForce(self._model.ptr, self._data.ptr, self._perturb.ptr) yield self._data.xfrc_applied[self._perturb.select] = 0 @property def ptr(self): """Returns the underlying Mujoco Perturbation object.""" return self._perturb.ptr @property def body_id(self): """A positive integer, ID of the manipulated body.""" return self._body_id class NullPerturbation: """An empty perturbation. A null-object pattern, used to avoid cumbersome if clauses. """ @contextlib.contextmanager def apply(self, paused): """Activates/deactivates the null context.""" del paused yield @property def ptr(self): """Returns None, because this class represents an empty perturbation.""" return None class RenderSettings: """Renderer settings.""" def __init__(self): self._visualization_options = wrapper.MjvOption() self._stereo_mode = mujoco.mjtStereo.mjSTEREO_NONE self._render_flags = _DEFAULT_RENDER_FLAGS @property def visualization(self): """Returns scene visualization options.""" return self._visualization_options @property def render_flags(self): """Returns the render flags.""" return self._render_flags @property def visualization_flags(self): """Returns scene visualization flags.""" return self._visualization_options.flags @property def geom_groups(self): """Returns geom groups visibility flags.""" return self._visualization_options.geomgroup @property def site_groups(self): """Returns site groups visibility flags.""" return self._visualization_options.sitegroup def apply_settings(self, scene): """Applies settings to the specified scene. Args: scene: Instance of MjvScene. """ scene.stereo = self._stereo_mode scene.flags[:] = self._render_flags[:] def toggle_rendering_flag(self, flag_index): """Toggles the specified rendering flag.""" self._render_flags[flag_index] = not self._render_flags[flag_index] def toggle_visualization_flag(self, flag_index): """Toggles the specified visualization flag.""" self._visualization_options.flags[flag_index] = ( not self._visualization_options.flags[flag_index]) def toggle_geom_group(self, group_index): """Toggles the specified geom group visible or not.""" self._visualization_options.geomgroup[group_index] = ( not self._visualization_options.geomgroup[group_index]) def toggle_site_group(self, group_index): """Toggles the specified site group visible or not.""" self._visualization_options.sitegroup[group_index] = ( not self._visualization_options.sitegroup[group_index]) def toggle_stereo_buffering(self): """Toggles the double buffering mode on/off.""" if self._stereo_mode == mujoco.mjtStereo.mjSTEREO_NONE: self._stereo_mode = mujoco.mjtStereo.mjSTEREO_QUADBUFFERED else: self._stereo_mode = mujoco.mjtStereo.mjSTEREO_NONE def select_next_rendering_mode(self): """Cycles to the next rendering mode.""" self._visualization_options.frame = ( (self._visualization_options.frame + 1) % mujoco.mjtFrame.mjNFRAME) def select_prev_rendering_mode(self): """Cycles to the previous rendering mode.""" self._visualization_options.frame = ( (self._visualization_options.frame - 1) % mujoco.mjtFrame.mjNFRAME) def select_next_labeling_mode(self): """Cycles to the next scene object labeling mode.""" self._visualization_options.label = ( (self._visualization_options.label + 1) % mujoco.mjtLabel.mjNLABEL) def select_prev_labeling_mode(self): """Cycles to the previous scene object labeling mode.""" self._visualization_options.label = ( (self._visualization_options.label - 1) % mujoco.mjtLabel.mjNLABEL) class SceneCamera: """A camera used to navigate around and render the scene.""" def __init__(self, model, data, options, settings=None, zoom_factor=_FULL_SCENE_ZOOM_FACTOR, scene_callback=None): """Instance initializer. Args: model: MjModel instance. data: MjData instance. options: RenderSettings instance. settings: Optional, internal camera settings obtained from another SceneCamera instance using 'settings' property. zoom_factor: The initial zoom factor for zooming into the scene. scene_callback: Scene callback. This is a callable of the form: `my_callable(MjModel, MjData, MjvScene)` that gets applied to every rendered scene. """ # Design notes: # We need to recreate the camera for each new model, because each model # defines different fixed cameras and objects to track, and therefore # severely the parameters of this class. self._scene = wrapper.MjvScene(model) self._data = data self._model = model self._options = options self._camera = wrapper.MjvCamera() self.set_freelook_mode() self._zoom_factor = zoom_factor self._scene_callback = scene_callback if settings is not None: self._settings = settings self.settings = settings else: self._settings = self._camera def set_freelook_mode(self): """Enables 6 degrees of freedom of movement for the camera.""" self._camera.trackbodyid = _NO_BODY_TRACKED_INDEX self._camera.fixedcamid = _FREE_CAMERA_INDEX self._camera.type_ = mujoco.mjtCamera.mjCAMERA_FREE mujoco.mjv_defaultFreeCamera(self._model.ptr, self._camera.ptr) def set_tracking_mode(self, body_id): """Latches the camera onto the specified body. Leaves the user only 3 degrees of freedom to rotate the camera. Args: body_id: A positive integer, ID of the body to track. """ if body_id < 0: return self._camera.trackbodyid = body_id self._camera.fixedcamid = _FREE_CAMERA_INDEX self._camera.type_ = mujoco.mjtCamera.mjCAMERA_TRACKING def set_fixed_mode(self, fixed_camera_id): """Fixes the camera in a pre-defined position, taking away all DOF. Args: fixed_camera_id: A positive integer, Id of a fixed camera defined in the scene. """ if fixed_camera_id < 0: return self._camera.trackbodyid = _NO_BODY_TRACKED_INDEX self._camera.fixedcamid = fixed_camera_id self._camera.type_ = mujoco.mjtCamera.mjCAMERA_FIXED def look_at(self, position, distance): """Positions the camera so that it's focused on the specified point.""" self._camera.lookat[:] = position self._camera.distance = distance def move(self, action, viewport_offset): """Moves the camera around the scene.""" # Not checking the validity of arguments on purpose. This method is designed # to be called very often, so in order to avoid the overhead, all arguments # are assumed to be valid. mujoco.mjv_moveCamera(self._model.ptr, action, viewport_offset[0], viewport_offset[1], self._scene.ptr, self._camera.ptr) def new_perturbation(self, body_id): """Creates a proxy that allows to manipulate the specified object.""" return Perturbation(body_id, self._model, self._data, self._scene) def raycast(self, viewport, screen_pos): """Shoots a ray from the specified viewport position into the scene.""" if not self.is_initialized: return -1, None viewport_pos = viewport.screen_to_inverse_viewport(screen_pos) grab_world_pos = np.empty(3, dtype=np.double) selected_geom_id_arr = np.intc([-1]) selected_skin_id_arr = np.intc([-1]) selected_body_id = mujoco.mjv_select( self._model.ptr, self._data.ptr, self._options.visualization.ptr, viewport.aspect_ratio, viewport_pos[0], viewport_pos[1], self._scene.ptr, grab_world_pos, selected_geom_id_arr, selected_skin_id_arr, ) del selected_geom_id_arr, selected_skin_id_arr # Unused. if selected_body_id < 0: selected_body_id = _INVALID_BODY_INDEX grab_world_pos = None return selected_body_id, grab_world_pos def render(self, perturbation=None): """Renders the scene form this camera's perspective. Args: perturbation: (Optional), instance of Perturbation. Returns: Rendered scene, instance of MjvScene. """ perturb_to_render = perturbation.ptr if perturbation else None mujoco.mjv_updateScene(self._model.ptr, self._data.ptr, self._options.visualization.ptr, perturb_to_render, self._camera.ptr, mujoco.mjtCatBit.mjCAT_ALL, self._scene.ptr) # Apply callback if defined. if self._scene_callback is not None: self._scene_callback(self._model, self._data, self._scene) return self._scene def zoom_to_scene(self): """Zooms in on the entire scene.""" self.look_at(self._model.stat.center[:], self._zoom_factor * self._model.stat.extent) self.settings = self._settings @property def transform(self): """Returns a tuple with camera transform. The transform comes in form: (3x3 rotation mtx, 3-component position). """ pos = np.zeros(3) forward = np.zeros(3) up = np.zeros(3) for i in range(3): forward[i] = self._scene.camera[0].forward[i] up[i] = self._scene.camera[0].up[i] pos[i] = (self._scene.camera[0].pos[i] + self._scene.camera[1].pos[i]) / 2 right = np.cross(forward, up) return np.array([right, up, forward]), pos @property def settings(self): """Returns internal camera settings.""" return self._camera @settings.setter def settings(self, value): """Restores the camera settings.""" self._camera.type_ = value.type_ self._camera.fixedcamid = value.fixedcamid self._camera.trackbodyid = value.trackbodyid self._camera.lookat[:] = value.lookat[:] self._camera.distance = value.distance self._camera.azimuth = value.azimuth self._camera.elevation = value.elevation @property def name(self): """Name of the active camera.""" if self._camera.type_ == mujoco.mjtCamera.mjCAMERA_TRACKING: body_name = self._model.id2name(self._camera.trackbodyid, 'body') if body_name: return 'Tracking body "%s"' % body_name else: return 'Tracking body id %d' % self._camera.trackbodyid elif self._camera.type_ == mujoco.mjtCamera.mjCAMERA_FIXED: camera_name = self._model.id2name(self._camera.fixedcamid, 'camera') if camera_name: return str(camera_name) else: return str(self._camera.fixedcamid) else: return 'Free' @property def mode(self): """Index of the mode the camera is currently in.""" return self._camera.type_ @property def is_initialized(self): """Returns True if camera is properly initialized.""" if not self._scene: return False frustum_near = self._scene.camera[0].frustum_near frustum_far = self._scene.camera[0].frustum_far return frustum_near > 0 and frustum_near < frustum_far class Viewport: """Render viewport.""" def __init__(self, width=1, height=1): """Instance initializer. Args: width: Viewport width, in pixels. height: Viewport height, in pixels. """ self._screen_size = mujoco.MjrRect(0, 0, width, height) def set_size(self, width, height): """Changes the viewport size. Args: width: Viewport width, in pixels. height: Viewport height, in pixels. """ self._screen_size.width = width self._screen_size.height = height def screen_to_viewport(self, screen_coordinates): """Converts screen coordinates to viewport coordinates. Args: screen_coordinates: 2-component tuple, with components being integral numbers in range defined by the screen/window resolution. Returns: A 2-component tuple, with components being floating point values in range [0, 1]. """ x = screen_coordinates[0] / self._screen_size.width y = screen_coordinates[1] / self._screen_size.height return np.array([x, y], np.float32) def screen_to_inverse_viewport(self, screen_coordinates): """Converts screen coordinates to viewport coordinates flipped vertically. Args: screen_coordinates: 2-component tuple, with components being integral numbers in range defined by the screen/window resolution. Returns: A 2-component tuple, with components being floating point values in range [0, 1]. The height component value will be flipped, with 1 at the top, and 0 at the bottom of the viewport. """ x = screen_coordinates[0] / self._screen_size.width y = 1. - (screen_coordinates[1] / self._screen_size.height) return np.array([x, y], np.float32) @property def aspect_ratio(self): return self._screen_size.width / self._screen_size.height @property def mujoco_rect(self): """Instance of MJRRECT with viewport dimensions.""" return self._screen_size @property def dimensions(self): """Viewport dimensions in form of a 2-component vector.""" return np.asarray([self._screen_size.width, self._screen_size.height]) @property def width(self): """Viewport width.""" return self._screen_size.width @property def height(self): """Viewport height.""" return self._screen_size.height
dm_control-main
dm_control/viewer/renderer.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 of the renderer module.""" from absl.testing import absltest from absl.testing import parameterized from dm_control.mujoco import wrapper from dm_control.mujoco.wrapper.mjbindings import enums from dm_control.viewer import renderer import mock import mujoco import numpy as np renderer.mujoco = mock.MagicMock() _SCREEN_SIZE = mujoco.MjrRect(0, 0, 320, 240) class BaseRendererTest(absltest.TestCase): class MockRenderer(renderer.BaseRenderer): pass class MockRenderComponent(renderer.Component): counter = 0 def __init__(self): self._call_order = -1 def render(self, context, viewport): self._call_order = BaseRendererTest.MockRenderComponent.counter BaseRendererTest.MockRenderComponent.counter += 1 @property def call_order(self): return self._call_order def setUp(self): super().setUp() self.renderer = BaseRendererTest.MockRenderer() self.context = mock.MagicMock() self.viewport = mock.MagicMock() def test_rendering_components(self): regular_component = BaseRendererTest.MockRenderComponent() screen_capture_component = BaseRendererTest.MockRenderComponent() self.renderer.components += regular_component self.renderer.screen_capture_components += screen_capture_component self.renderer._render_components(self.context, self.viewport) self.assertEqual(0, regular_component.call_order) self.assertEqual(1, screen_capture_component.call_order) @absltest.skip('b/222664582') class OffScreenRendererTest(absltest.TestCase): def setUp(self): super().setUp() self.model = mock.MagicMock() self.model.vis.global_.offwidth = _SCREEN_SIZE.width self.model.vis.global_.offheight = _SCREEN_SIZE.height self.surface = mock.MagicMock() self.renderer = renderer.OffScreenRenderer(self.model, self.surface) self.renderer._mujoco_context = mock.MagicMock() self.viewport = mock.MagicMock() self.scene = mock.MagicMock() self.viewport.width = 3 self.viewport.height = 3 self.viewport.dimensions = np.array([3, 3]) def test_render_context_initialization(self): self.renderer._mujoco_context = None self.renderer.render(self.viewport, self.scene) self.assertIsNotNone(self.renderer._mujoco_context) def test_resizing_pixel_buffer_to_viewport_size(self): self.renderer.render(self.viewport, self.scene) self.assertEqual((self.viewport.width, self.viewport.height, 3), self.renderer._rgb_buffer.shape) def test_rendering_components(self): regular_component = mock.MagicMock() screen_capture_components = mock.MagicMock() self.renderer.components += [regular_component] self.renderer.screen_capture_components += [screen_capture_components] self.renderer._render_on_gl_thread(self.viewport, self.scene) regular_component.render.assert_called_once() screen_capture_components.render.assert_called_once() @absltest.skip('b/222664582') class PerturbationTest(absltest.TestCase): def setUp(self): super().setUp() self.model = mock.MagicMock() self.data = mock.MagicMock() self.scene = mock.MagicMock() self.valid_pos = np.array([1, 2, 3]) self.body_id = 0 self.data.xpos = [np.array([0, 1, 2])] self.data.xmat = [np.identity(3)] self.perturbation = renderer.Perturbation( self.body_id, self.model, self.data, self.scene) renderer.mujoco.reset_mock() def test_start_params_validation(self): self.perturbation.start_move(None, self.valid_pos) self.assertEqual(0, renderer.mujoco.mjv_initPerturb.call_count) self.assertEqual(enums.mjtMouse.mjMOUSE_NONE, self.perturbation._action) self.perturbation.start_move(enums.mjtMouse.mjMOUSE_MOVE_V, None) self.assertEqual(0, renderer.mujoco.mjv_initPerturb.call_count) self.assertEqual(enums.mjtMouse.mjMOUSE_NONE, self.perturbation._action) def test_starting_an_operation(self): self.perturbation.start_move(enums.mjtMouse.mjMOUSE_MOVE_V, self.valid_pos) renderer.mujoco.mjv_initPerturb.assert_called_once() self.assertEqual(enums.mjtMouse.mjMOUSE_MOVE_V, self.perturbation._action) def test_starting_translation(self): self.perturbation.start_move(enums.mjtMouse.mjMOUSE_MOVE_V, self.valid_pos) self.assertEqual( enums.mjtPertBit.mjPERT_TRANSLATE, self.perturbation._perturb.active) def test_starting_rotation(self): self.perturbation.start_move(enums.mjtMouse.mjMOUSE_ROTATE_V, self.valid_pos) self.assertEqual( enums.mjtPertBit.mjPERT_ROTATE, self.perturbation._perturb.active) def test_starting_grip_transform(self): self.perturbation.start_move(enums.mjtMouse.mjMOUSE_MOVE_V, self.valid_pos) np.testing.assert_array_equal( [1, 1, 1], self.perturbation._perturb.localpos) def test_ticking_operation(self): self.perturbation._action = enums.mjtMouse.mjMOUSE_MOVE_V self.perturbation.tick_move([.1, .2]) renderer.mujoco.mjv_movePerturb.assert_called_once() action, dx, dy = renderer.mujoco.mjv_movePerturb.call_args[0][2:5] self.assertEqual(self.perturbation._action, action) self.assertEqual(.1, dx) self.assertEqual(.2, dy) def test_ticking_stopped_operation_yields_no_results(self): self.perturbation._action = None self.perturbation.tick_move([.1, .2]) self.assertEqual(0, renderer.mujoco.mjv_movePerturb.call_count) self.perturbation._action = enums.mjtMouse.mjMOUSE_NONE self.perturbation.tick_move([.1, .2]) self.assertEqual(0, renderer.mujoco.mjv_movePerturb.call_count) def test_stopping_operation(self): self.perturbation._action = enums.mjtMouse.mjMOUSE_MOVE_V self.perturbation._perturb.active = enums.mjtPertBit.mjPERT_TRANSLATE self.perturbation.end_move() self.assertEqual(enums.mjtMouse.mjMOUSE_NONE, self.perturbation._action) self.assertEqual(0, self.perturbation._perturb.active) def test_applying_operation_results_while_not_paused(self): with self.perturbation.apply(False): renderer.mujoco.mjv_applyPerturbPose.assert_called_once() self.assertEqual(0, renderer.mujoco.mjv_applyPerturbPose.call_args[0][3]) renderer.mujoco.mjv_applyPerturbForce.assert_called_once() def test_applying_operation_results_while_paused(self): with self.perturbation.apply(True): renderer.mujoco.mjv_applyPerturbPose.assert_called_once() self.assertEqual(1, renderer.mujoco.mjv_applyPerturbPose.call_args[0][3]) self.assertEqual(0, renderer.mujoco.mjv_applyPerturbForce.call_count) def test_clearing_applied_forces_after_appling_operation(self): self.data.xfrc_applied = np.zeros(1) with self.perturbation.apply(True): # At this point the simulation will calculate forces to apply and assign # them to a proper MjvData structure field, as we're doing below. self.data.xfrc_applied[self.body_id] = 1 # While exiting, the context clears that information. self.assertEqual(0, self.data.xfrc_applied[self.body_id]) @absltest.skip('b/222664582') class RenderSettingsTest(absltest.TestCase): def setUp(self): super().setUp() self.settings = renderer.RenderSettings() self.scene = wrapper.MjvScene() def test_applying_settings(self): self.settings._stereo_mode = 5 self.settings._render_flags[:] = np.arange(len(self.settings._render_flags)) self.settings.apply_settings(self.scene) self.assertEqual(self.settings._stereo_mode, self.scene.stereo) np.testing.assert_array_equal(self.settings._render_flags, self.scene.flags) def test_toggle_rendering_flag(self): self.settings._render_flags[0] = 1 self.settings.toggle_rendering_flag(0) self.assertEqual(0, self.settings._render_flags[0]) self.settings.toggle_rendering_flag(0) self.assertEqual(1, self.settings._render_flags[0]) def test_toggle_visualization_flag(self): self.settings._visualization_options.flags[0] = 1 self.settings.toggle_visualization_flag(0) self.assertEqual(0, self.settings._visualization_options.flags[0]) self.settings.toggle_visualization_flag(0) self.assertEqual(1, self.settings._visualization_options.flags[0]) def test_toggle_geom_group(self): self.settings._visualization_options.geomgroup[0] = 1 self.settings.toggle_geom_group(0) self.assertEqual(0, self.settings._visualization_options.geomgroup[0]) self.settings.toggle_geom_group(0) self.assertEqual(1, self.settings._visualization_options.geomgroup[0]) def test_toggle_site_group(self): self.settings._visualization_options.sitegroup[0] = 1 self.settings.toggle_site_group(0) self.assertEqual(0, self.settings._visualization_options.sitegroup[0]) self.settings.toggle_site_group(0) self.assertEqual(1, self.settings._visualization_options.sitegroup[0]) def test_toggle_stereo_buffering(self): self.settings.toggle_stereo_buffering() self.assertEqual(enums.mjtStereo.mjSTEREO_QUADBUFFERED, self.settings._stereo_mode) self.settings.toggle_stereo_buffering() self.assertEqual(enums.mjtStereo.mjSTEREO_NONE, self.settings._stereo_mode) def test_cycling_forward_through_render_modes(self): self.settings._visualization_options.frame = 0 self.settings.select_next_rendering_mode() self.assertEqual(1, self.settings._visualization_options.frame) self.settings._visualization_options.frame = enums.mjtFrame.mjNFRAME - 1 self.settings.select_next_rendering_mode() self.assertEqual(0, self.settings._visualization_options.frame) def test_cycling_backward_through_render_modes(self): self.settings._visualization_options.frame = 0 self.settings.select_prev_rendering_mode() self.assertEqual(enums.mjtFrame.mjNFRAME - 1, self.settings._visualization_options.frame) self.settings._visualization_options.frame = 1 self.settings.select_prev_rendering_mode() self.assertEqual(0, self.settings._visualization_options.frame) def test_cycling_forward_through_labeling_modes(self): self.settings._visualization_options.label = 0 self.settings.select_next_labeling_mode() self.assertEqual(1, self.settings._visualization_options.label) self.settings._visualization_options.label = enums.mjtLabel.mjNLABEL - 1 self.settings.select_next_labeling_mode() self.assertEqual(0, self.settings._visualization_options.label) def test_cycling_backward_through_labeling_modes(self): self.settings._visualization_options.label = 0 self.settings.select_prev_labeling_mode() self.assertEqual(enums.mjtLabel.mjNLABEL - 1, self.settings._visualization_options.label) self.settings._visualization_options.label = 1 self.settings.select_prev_labeling_mode() self.assertEqual(0, self.settings._visualization_options.label) @absltest.skip('b/222664582') class SceneCameraTest(parameterized.TestCase): @mock.patch.object(renderer.wrapper.core, '_estimate_max_renderable_geoms', return_value=1000) @mock.patch.object(renderer.wrapper.core.mujoco, 'MjvScene') def setUp(self, mock_make_scene, _): super().setUp() self.model = mock.MagicMock() self.data = mock.MagicMock() self.options = mock.MagicMock() self.camera = renderer.SceneCamera(self.model, self.data, self.options) mock_make_scene.assert_called_once() def test_freelook_mode(self): self.camera.set_freelook_mode() self.assertEqual(-1, self.camera._camera.trackbodyid) self.assertEqual(-1, self.camera._camera.fixedcamid) self.assertEqual(enums.mjtCamera.mjCAMERA_FREE, self.camera._camera.type_) self.assertEqual('Free', self.camera.name) def test_tracking_mode(self): body_id = 5 self.camera.set_tracking_mode(body_id) self.assertEqual(body_id, self.camera._camera.trackbodyid) self.assertEqual(-1, self.camera._camera.fixedcamid) self.assertEqual(enums.mjtCamera.mjCAMERA_TRACKING, self.camera._camera.type_) self.model.id2name = mock.MagicMock(return_value='body_name') self.assertEqual('Tracking body "body_name"', self.camera.name) def test_fixed_mode(self): camera_id = 5 self.camera.set_fixed_mode(camera_id) self.assertEqual(-1, self.camera._camera.trackbodyid) self.assertEqual(camera_id, self.camera._camera.fixedcamid) self.assertEqual(enums.mjtCamera.mjCAMERA_FIXED, self.camera._camera.type_) self.model.id2name = mock.MagicMock(return_value='camera_name') self.assertEqual('camera_name', self.camera.name) def test_look_at(self): target_pos = [10, 20, 30] distance = 5. self.camera.look_at(target_pos, distance) np.testing.assert_array_equal(target_pos, self.camera._camera.lookat) np.testing.assert_array_equal(distance, self.camera._camera.distance) def test_moving_camera(self): action = enums.mjtMouse.mjMOUSE_MOVE_V offset = [0.1, -0.2] with mock.patch(renderer.__name__ + '.mujoco') as mock_mujoco: self.camera.move(action, offset) mock_mujoco.mjv_moveCamera.assert_called_once() def test_zoom_to_scene(self): scene_center = np.array([1, 2, 3]) scene_extents = np.array([10, 20, 30]) self.camera.look_at = mock.MagicMock() self.model.stat = mock.MagicMock() self.model.stat.center = scene_center self.model.stat.extent = scene_extents self.camera.zoom_to_scene() self.camera.look_at.assert_called_once() np.testing.assert_array_equal( scene_center, self.camera.look_at.call_args[0][0]) np.testing.assert_array_equal( scene_extents * 1.5, self.camera.look_at.call_args[0][1]) def test_camera_transform(self): self.camera._scene.camera[0].up[:] = [0, 1, 0] self.camera._scene.camera[0].forward[:] = [0, 0, 1] self.camera._scene.camera[0].pos[:] = [5, 0, 0] self.camera._scene.camera[1].pos[:] = [10, 0, 0] rotation_mtx, position = self.camera.transform np.testing.assert_array_equal([-1, 0, 0], rotation_mtx[0]) np.testing.assert_array_equal([0, 1, 0], rotation_mtx[1]) np.testing.assert_array_equal([0, 0, 1], rotation_mtx[2]) np.testing.assert_array_equal([7.5, 0, 0], position) @parameterized.parameters( (0, 0, False), (0, 1, False), (1, 0, False), (2, 1, False), (1, 2, True)) def test_is_camera_initialized(self, frustum_near, frustum_far, result): gl_camera = mock.MagicMock() self.camera._scene = mock.MagicMock() self.camera._scene.camera = [gl_camera] gl_camera.frustum_near = frustum_near gl_camera.frustum_far = frustum_far self.assertEqual(result, self.camera.is_initialized) @absltest.skip('b/222664582') class RaycastsTest(absltest.TestCase): @mock.patch.object(renderer.wrapper.core, '_estimate_max_renderable_geoms', return_value=1000) @mock.patch.object(renderer.wrapper.core.mujoco, 'MjvScene') def setUp(self, mock_make_scene, _): super().setUp() self.model = mock.MagicMock() self.data = mock.MagicMock() self.options = mock.MagicMock() self.viewport = mock.MagicMock() self.camera = renderer.SceneCamera(self.model, self.data, self.options) mock_make_scene.assert_called_once() self.initialize_camera(True) def initialize_camera(self, enable): gl_camera = mock.MagicMock() self.camera._scene = mock.MagicMock() self.camera._scene.camera = [gl_camera] gl_camera.frustum_near = 1 if enable else 0 gl_camera.frustum_far = 2 if enable else 0 def test_raycast_mapping_geom_to_body_id(self): def build_mjv_select(mock_body_id, mock_geom_id, mock_position): def mock_select( m, d, vopt, aspectratio, relx, rely, scn, selpnt, geomid, skinid): del m, d, vopt, aspectratio, relx, rely, scn, skinid # Unused. selpnt[:] = mock_position geomid[:] = mock_geom_id return mock_body_id return mock_select geom_id = 0 body_id = 5 world_pos = [1, 2, 3] self.model.geom_bodyid = np.zeros(10) self.model.geom_bodyid[geom_id] = body_id mock_select = build_mjv_select(body_id, geom_id, world_pos) with mock.patch(renderer.__name__ + '.mujoco') as mock_mujoco: mock_mujoco.mjv_select = mock.MagicMock(side_effect=mock_select) hit_body_id, hit_world_pos = self.camera.raycast(self.viewport, [0, 0]) self.assertEqual(hit_body_id, body_id) np.testing.assert_array_equal(hit_world_pos, world_pos) def test_raycast_hitting_empty_space(self): def mock_select( m, d, vopt, aspectratio, relx, rely, scn, selpnt, geomid, skinid): del (m, d, vopt, aspectratio, relx, rely, scn, selpnt, geomid, skinid) # Unused. mock_body_id = -1 # Nothing selected. return mock_body_id with mock.patch(renderer.__name__ + '.mujoco') as mock_mujoco: mock_mujoco.mjv_select = mock.MagicMock(side_effect=mock_select) hit_body_id, hit_world_pos = self.camera.raycast(self.viewport, [0, 0]) self.assertEqual(-1, hit_body_id) self.assertIsNone(hit_world_pos) def test_raycast_maps_coordinates_to_viewport_space(self): def build_mjv_select(expected_aspect_ratio, expected_viewport_pos): def mock_select( m, d, vopt, aspectratio, relx, rely, scn, selpnt, geomid, skinid): del m, d, vopt, scn, selpnt, geomid, skinid # Unused. self.assertEqual(expected_aspect_ratio, aspectratio) np.testing.assert_array_equal(expected_viewport_pos, [relx, rely]) mock_body_id = 0 return mock_body_id return mock_select viewport_pos = [.5, .5] self.viewport.screen_to_inverse_viewport.return_value = viewport_pos mock_select = build_mjv_select(self.viewport.aspect_ratio, viewport_pos) with mock.patch(renderer.__name__ + '.mujoco') as mock_mujoco: mock_mujoco.mjv_select = mock.MagicMock(side_effect=mock_select) self.camera.raycast(self.viewport, [50, 25]) def test_raycasts_disabled_when_camera_is_not_initialized(self): self.initialize_camera(False) hit_body_id, hit_world_pos = self.camera.raycast(self.viewport, [0, 0]) self.assertEqual(-1, hit_body_id) self.assertIsNone(hit_world_pos) class ViewportTest(parameterized.TestCase): def setUp(self): super().setUp() self.viewport = renderer.Viewport() self.viewport.set_size(100, 100) @parameterized.parameters( ([0, 0], [0., 0.]), ([100, 0], [1., 0.]), ([0, 100], [0., 1.]), ([50, 50], [.5, .5])) def test_screen_to_viewport(self, screen_coords, viewport_coords): np.testing.assert_array_equal( viewport_coords, self.viewport.screen_to_viewport(screen_coords)) @parameterized.parameters( ([0, 0], [0., 1.]), ([100, 0], [1., 1.]), ([0, 100], [0., 0.]), ([50, 50], [.5, .5])) def test_screen_to_inverse_viewport(self, screen_coords, viewport_coords): np.testing.assert_array_equal( viewport_coords, self.viewport.screen_to_inverse_viewport(screen_coords)) @parameterized.parameters( ([10, 10], 1.), ([30, 40], 3./4.)) def test_aspect_ratio(self, screen_size, aspect_ratio): self.viewport.set_size(screen_size[0], screen_size[1]) self.assertEqual(aspect_ratio, self.viewport.aspect_ratio) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/viewer/renderer_test.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Suite environments viewer package.""" from dm_control.viewer import application def launch(environment_loader, policy=None, title='Explorer', width=1024, height=768): """Launches an environment viewer. Args: environment_loader: An environment loader (a callable that returns an instance of dm_control.rl.control.Environment), an instance of dm_control.rl.control.Environment. policy: An optional callable corresponding to a policy to execute within the environment. It should accept a `TimeStep` and return a numpy array of actions conforming to the output of `environment.action_spec()`. title: Application title to be displayed in the title bar. width: Window width, in pixels. height: Window height, in pixels. Raises: ValueError: When 'environment_loader' argument is set to None. """ app = application.Application(title=title, width=width, height=height) app.launch(environment_loader=environment_loader, policy=policy)
dm_control-main
dm_control/viewer/__init__.py
# Copyright 2018-2019 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Environment's execution runtime.""" import collections import copy import enum from dm_control.mujoco.wrapper import mjbindings from dm_control.viewer import util import mujoco import numpy as np mjlib = mjbindings.mjlib # Pause interval between simulation steps. _SIMULATION_STEP_INTERVAL = 0.001 # The longest allowed simulation time step, in seconds. _DEFAULT_MAX_SIM_STEP = 1./5. def _get_default_action(action_spec): """Generates an action to apply to the environment if there is no agent. * For action dimensions that are closed intervals this will be the midpoint. * For left-open or right-open intervals this will be the maximum or the minimum respectively. * For unbounded intervals this will be zero. Args: action_spec: An instance of `BoundedArraySpec` or a list or tuple containing these. Returns: A numpy array of actions if `action_spec` is a single `BoundedArraySpec`, or a tuple of such arrays if `action_spec` is a list or tuple. """ if isinstance(action_spec, (list, tuple)): return tuple(_get_default_action(spec) for spec in action_spec) elif isinstance(action_spec, collections.abc.MutableMapping): # Clones the Mapping, preserving type and key order. result = copy.copy(action_spec) for key, value in action_spec.items(): result[key] = _get_default_action(value) return result minimum = np.broadcast_to(action_spec.minimum, action_spec.shape) maximum = np.broadcast_to(action_spec.maximum, action_spec.shape) left_bounded = np.isfinite(minimum) right_bounded = np.isfinite(maximum) action = np.select( condlist=[left_bounded & right_bounded, left_bounded, right_bounded], choicelist=[0.5 * (minimum + maximum), minimum, maximum], default=0.) action = action.astype(action_spec.dtype, copy=False) action.flags.writeable = False return action class State(enum.Enum): """State of the Runtime class.""" START = 0 RUNNING = 1 STOP = 2 STOPPED = 3 RESTARTING = 4 class Runtime: """Base Runtime class. Attributes: simulation_time_budget: Float value, how much time can be spent on physics simulation every frame, in seconds. on_episode_begin: An observable subject, an instance of util.QuietSet. It contains argumentless callables, invoked, when a new episode begins. on_error: An observable subject, an instance of util.QuietSet. It contains single argument callables, invoked, when the environment or the agent throw an error. on_physics_changed: An observable subject, an instance of util.QuietSet. During episode restarts, the underlying physics instance may change. If you are interested in learning about those changes, attach a listener using the += operator. The listener should be a callable with no required arguments. """ def __init__(self, environment, policy=None): """Instance initializer. Args: environment: An instance of dm_control.rl.control.Environment. policy: Either a callable that accepts a `TimeStep` and returns a numpy array of actions conforming to `environment.action_spec()`, or None, in which case a default action will be generated for each environment step. """ self.on_error = util.QuietSet() self.on_episode_begin = util.QuietSet() self.simulation_time_budget = _DEFAULT_MAX_SIM_STEP self._state = State.START self._simulation_timer = util.Timer() self._tracked_simulation_time = 0.0 self._error_logger = util.ErrorLogger(self.on_error) self._env = environment self._policy = policy self._default_action = _get_default_action(environment.action_spec()) self._time_step = None self._last_action = None self.on_physics_changed = util.QuietSet() def tick(self, time_elapsed, paused): """Advances the simulation by one frame. Args: time_elapsed: Time elapsed since the last time this method was called. paused: A boolean flag telling if the simulation is paused. Returns: A boolean flag to determine if the episode has finished. """ with self._simulation_timer.measure_time(): if self._state == State.RESTARTING: self._state = State.START if self._state == State.START: if self._start(): self._broadcast_episode_start() self._tracked_simulation_time = self.get_time() self._state = State.RUNNING else: self._state = State.STOPPED if self._state == State.RUNNING: finished = self._step_simulation(time_elapsed, paused) if finished: self._state = State.STOP if self._state == State.STOP: self._state = State.STOPPED def _step_simulation(self, time_elapsed, paused): """Simulate a simulation step.""" finished = False if paused: self._step_paused() else: step_duration = min(time_elapsed, self.simulation_time_budget) actual_simulation_time = self.get_time() if self._tracked_simulation_time >= actual_simulation_time: end_time = actual_simulation_time + step_duration while not finished and self.get_time() < end_time: finished = self._step() self._tracked_simulation_time += step_duration return finished def single_step(self): """Performs a single step of simulation.""" if self._state == State.RUNNING: finished = self._step() self._state = State.STOP if finished else State.RUNNING def stop(self): """Stops the runtime.""" self._state = State.STOPPED def restart(self): """Restarts the episode, resetting environment, model, and data.""" if self._state != State.STOPPED: self._state = State.RESTARTING else: self._state = State.START def get_time(self): """Elapsed simulation time.""" return self._env.physics.data.time @property def state(self): """Returns the current state of the state machine. Returned states are values of runtime.State enum. """ return self._state @property def simulation_time(self): """Returns the amount of time spent running the simulation.""" return self._simulation_timer.measured_time @property def last_action(self): """Action passed to the environment on the last step.""" return self._last_action def _broadcast_episode_start(self): for listener in self.on_episode_begin: listener() def _start(self): """Starts a new simulation episode. Starting a new episode may be associated with changing the physics instance. The method tracks that and notifies observers through 'on_physics_changed' subject. Returns: True if the operation was successful, False otherwise. """ # NB: we check the identity of the data pointer rather than the physics # instance itself, since this allows us to detect when the physics has been # "reloaded" using one of the `reload_from_*` methods. old_data_ptr = self._env.physics.data.ptr with self._error_logger: self._time_step = self._env.reset() if self._env.physics.data.ptr is not old_data_ptr: for listener in self.on_physics_changed: listener() return not self._error_logger.errors_found def _step_paused(self): mujoco.mj_forward(self._env.physics.model.ptr, self._env.physics.data.ptr) def _step(self): """Generates an action and applies it to the environment. If a `policy` was provided, this will be invoked to generate an action to feed to the environment, otherwise a default action will be generated. Returns: A boolean value, True if the environment signaled the episode end, False if the episode is still running. """ finished = True with self._error_logger: if self._policy: action = self._policy(self._time_step) else: action = self._default_action self._time_step = self._env.step(action) self._last_action = action finished = self._time_step.last() return finished or self._error_logger.errors_found
dm_control-main
dm_control/viewer/runtime.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 the keyboard module.""" import collections from absl.testing import absltest from absl.testing import parameterized from dm_control.viewer import util import mock import numpy as np class QuietSetTest(absltest.TestCase): def test_add_listeners(self): subject = util.QuietSet() listeners = [object() for _ in range(5)] for listener in listeners: subject += listener self.assertLen(subject, 5) def test_add_collection_of_listeners(self): subject = util.QuietSet() subject += [object() for _ in range(5)] self.assertLen(subject, 5) def test_add_collection_and_individual_listeners(self): subject = util.QuietSet() subject += object() subject += [object() for _ in range(5)] subject += object() self.assertLen(subject, 7) def test_add_duplicate_listeners(self): subject = util.QuietSet() listener = object() subject += listener self.assertLen(subject, 1) subject += listener self.assertLen(subject, 1) def test_remove_listeners(self): subject = util.QuietSet() listeners = [object() for _ in range(3)] for listener in listeners: subject += listener subject -= listeners[1] self.assertLen(subject, 2) def test_remove_unregistered_listener(self): subject = util.QuietSet() listeners = [object() for _ in range(3)] for listener in listeners: subject += listener subject -= object() self.assertLen(subject, 3) class ToIterableTest(parameterized.TestCase): def test_scalars_converted_to_iterables(self): original_value = 3 result = util.to_iterable(original_value) self.assertIsInstance(result, collections.abc.Iterable) self.assertLen(result, 1) self.assertEqual(original_value, result[0]) def test_strings_wrappe_by_list(self): original_value = 'test_string' result = util.to_iterable(original_value) self.assertIsInstance(result, collections.abc.Iterable) self.assertLen(result, 1) self.assertEqual(original_value, result[0]) @parameterized.named_parameters( ('list', [1, 2, 3]), ('set', set([1, 2, 3])), ('dict', {'1': 2, '3': 4, '5': 6}) ) def test_iterables_remain_unaffected(self, original_value): result = util.to_iterable(original_value) self.assertEqual(result, original_value) class InterleaveTest(absltest.TestCase): def test_equal_sized_iterables(self): a = [1, 2, 3] b = [4, 5, 6] c = [i for i in util.interleave(a, b)] np.testing.assert_array_equal([1, 4, 2, 5, 3, 6], c) def test_iteration_ends_when_smaller_iterable_runs_out_of_elements(self): a = [1, 2, 3] b = [4, 5, 6, 7, 8] c = [i for i in util.interleave(a, b)] np.testing.assert_array_equal([1, 4, 2, 5, 3, 6], c) class TimeMultiplierTests(absltest.TestCase): def setUp(self): super().setUp() self.factor = util.TimeMultiplier(initial_time_multiplier=1.0) def test_custom_initial_factor(self): initial_value = 0.5 factor = util.TimeMultiplier(initial_time_multiplier=initial_value) self.assertEqual(initial_value, factor.get()) def test_initial_factor_clamped_to_valid_value_range(self): too_large_multiplier = util._MAX_TIME_MULTIPLIER + 1. too_small_multiplier = util._MIN_TIME_MULTIPLIER - 1. factor = util.TimeMultiplier(initial_time_multiplier=too_large_multiplier) self.assertEqual(util._MAX_TIME_MULTIPLIER, factor.get()) factor = util.TimeMultiplier(initial_time_multiplier=too_small_multiplier) self.assertEqual(util._MIN_TIME_MULTIPLIER, factor.get()) def test_increase(self): self.factor.decrease() self.factor.decrease() self.factor.increase() self.assertEqual(self.factor._real_time_multiplier, 0.5) def test_increase_limit(self): self.factor._real_time_multiplier = util._MAX_TIME_MULTIPLIER self.factor.increase() self.assertEqual(util._MAX_TIME_MULTIPLIER, self.factor.get()) def test_decrease(self): self.factor.decrease() self.factor.decrease() self.assertEqual(self.factor._real_time_multiplier, 0.25) def test_decrease_limit(self): self.factor._real_time_multiplier = util._MIN_TIME_MULTIPLIER self.factor.decrease() self.assertEqual(util._MIN_TIME_MULTIPLIER, self.factor.get()) def test_stringify_when_less_than_one(self): self.assertEqual('1', str(self.factor)) self.factor.decrease() self.assertEqual('1/2', str(self.factor)) self.factor.decrease() self.assertEqual('1/4', str(self.factor)) class IntegratorTests(absltest.TestCase): def setUp(self): super().setUp() self.integration_step = 1 self.integrator = util.Integrator(self.integration_step) self.integrator._sampling_timestamp = 0.0 def test_initial_value(self): self.assertEqual(0, self.integrator.value) def test_integration_step(self): with mock.patch(util.__name__ + '.time') as time_mock: time_mock.time.return_value = self.integration_step self.integrator.value = 1 self.assertEqual(1, self.integrator.value) def test_averaging(self): with mock.patch(util.__name__ + '.time') as time_mock: time_mock.time.return_value = 0 self.integrator.value = 1 self.integrator.value = 1 self.integrator.value = 1 time_mock.time.return_value = self.integration_step self.integrator.value = 1 self.assertEqual(1, self.integrator.value) class AtomicActionTests(absltest.TestCase): def setUp(self): super().setUp() self.callback = mock.MagicMock() self.action = util.AtomicAction(self.callback) def test_starting_and_ending_one_action(self): self.action.begin(1) self.assertEqual(1, self.action.watermark) self.callback.assert_called_once_with(1) self.callback.reset_mock() self.action.end(1) self.assertIsNone(self.action.watermark) self.callback.assert_called_once_with(None) def test_trying_to_interrupt_with_another_action(self): self.action.begin(1) self.assertEqual(1, self.action.watermark) self.callback.assert_called_once_with(1) self.callback.reset_mock() self.action.begin(2) self.assertEqual(1, self.action.watermark) self.assertEqual(0, self.callback.call_count) def test_trying_to_end_another_action(self): self.action.begin(1) self.callback.reset_mock() self.action.end(2) self.assertEqual(1, self.action.watermark) self.assertEqual(0, self.callback.call_count) class ObservableFlagTest(absltest.TestCase): def test_update_each_added_listener(self): listener = mock.MagicMock(spec=object) subject = util.ObservableFlag(True) subject += listener listener.assert_called_once_with(True) def test_update_listeners_on_toggle(self): listeners = [mock.MagicMock(spec=object) for _ in range(10)] subject = util.ObservableFlag(True) subject += listeners for listener in listeners: listener.reset_mock() subject.toggle() for listener in listeners: listener.assert_called_once_with(False) class TimerTest(absltest.TestCase): def setUp(self): super().setUp() self.timer = util.Timer() def test_time_elapsed(self): with mock.patch(util.__name__ + '.time') as time_mock: time_mock.time.return_value = 1 self.timer.tick() time_mock.time.return_value = 2 self.assertEqual(1, self.timer.tick()) def test_time_measurement(self): with mock.patch(util.__name__ + '.time') as time_mock: time_mock.time.return_value = 1 with self.timer.measure_time(): time_mock.time.return_value = 4 self.assertEqual(3, self.timer.measured_time) class ErrorLoggerTest(absltest.TestCase): def setUp(self): super().setUp() self.callback = mock.MagicMock() self.logger = util.ErrorLogger([self.callback]) def test_no_errors_found_on_initialization(self): self.assertFalse(self.logger.errors_found) def test_no_error_caught(self): with self.logger: pass self.assertFalse(self.logger.errors_found) def test_error_caught(self): with self.logger: raise Exception('error message') self.assertTrue(self.logger.errors_found) def test_notifying_callbacks(self): error_message = 'error message' with self.logger: raise Exception(error_message) self.callback.assert_called_once_with(error_message) class NullErrorLoggerTest(absltest.TestCase): def setUp(self): super().setUp() self.logger = util.NullErrorLogger() def test_thrown_errors_are_not_being_intercepted(self): with self.assertRaises(Exception): with self.logger: raise Exception() def test_errors_found_always_returns_false(self): self.assertFalse(self.logger.errors_found) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/viewer/util_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. # ============================================================================ """Viewer application module.""" import collections from dm_control import _render from dm_control.viewer import gui from dm_control.viewer import renderer from dm_control.viewer import runtime from dm_control.viewer import user_input from dm_control.viewer import util from dm_control.viewer import viewer from dm_control.viewer import views _DOUBLE_BUFFERING = (user_input.KEY_F5) _PAUSE = user_input.KEY_SPACE _RESTART = user_input.KEY_BACKSPACE _ADVANCE_SIMULATION = user_input.KEY_RIGHT _SPEED_UP_TIME = user_input.KEY_EQUAL _SLOW_DOWN_TIME = user_input.KEY_MINUS _HELP = user_input.KEY_F1 _STATUS = user_input.KEY_F2 _MAX_FRONTBUFFER_SIZE = 2048 _MISSING_STATUS_ENTRY = '--' _RUNTIME_STOPPED_LABEL = 'EPISODE TERMINATED - hit backspace to restart' _STATUS_LABEL = 'Status' _TIME_LABEL = 'Time' _CPU_LABEL = 'CPU' _FPS_LABEL = 'FPS' _CAMERA_LABEL = 'Camera' _PAUSED_LABEL = 'Paused' _ERROR_LABEL = 'Error' class Help(views.ColumnTextModel): """Contains the description of input map employed in the application.""" def __init__(self): """Instance initializer.""" self._value = [ ['Help', 'F1'], ['Info', 'F2'], ['Stereo', 'F5'], ['Frame', 'F6'], ['Label', 'F7'], ['--------------', ''], ['Pause', 'Space'], ['Reset', 'BackSpace'], ['Autoscale', 'Ctrl A'], ['Geoms', '0 - 4'], ['Sites', 'Shift 0 - 4'], ['Speed Up', '='], ['Slow Down', '-'], ['Switch Cam', '[ ]'], ['--------------', ''], ['Translate', 'R drag'], ['Rotate', 'L drag'], ['Zoom', 'Scroll'], ['Select', 'L dblclick'], ['Center', 'R dblclick'], ['Track', 'Ctrl R dblclick / Esc'], ['Perturb', 'Ctrl [Shift] L/R drag'], ] def get_columns(self): """Returns the text to display in two columns.""" return self._value class Status(views.ColumnTextModel): """Monitors and returns the status of the application.""" def __init__(self, time_multiplier, pause, frame_timer): """Instance initializer. Args: time_multiplier: Instance of util.TimeMultiplier. pause: An observable pause subject, instance of util.ObservableFlag. frame_timer: A Timer instance counting duration of frames. """ self._runtime = None self._time_multiplier = time_multiplier self._camera = None self._pause = pause self._frame_timer = frame_timer self._fps_counter = util.Integrator() self._cpu_counter = util.Integrator() self._value = collections.OrderedDict([ (_STATUS_LABEL, _MISSING_STATUS_ENTRY), (_TIME_LABEL, _MISSING_STATUS_ENTRY), (_CPU_LABEL, _MISSING_STATUS_ENTRY), (_FPS_LABEL, _MISSING_STATUS_ENTRY), (_CAMERA_LABEL, _MISSING_STATUS_ENTRY), (_PAUSED_LABEL, _MISSING_STATUS_ENTRY), (_ERROR_LABEL, _MISSING_STATUS_ENTRY), ]) def set_camera(self, camera): """Updates the active camera instance. Args: camera: Instance of renderer.SceneCamera. """ self._camera = camera def set_runtime(self, instance): """Updates the active runtime instance. Args: instance: Instance of runtime.Base. """ if self._runtime: self._runtime.on_error -= self._on_error self._runtime.on_episode_begin -= self._clear_error self._runtime = instance if self._runtime: self._runtime.on_error += self._on_error self._runtime.on_episode_begin += self._clear_error def get_columns(self): """Returns the text to display in two columns.""" if self._frame_timer.measured_time > 0: self._fps_counter.value = 1. / self._frame_timer.measured_time self._value[_FPS_LABEL] = '{0:.1f}'.format(self._fps_counter.value) if self._runtime: if self._runtime.state == runtime.State.STOPPED: self._value[_STATUS_LABEL] = _RUNTIME_STOPPED_LABEL else: self._value[_STATUS_LABEL] = str(self._runtime.state) self._cpu_counter.value = self._runtime.simulation_time self._value[_TIME_LABEL] = '{0:.1f} ({1}x)'.format( self._runtime.get_time(), str(self._time_multiplier)) self._value[_CPU_LABEL] = '{0:.2f}ms'.format( self._cpu_counter.value * 1000.0) else: self._value[_STATUS_LABEL] = _MISSING_STATUS_ENTRY self._value[_TIME_LABEL] = _MISSING_STATUS_ENTRY self._value[_CPU_LABEL] = _MISSING_STATUS_ENTRY if self._camera: self._value[_CAMERA_LABEL] = self._camera.name else: self._value[_CAMERA_LABEL] = _MISSING_STATUS_ENTRY self._value[_PAUSED_LABEL] = str(self._pause.value) return list(self._value.items()) # For Python 2/3 compatibility. def _clear_error(self): self._value[_ERROR_LABEL] = _MISSING_STATUS_ENTRY def _on_error(self, error_msg): self._value[_ERROR_LABEL] = error_msg class ReloadParams(collections.namedtuple( 'RefreshParams', ['zoom_to_scene'])): """Parameters of a reload request.""" class Application: """Viewer application.""" def __init__(self, title='Explorer', width=1024, height=768): """Instance initializer.""" self._render_surface = None self._renderer = renderer.NullRenderer() self._viewport = renderer.Viewport(width, height) self._window = gui.RenderWindow(width, height, title) self._pause_subject = util.ObservableFlag(True) self._time_multiplier = util.TimeMultiplier(1.) self._frame_timer = util.Timer() self._viewer = viewer.Viewer( self._viewport, self._window.mouse, self._window.keyboard) self._viewer_layout = views.ViewportLayout() self._status = Status( self._time_multiplier, self._pause_subject, self._frame_timer) self._runtime = None self._environment_loader = None self._environment = None self._policy = None self._deferred_reload_request = None status_view_toggle = self._build_view_toggle( views.ColumnTextView(self._status), views.PanelLocation.BOTTOM_LEFT) help_view_toggle = self._build_view_toggle( views.ColumnTextView(Help()), views.PanelLocation.TOP_RIGHT) status_view_toggle() self._input_map = user_input.InputMap( self._window.mouse, self._window.keyboard) self._input_map.bind(self._pause_subject.toggle, _PAUSE) self._input_map.bind(self._time_multiplier.increase, _SPEED_UP_TIME) self._input_map.bind(self._time_multiplier.decrease, _SLOW_DOWN_TIME) self._input_map.bind(self._advance_simulation, _ADVANCE_SIMULATION) self._input_map.bind(self._restart_runtime, _RESTART) self._input_map.bind(help_view_toggle, _HELP) self._input_map.bind(status_view_toggle, _STATUS) def _on_reload(self, zoom_to_scene=False): """Perform initialization related to Physics reload. Reset the components that depend on a specific Physics class instance. Args: zoom_to_scene: Should the camera zoom to show the entire scene after the reload is complete. """ self._deferred_reload_request = ReloadParams(zoom_to_scene) self._viewer.deinitialize() self._status.set_camera(None) def _perform_deferred_reload(self, params): """Performs the deferred part of initialization related to Physics reload. Args: params: Deferred reload parameters, an instance of ReloadParams. """ if self._render_surface: self._render_surface.free() if self._renderer: self._renderer.release() self._render_surface = _render.Renderer( max_width=_MAX_FRONTBUFFER_SIZE, max_height=_MAX_FRONTBUFFER_SIZE) self._renderer = renderer.OffScreenRenderer( self._environment.physics.model, self._render_surface) self._renderer.components += self._viewer_layout self._viewer.initialize( self._environment.physics, self._renderer, touchpad=False) self._status.set_camera(self._viewer.camera) if params.zoom_to_scene: self._viewer.zoom_to_scene() def _build_view_toggle(self, view, location): def toggle(): if view in self._viewer_layout: self._viewer_layout.remove(view) else: self._viewer_layout.add(view, location) return toggle def _tick(self): """Handle GUI events until the main window is closed.""" if self._deferred_reload_request: self._perform_deferred_reload(self._deferred_reload_request) self._deferred_reload_request = None time_elapsed = self._frame_timer.tick() * self._time_multiplier.get() if self._runtime: with self._viewer.perturbation.apply(self._pause_subject.value): self._runtime.tick(time_elapsed, self._pause_subject.value) self._viewer.render() def _load_environment(self, zoom_to_scene): """Loads a new environment.""" if self._runtime: del self._runtime self._runtime = None self._environment = None environment_instance = None if self._environment_loader: environment_instance = self._environment_loader() if environment_instance: self._environment = environment_instance self._runtime = runtime.Runtime( environment=self._environment, policy=self._policy) self._runtime.on_physics_changed += lambda: self._on_reload(False) self._status.set_runtime(self._runtime) self._on_reload(zoom_to_scene=zoom_to_scene) def _restart_runtime(self): """Restarts the episode, resetting environment, model, and data.""" if self._runtime: self._runtime.stop() self._load_environment(zoom_to_scene=False) if self._policy: if hasattr(self._policy, 'reset'): self._policy.reset() def _advance_simulation(self): if self._runtime: self._runtime.single_step() def launch(self, environment_loader, policy=None): """Starts the viewer with the specified policy and environment. Args: environment_loader: Either a callable that takes no arguments and returns an instance of dm_control.rl.control.Environment, or an instance of dm_control.rl.control.Environment. policy: An optional callable corresponding to a policy to execute within the environment. It should accept a `TimeStep` and return a numpy array of actions conforming to the output of `environment.action_spec()`. If the callable implements a method `reset` then this method is called when the viewer is reset. Raises: ValueError: If `environment_loader` is None. """ if environment_loader is None: raise ValueError('"environment_loader" argument is required.') if callable(environment_loader): self._environment_loader = environment_loader else: self._environment_loader = lambda: environment_loader self._policy = policy self._load_environment(zoom_to_scene=True) def tick(): self._viewport.set_size(*self._window.shape) self._tick() return self._renderer.pixels self._window.event_loop(tick_func=tick) self._window.close()
dm_control-main
dm_control/viewer/application.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 of the viewer.py module.""" from absl.testing import absltest from dm_control.mujoco.wrapper.mjbindings import enums from dm_control.viewer import util from dm_control.viewer import viewer import mock class ViewerTest(absltest.TestCase): def setUp(self): super().setUp() self.viewport = mock.MagicMock() self.mouse = mock.MagicMock() self.keyboard = mock.MagicMock() self.viewer = viewer.Viewer(self.viewport, self.mouse, self.keyboard) self.viewer._render_settings = mock.MagicMock() self.physics = mock.MagicMock() self.renderer = mock.MagicMock() self.renderer.priority_components = util.QuietSet() def _extract_bind_call_args(self, bind_mock): call_args = [] for calls in bind_mock.call_args_list: args = calls[0] if len(args) == 2: call_args.append(args[1]) return call_args def test_initialize_creates_components(self): with mock.patch(viewer.__name__ + '.renderer'): self.viewer.initialize(self.physics, self.renderer, touchpad=False) self.assertIsNotNone(self.viewer._camera) self.assertIsNotNone(self.viewer._manipulator) self.assertIsNotNone(self.viewer._free_camera) self.assertIsNotNone(self.viewer._camera_select) self.assertEqual(self.renderer, self.viewer._renderer) def test_initialize_creates_touchpad_specific_input_mapping(self): self.viewer._input_map = mock.MagicMock() with mock.patch(viewer.__name__ + '.renderer'): self.viewer.initialize(self.physics, self.renderer, touchpad=True) call_args = self._extract_bind_call_args(self.viewer._input_map.bind) self.assertIn(viewer._MOVE_OBJECT_VERTICAL_TOUCHPAD, call_args) self.assertIn(viewer._MOVE_OBJECT_HORIZONTAL_TOUCHPAD, call_args) self.assertIn(viewer._ROTATE_OBJECT_TOUCHPAD, call_args) self.assertIn(viewer._PAN_CAMERA_VERTICAL_TOUCHPAD, call_args) self.assertIn(viewer._PAN_CAMERA_HORIZONTAL_TOUCHPAD, call_args) def test_initialize_create_mouse_specific_input_mapping(self): self.viewer._input_map = mock.MagicMock() with mock.patch(viewer.__name__ + '.renderer'): self.viewer.initialize(self.physics, self.renderer, touchpad=False) call_args = self._extract_bind_call_args(self.viewer._input_map.bind) self.assertIn(viewer._MOVE_OBJECT_VERTICAL_MOUSE, call_args) self.assertIn(viewer._MOVE_OBJECT_HORIZONTAL_MOUSE, call_args) self.assertIn(viewer._ROTATE_OBJECT_MOUSE, call_args) self.assertIn(viewer._PAN_CAMERA_VERTICAL_MOUSE, call_args) self.assertIn(viewer._PAN_CAMERA_HORIZONTAL_MOUSE, call_args) def test_initialization_flushes_old_input_map(self): self.viewer._input_map = mock.MagicMock() with mock.patch(viewer.__name__ + '.renderer'): self.viewer.initialize(self.physics, self.renderer, touchpad=False) self.viewer._input_map.clear_bindings.assert_called_once() def test_deinitialization_deletes_components(self): self.viewer._camera = mock.MagicMock() self.viewer._manipulator = mock.MagicMock() self.viewer._free_camera = mock.MagicMock() self.viewer._camera_select = mock.MagicMock() self.viewer._renderer = mock.MagicMock() self.viewer.deinitialize() self.assertIsNone(self.viewer._camera) self.assertIsNone(self.viewer._manipulator) self.assertIsNone(self.viewer._free_camera) self.assertIsNone(self.viewer._camera_select) self.assertIsNone(self.viewer._renderer) def test_deinitialization_flushes_old_input_map(self): self.viewer._input_map = mock.MagicMock() self.viewer.deinitialize() self.viewer._input_map.clear_bindings.assert_called_once() def test_rendering_uninitialized(self): self.viewer.render() # nothing crashes def test_zoom_to_scene_uninitialized(self): self.viewer.zoom_to_scene() # nothing crashes def test_rendering(self): self.viewer._camera = mock.MagicMock() self.viewer._renderer = mock.MagicMock() self.viewer.render() self.viewer._camera.render.assert_called_once_with(self.viewer.perturbation) self.viewer._renderer.render.assert_called_once() def test_applying_render_settings_before_rendering_a_scene(self): self.viewer._camera = mock.MagicMock() self.viewer._renderer = mock.MagicMock() self.viewer.render() self.viewer._render_settings.apply_settings.assert_called_once() def test_zoom_to_scene(self): self.viewer._camera = mock.MagicMock() self.viewer.zoom_to_scene() self.viewer._camera.zoom_to_scene.assert_called_once() def test_retrieving_perturbation(self): object_perturbation = mock.MagicMock() self.viewer._manipulator = mock.MagicMock() self.viewer._manipulator.perturbation = object_perturbation self.assertEqual(object_perturbation, self.viewer.perturbation) def test_retrieving_perturbation_without_manipulator(self): self.viewer._manipulator = None self.assertEqual(self.viewer._null_perturbation, self.viewer.perturbation) def test_retrieving_perturbation_without_selected_object(self): self.viewer._manipulator = mock.MagicMock() self.viewer._manipulator.perturbation = None self.assertEqual(self.viewer._null_perturbation, self.viewer.perturbation) class CameraSelectorTest(absltest.TestCase): def setUp(self): super().setUp() self.camera = mock.MagicMock() self.model = mock.MagicMock() self.free_camera = mock.MagicMock() self.model.ncam = 2 options = { 'camera': self.camera, 'model': self.model, 'free_camera': self.free_camera } self.controller = viewer.CameraSelector(**options) def test_activating_freelook_camera_by_default(self): self.assertEqual(self.controller._free_ctrl, self.controller._active_ctrl) def test_cycling_forward_through_cameras(self): self.controller.select_next() self.assertIsNone(self.controller._active_ctrl) self.controller._free_ctrl.deactivate.assert_called_once() self.controller._free_ctrl.reset_mock() self.controller._camera.set_fixed_mode.assert_called_once_with(0) self.controller._camera.reset_mock() self.controller.select_next() self.assertIsNone(self.controller._active_ctrl) self.controller._camera.set_fixed_mode.assert_called_once_with(1) self.controller._camera.reset_mock() self.controller.select_next() self.assertEqual(self.controller._free_ctrl, self.controller._active_ctrl) self.controller._free_ctrl.activate.assert_called_once() def test_cycling_backwards_through_cameras(self): self.controller.select_previous() self.assertIsNone(self.controller._active_ctrl) self.controller._free_ctrl.deactivate.assert_called_once() self.controller._free_ctrl.reset_mock() self.controller._camera.set_fixed_mode.assert_called_once_with(1) self.controller._camera.reset_mock() self.controller.select_previous() self.assertIsNone(self.controller._active_ctrl) self.controller._camera.set_fixed_mode.assert_called_once_with(0) self.controller._camera.reset_mock() self.controller.select_previous() self.assertEqual(self.controller._free_ctrl, self.controller._active_ctrl) self.controller._free_ctrl.activate.assert_called_once() def test_controller_activation(self): old_controller = mock.MagicMock() new_controller = mock.MagicMock() self.controller._active_ctrl = old_controller self.controller._activate(new_controller) old_controller.deactivate.assert_called_once() new_controller.activate.assert_called_once() def test_controller_activation_not_repeated_for_already_active_one(self): controller = mock.MagicMock() self.controller._active_ctrl = controller self.controller._activate(controller) self.assertEqual(0, controller.deactivate.call_count) self.assertEqual(0, controller.activate.call_count) class FreeCameraControllerTest(absltest.TestCase): def setUp(self): super().setUp() self.viewport = mock.MagicMock() self.camera = mock.MagicMock() self.mouse = mock.MagicMock() self.selection_service = mock.MagicMock() options = { 'camera': self.camera, 'viewport': self.viewport, 'pointer': self.mouse, 'selection_service': self.selection_service } self.controller = viewer.FreeCameraController(**options) self.controller._action = mock.MagicMock() def test_activation_while_not_in_tracking_mode(self): self.controller._tracked_body_idx = -1 self.controller.activate() self.camera.set_freelook_mode.assert_called_once() def test_activation_while_in_tracking_mode(self): self.controller._tracked_body_idx = 1 self.controller.activate() self.camera.set_tracking_mode.assert_called_once_with(1) def test_activation_and_deactivation_flag(self): self.controller.activate() self.assertTrue(self.controller._active) self.controller.deactivate() self.assertFalse(self.controller._active) def test_vertical_panning_camera_with_active_controller(self): self.controller._active = True self.controller.set_pan_vertical_mode(True) self.controller._action.begin.assert_called_once_with( enums.mjtMouse.mjMOUSE_MOVE_V) self.controller.set_pan_vertical_mode(False) self.controller._action.end.assert_called_once_with( enums.mjtMouse.mjMOUSE_MOVE_V) def test_vertical_panning_camera_with_inactive_controller(self): self.controller._active = False self.controller.set_pan_vertical_mode(True) self.assertEqual(0, self.controller._action.begin.call_count) self.controller.set_pan_vertical_mode(False) self.assertEqual(0, self.controller._action.end.call_count) def test_horizontal_panning_camera_with_active_controller(self): self.controller._active = True self.controller.set_pan_horizontal_mode(True) self.controller._action.begin.assert_called_once_with( enums.mjtMouse.mjMOUSE_MOVE_H) self.controller.set_pan_horizontal_mode(False) self.controller._action.end.assert_called_once_with( enums.mjtMouse.mjMOUSE_MOVE_H) def test_horizontal_panning_camera_with_inactive_controller(self): self.controller._active = False self.controller.set_pan_horizontal_mode(True) self.assertEqual(0, self.controller._action.begin.call_count) self.controller.set_pan_horizontal_mode(False) self.assertEqual(0, self.controller._action.end.call_count) def test_rotating_camera_with_active_controller(self): self.controller._active = True self.controller.set_rotate_mode(True) self.controller._action.begin.assert_called_once_with( enums.mjtMouse.mjMOUSE_ROTATE_H) self.controller.set_rotate_mode(False) self.controller._action.end.assert_called_once_with( enums.mjtMouse.mjMOUSE_ROTATE_H) def test_rotating_camera_with_inactive_controller(self): self.controller._active = False self.controller.set_rotate_mode(True) self.assertEqual(0, self.controller._action.begin.call_count) self.controller.set_rotate_mode(False) self.assertEqual(0, self.controller._action.end.call_count) def test_centering_with_active_controller(self): self.controller._active = True self.camera.raycast.return_value = 1, 2 self.controller.center() self.camera.raycast.assert_called_once() def test_centering_with_inactive_controller(self): self.controller._active = False self.controller.center() self.assertEqual(0, self.camera.raycast.call_count) def test_moving_mouse_moves_camera(self): position = [100, 200] translation = [1, 0] viewport_space_translation = [2, 0] action = 1 self.viewport.screen_to_viewport.return_value = viewport_space_translation self.controller._action.in_progress = True self.controller._action.watermark = action self.controller.on_move(position, translation) self.viewport.screen_to_viewport.assert_called_once_with(translation) self.camera.move.assert_called_once_with(action, viewport_space_translation) def test_mouse_move_doesnt_work_without_an_action_selected(self): self.controller._action.in_progress = False self.controller.on_move([], []) self.assertEqual(0, self.camera.move.call_count) def test_zoom_with_active_controller(self): self.controller._active = True expected_zoom_vector = [0, -0.05] self.controller.zoom(1.) self.camera.move.assert_called_once_with( enums.mjtMouse.mjMOUSE_ZOOM, expected_zoom_vector) def test_zoom_with_inactive_controller(self): self.controller._active = False self.controller.zoom(1.) self.assertEqual(0, self.camera.move.call_count) def test_tracking_with_active_controller(self): self.controller._active = True selected_body_id = 5 self.selection_service.selected_body_id = selected_body_id self.controller._tracked_body_idx = -1 self.controller.track() self.assertEqual(self.controller._tracked_body_idx, selected_body_id) self.camera.set_tracking_mode.assert_called_once_with(selected_body_id) def test_tracking_with_inactive_controller(self): self.controller._active = False selected_body_id = 5 self.selection_service.selected_body_id = selected_body_id self.controller.track() self.assertEqual(self.controller._tracked_body_idx, -1) self.assertEqual(0, self.camera.set_tracking_mode.call_count) def test_free_look_mode_with_active_controller(self): self.controller._active = True self.controller._tracked_body_idx = 5 self.controller.free_look() self.assertEqual(self.controller._tracked_body_idx, -1) self.camera.set_freelook_mode.assert_called_once() def test_free_look_mode_with_inactive_controller(self): self.controller._active = False self.controller._tracked_body_idx = 5 self.controller.free_look() self.assertEqual(self.controller._tracked_body_idx, 5) self.assertEqual(0, self.camera.set_freelook_mode.call_count) class ManipulationControllerTest(absltest.TestCase): def setUp(self): super().setUp() self.viewport = mock.MagicMock() self.camera = mock.MagicMock() self.mouse = mock.MagicMock() options = { 'camera': self.camera, 'viewport': self.viewport, 'pointer': self.mouse, } self.controller = viewer.ManipulationController(**options) self.body_id = 1 self.click_pos_on_body = [1, 2, 3] self.camera.raycast.return_value = (self.body_id, self.click_pos_on_body) def test_selecting_a_body(self): self.camera.raycast.return_value = (self.body_id, self.click_pos_on_body) self.controller.select() self.assertIsNotNone(self.controller._perturb) def test_selecting_empty_space_cancels_selection(self): self.camera.raycast.return_value = (-1, None) self.controller.select() self.assertIsNone(self.controller._perturb) def test_vertical_movement_operation(self): self.controller._perturb = mock.MagicMock() self.controller.set_move_vertical_mode(True) self.controller._perturb.start_move.assert_called_once() self.assertEqual(enums.mjtMouse.mjMOUSE_MOVE_V, self.controller._perturb.start_move.call_args[0][0]) self.controller.set_move_vertical_mode(False) self.controller._perturb.end_move.assert_called_once() def test_horzontal_movement_operation(self): self.controller._perturb = mock.MagicMock() self.controller.set_move_horizontal_mode(True) self.controller._perturb.start_move.assert_called_once() self.assertEqual(enums.mjtMouse.mjMOUSE_MOVE_H, self.controller._perturb.start_move.call_args[0][0]) self.controller.set_move_horizontal_mode(False) self.controller._perturb.end_move.assert_called_once() def test_rotation_operation(self): self.controller._perturb = mock.MagicMock() self.controller.set_rotate_mode(True) self.controller._perturb.start_move.assert_called_once() self.assertEqual(enums.mjtMouse.mjMOUSE_ROTATE_H, self.controller._perturb.start_move.call_args[0][0]) self.controller.set_rotate_mode(False) self.controller._perturb.end_move.assert_called_once() def test_every_action_generates_a_fresh_grab_pos(self): some_action = 0 self.controller._perturb = mock.MagicMock() self.controller._update_action(some_action) self.camera.raycast.assert_called_once() def test_actions_not_started_without_object_selected(self): some_action = 0 self.controller._perturb = None self.controller._update_action(some_action) self.assertEqual(0, self.camera.raycast.call_count) def test_on_move_requires_an_action_to_be_started_first(self): self.controller._perturb = mock.MagicMock() self.controller._action = mock.MagicMock() self.controller._action.in_progress = False self.controller.on_move([], []) self.assertEqual(0, self.controller._perturb.tick_move.call_count) def test_dragging_selected_object_moves_it(self): screen_pos = [1, 2] screen_translation = [3, 4] viewport_offset = [5, 6] self.controller._perturb = mock.MagicMock() self.controller._action = mock.MagicMock() self.controller._action.in_progress = True self.viewport.screen_to_viewport.return_value = viewport_offset self.controller.on_move(screen_pos, screen_translation) self.viewport.screen_to_viewport.assert_called_once_with(screen_translation) self.controller._perturb.tick_move.assert_called_once_with(viewport_offset) def test_operations_require_object_to_be_selected(self): self.controller._perturb = None # No exceptions should be raised. self.controller.set_move_vertical_mode(True) self.controller.set_move_vertical_mode(False) self.controller.set_move_horizontal_mode(True) self.controller.set_move_horizontal_mode(False) self.controller.set_rotate_mode(True) self.controller.set_rotate_mode(False) self.controller.on_move([1, 2], [3, 4]) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/viewer/viewer_test.py
# Copyright 2018-2019 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Runtime tests.""" import collections from absl.testing import absltest from absl.testing import parameterized from dm_control.viewer import runtime import dm_env from dm_env import specs import mock import numpy as np class RuntimeStateMachineTest(parameterized.TestCase): def setUp(self): super().setUp() env = mock.MagicMock() env.action_spec.return_value = specs.BoundedArray((1,), np.float64, -1, 1) self.runtime = runtime.Runtime(env, mock.MagicMock()) self.runtime._start = mock.MagicMock() self.runtime.get_time = mock.MagicMock() self.runtime.get_time.return_value = 0 self.runtime._step_simulation = mock.MagicMock(return_value=False) def test_initial_state(self): self.assertEqual(self.runtime._state, runtime.State.START) def test_successful_starting(self): self.runtime._start.return_value = True self.runtime._state = runtime.State.START self.runtime.tick(0, False) self.assertEqual(self.runtime._state, runtime.State.RUNNING) self.runtime._start.assert_called_once() self.runtime._step_simulation.assert_called_once() def test_failure_during_start(self): self.runtime._start.return_value = False self.runtime._state = runtime.State.START self.runtime.tick(0, False) self.assertEqual(self.runtime._state, runtime.State.STOPPED) self.runtime._start.assert_called_once() self.runtime._step_simulation.assert_not_called() def test_restarting(self): self.runtime._state = runtime.State.RUNNING self.runtime.restart() self.runtime.tick(0, False) self.assertEqual(self.runtime._state, runtime.State.RUNNING) self.runtime._start.assert_called_once() self.runtime._step_simulation.assert_called_once() def test_running(self): self.runtime._state = runtime.State.RUNNING self.runtime.tick(0, False) self.assertEqual(self.runtime._state, runtime.State.RUNNING) self.runtime._step_simulation.assert_called_once() def test_ending_a_running_episode(self): self.runtime._state = runtime.State.RUNNING self.runtime._step_simulation.return_value = True self.runtime.tick(0, False) self.assertEqual(self.runtime._state, runtime.State.STOPPED) self.runtime._step_simulation.assert_called_once() def test_calling_stop_has_immediate_effect_on_state(self): self.runtime.stop() self.assertEqual(self.runtime._state, runtime.State.STOPPED) @parameterized.parameters(runtime.State.RUNNING, runtime.State.RESTARTING,) def test_states_affected_by_stop(self, state): self.runtime._state = state self.runtime.stop() self.assertEqual(self.runtime._state, runtime.State.STOPPED) def test_notifying_listeners_about_successful_start(self): callback = mock.MagicMock() self.runtime.on_episode_begin += [callback] self.runtime._start.return_value = True self.runtime._state = runtime.State.START self.runtime.tick(0, False) callback.assert_called_once() def test_listeners_not_notified_when_start_fails(self): callback = mock.MagicMock() self.runtime.on_episode_begin += [callback] self.runtime._start.return_value = False self.runtime._state = runtime.State.START self.runtime.tick(0, False) callback.assert_not_called() class RuntimeSingleStepTest(parameterized.TestCase): def setUp(self): super().setUp() env = mock.MagicMock(spec=dm_env.Environment) env.action_spec.return_value = specs.BoundedArray((1,), np.float64, -1, 1) self.runtime = runtime.Runtime(env, mock.MagicMock()) self.runtime._step = mock.MagicMock() self.runtime._step.return_value = False def test_when_running(self): self.runtime._state = runtime.State.RUNNING self.runtime.single_step() self.assertEqual(self.runtime._state, runtime.State.RUNNING) self.runtime._step.assert_called_once() def test_ending_episode(self): self.runtime._state = runtime.State.RUNNING self.runtime._step.return_value = True self.runtime.single_step() self.assertEqual(self.runtime._state, runtime.State.STOP) self.runtime._step.assert_called_once() @parameterized.parameters(runtime.State.START, runtime.State.STOP, runtime.State.STOPPED, runtime.State.RESTARTING) def test_runs_only_in_running_state(self, state): self.runtime._state = state self.runtime.single_step() self.assertEqual(self.runtime._state, state) self.assertEqual(0, self.runtime._step.call_count) class RuntimeTest(absltest.TestCase): def setUp(self): super().setUp() env = mock.MagicMock(spec=dm_env.Environment) env.action_spec.return_value = specs.BoundedArray((1,), np.float64, -1, 1) self.runtime = runtime.Runtime(env, mock.MagicMock()) self.runtime._step_paused = mock.MagicMock() self.runtime._step = mock.MagicMock(return_value=True) self.runtime.get_time = mock.MagicMock(return_value=0) self.time_step = 1e-2 def set_loop(self, num_iterations, finish_after=0): finish_after = finish_after or num_iterations + 1 self.delta_time = self.time_step / float(num_iterations) self.time = 0 self.iteration = 0 def fakeget_time(): return self.time def fake_step(): self.time += self.delta_time self.iteration += 1 return self.iteration >= finish_after self.runtime._step = mock.MagicMock(side_effect=fake_step) self.runtime.get_time = mock.MagicMock(side_effect=fakeget_time) def test_num_step_calls(self): expected_call_count = 5 self.set_loop(num_iterations=expected_call_count) finished = self.runtime._step_simulation(self.time_step, False) self.assertFalse(finished) self.assertEqual(expected_call_count, self.runtime._step.call_count) def test_finishing_if_episode_ends(self): num_iterations = 5 finish_after = 2 self.set_loop(num_iterations=num_iterations, finish_after=finish_after) finished = self.runtime._step_simulation(self.time_step, False) self.assertTrue(finished) self.assertEqual(finish_after, self.runtime._step.call_count) def test_stepping_paused(self): self.runtime._step_simulation(0, True) self.runtime._step_paused.assert_called_once() self.assertEqual(0, self.runtime._step.call_count) def test_physics_step_takes_less_time_than_tick(self): self.physics_time_step = runtime._DEFAULT_MAX_SIM_STEP * 0.5 self.physics_time = 0.0 def mock_get_time(): return self.physics_time def mock_step(): self.physics_time += self.physics_time_step self.runtime._step = mock.MagicMock(side_effect=mock_step) self.runtime.get_time = mock.MagicMock(side_effect=mock_get_time) self.runtime._step_simulation( time_elapsed=runtime._DEFAULT_MAX_SIM_STEP, paused=False) self.assertEqual(2, self.runtime._step.call_count) def test_physics_step_takes_more_time_than_tick(self): self.physics_time_step = runtime._DEFAULT_MAX_SIM_STEP * 2 self.physics_time = 0.0 def mock_get_time(): return self.physics_time def mock_step(): self.physics_time += self.physics_time_step self.runtime._step = mock.MagicMock(side_effect=mock_step) self.runtime.get_time = mock.MagicMock(side_effect=mock_get_time) # Simulates after the first frame self.runtime._step_simulation( time_elapsed=runtime._DEFAULT_MAX_SIM_STEP, paused=False) self.assertEqual(1, self.runtime._step.call_count) self.runtime._step.reset_mock() # Then pauses for one frame to let the internal timer catch up with the # simulation timer. self.runtime._step_simulation( time_elapsed=runtime._DEFAULT_MAX_SIM_STEP, paused=False) self.assertEqual(0, self.runtime._step.call_count) # Resumes simulation on the subsequent frame. self.runtime._step_simulation( time_elapsed=runtime._DEFAULT_MAX_SIM_STEP, paused=False) self.assertEqual(1, self.runtime._step.call_count) def test_updating_tracked_time_during_start(self): invalid_time = 20 self.runtime.get_time = mock.MagicMock(return_value=invalid_time) valid_time = 2 def mock_start(): self.runtime.get_time = mock.MagicMock(return_value=valid_time) return True self.runtime._start = mock.MagicMock(side_effect=mock_start) self.runtime._step_simulation = mock.MagicMock() self.runtime.tick(time_elapsed=runtime._DEFAULT_MAX_SIM_STEP, paused=False) self.assertEqual(valid_time, self.runtime._tracked_simulation_time) def test_error_logger_forward_errors_to_listeners(self): callback = mock.MagicMock() self.runtime.on_error += [callback] with self.runtime._error_logger: raise Exception('error message') callback.assert_called_once() class EnvironmentRuntimeTest(parameterized.TestCase): def setUp(self): super().setUp() self.observation = mock.MagicMock() self.env = mock.MagicMock(spec=dm_env.Environment) self.env.physics = mock.MagicMock() self.env.step = mock.MagicMock() self.env.action_spec.return_value = specs.BoundedArray( (1,), np.float64, -1, 1) self.policy = mock.MagicMock() self.actions = mock.MagicMock() self.runtime = runtime.Runtime(self.env, self.policy) def test_start(self): with mock.patch(runtime.__name__ + '.mujoco'): result = self.runtime._start() self.assertTrue(result) self.env.reset.assert_called_once() self.policy.assert_not_called() def test_step_with_policy(self): time_step = mock.Mock(spec=dm_env.TimeStep) self.runtime._time_step = time_step self.runtime._step() self.policy.assert_called_once_with(time_step) self.env.step.assert_called_once_with(self.policy.return_value) def test_step_without_policy(self): with mock.patch( runtime.__name__ + '._get_default_action') as mock_get_default_action: this_runtime = runtime.Runtime(environment=self.env, policy=None) this_runtime._step() self.env.step.assert_called_once_with(mock_get_default_action.return_value) def test_stepping_paused(self): with mock.patch(runtime.__name__ + '.mujoco') as mujoco: self.runtime._step_paused() mujoco.mj_forward.assert_called_once() def test_get_time(self): expected_time = 20 self.env.physics = mock.MagicMock() self.env.physics.data = mock.MagicMock() self.env.physics.data.time = expected_time self.assertEqual(expected_time, self.runtime.get_time()) def test_tracking_physics_instance_changes(self): callback = mock.MagicMock() self.runtime.on_physics_changed += [callback] def begin_episode_and_reload_physics(): self.env.physics.data.ptr = mock.MagicMock() self.env.reset.side_effect = begin_episode_and_reload_physics self.runtime._start() callback.assert_called_once_with() def test_tracking_physics_instance_that_doesnt_change(self): callback = mock.MagicMock() self.runtime.on_physics_changed += [callback] self.runtime._start() callback.assert_not_called() def test_exception_thrown_during_start(self): def raise_exception(*unused_args, **unused_kwargs): raise Exception('test error message') self.runtime._env.reset.side_effect = raise_exception result = self.runtime._start() self.assertFalse(result) def test_exception_thrown_during_step(self): def raise_exception(*unused_args, **unused_kwargs): raise Exception('test error message') self.runtime._env.step.side_effect = raise_exception finished = self.runtime._step() self.assertTrue(finished) class DefaultActionFromSpecTest(parameterized.TestCase): def assertNestedArraysEqual(self, expected, actual): """Asserts that two potentially nested structures of arrays are equal.""" self.assertIs(type(actual), type(expected)) if isinstance(expected, (list, tuple)): self.assertIsInstance(actual, (list, tuple)) self.assertLen(actual, len(expected)) for expected_item, actual_item in zip(expected, actual): self.assertNestedArraysEqual(expected_item, actual_item) elif isinstance(expected, collections.abc.MutableMapping): keys_type = list if isinstance(expected, collections.OrderedDict) else set self.assertEqual(keys_type(actual.keys()), keys_type(expected.keys())) for key, expected_value in expected.items(): self.assertNestedArraysEqual(actual[key], expected_value) else: np.testing.assert_array_equal(expected, actual) _SHAPE = (2,) _DTYPE = np.float64 _ACTION = np.zeros(_SHAPE) _ACTION_SPEC = specs.BoundedArray(_SHAPE, np.float64, -1, 1) @parameterized.named_parameters( ('single_array', _ACTION_SPEC, _ACTION), ('tuple', (_ACTION_SPEC, _ACTION_SPEC), (_ACTION, _ACTION)), ('list', [_ACTION_SPEC, _ACTION_SPEC], (_ACTION, _ACTION)), ('dict', {'a': _ACTION_SPEC, 'b': _ACTION_SPEC}, {'a': _ACTION, 'b': _ACTION}), ('OrderedDict', collections.OrderedDict([('a', _ACTION_SPEC), ('b', _ACTION_SPEC)]), collections.OrderedDict([('a', _ACTION), ('b', _ACTION)])), ) def test_action_structure(self, action_spec, expected_action): self.assertNestedArraysEqual(expected_action, runtime._get_default_action(action_spec)) def test_ordered_dict_action_structure_with_bad_ordering(self): reversed_spec = collections.OrderedDict([('a', self._ACTION_SPEC), ('b', self._ACTION_SPEC)]) expected_action = collections.OrderedDict([('b', self._ACTION), ('a', self._ACTION)]) with self.assertRaisesRegex( AssertionError, r"Lists differ: \['a', 'b'\] != \['b', 'a'\]"): self.assertNestedArraysEqual(expected_action, runtime._get_default_action(reversed_spec)) @parameterized.named_parameters( ('closed', specs.BoundedArray(_SHAPE, _DTYPE, minimum=1., maximum=2.), np.full(_SHAPE, fill_value=1.5, dtype=_DTYPE)), ('left_open', specs.BoundedArray(_SHAPE, _DTYPE, minimum=-np.inf, maximum=2.), np.full(_SHAPE, fill_value=2., dtype=_DTYPE)), ('right_open', specs.BoundedArray(_SHAPE, _DTYPE, minimum=1., maximum=np.inf), np.full(_SHAPE, fill_value=1., dtype=_DTYPE)), ('unbounded', specs.BoundedArray(_SHAPE, _DTYPE, minimum=-np.inf, maximum=np.inf), np.full(_SHAPE, fill_value=0., dtype=_DTYPE))) def test_action_spec_interval(self, action_spec, expected_action): self.assertNestedArraysEqual(expected_action, runtime._get_default_action(action_spec)) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/viewer/runtime_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. # ============================================================================ """Components and views that render custom images into Mujoco render frame.""" import abc import enum from dm_control.viewer import renderer import mujoco import numpy as np class PanelLocation(enum.Enum): TOP_LEFT = mujoco.mjtGridPos.mjGRID_TOPLEFT.value TOP_RIGHT = mujoco.mjtGridPos.mjGRID_TOPRIGHT.value BOTTOM_LEFT = mujoco.mjtGridPos.mjGRID_BOTTOMLEFT.value BOTTOM_RIGHT = mujoco.mjtGridPos.mjGRID_BOTTOMRIGHT.value class BaseViewportView(metaclass=abc.ABCMeta): """Base abstract view class.""" @abc.abstractmethod def render(self, context, viewport, location): """Renders the view on screen. Args: context: MjrContext instance. viewport: Viewport instance. location: Value defined in PanelLocation enum. """ pass class ColumnTextModel(metaclass=abc.ABCMeta): """Data model that returns 2 columns of text.""" @abc.abstractmethod def get_columns(self): """Returns the text to display in two columns. Returns: Returns an iterable of tuples of 2 strings. Each tuple has format (left_column_label, right_column_label). """ pass class ColumnTextView(BaseViewportView): """A view displayed in Mujoco render window.""" def __init__(self, model): """Instance initializer. Args: model: Instance of ColumnTextModel. """ self._model = model def render(self, context, viewport, location): """Renders the overlay on screen. Args: context: MjrContext instance. viewport: Viewport instance. location: Value defined in PanelLocation enum. """ columns = self._model.get_columns() if not columns: return columns = np.asarray(columns) left_column = '\n'.join(columns[:, 0]) right_column = '\n'.join(columns[:, 1]) mujoco.mjr_overlay(mujoco.mjtFont.mjFONT_NORMAL, location.value, viewport.mujoco_rect, left_column, right_column, context.ptr) class MujocoDepthBuffer(renderer.Component): """Displays the contents of the scene's depth buffer.""" def __init__(self): self._depth_buffer = np.zeros((1, 1), np.float32) def render(self, context, viewport): """Renders the overlay on screen. Args: context: MjrContext instance. viewport: MJRRECT instance. """ width_adjustment = viewport.width % 4 rect_shape = (viewport.width - width_adjustment, viewport.height) if self._depth_buffer is None or self._depth_buffer.shape != rect_shape: self._depth_buffer = np.zeros( (viewport.width, viewport.height), np.float32) mujoco.mjr_readPixels(None, self._depth_buffer, viewport.mujoco_rect, context.ptr) # Subsample by 4, convert to RGB, and cast to unsigned bytes. depth_rgb = np.repeat(self._depth_buffer[::4, ::4, None] * 255, 3, -1).astype(np.ubyte) pos = mujoco.MjrRect( int(3 * viewport.width / 4) + width_adjustment, 0, int(viewport.width / 4), int(viewport.height / 4)) mujoco.mjr_drawPixels(depth_rgb, None, pos, context.ptr) class ViewportLayout(renderer.Component): """Layout manager for the render viewport. Allows to create a viewport layout by injecting renderer component even in absence of a renderer, and then easily reattach it between renderers. """ def __init__(self): """Instance initializer.""" self._views = dict() def __len__(self): return len(self._views) def __contains__(self, key): value = self._views.get(key, None) return value is not None def add(self, view, location): """Adds a new view. Args: view: renderer.BaseViewportView instance. location: Value defined in PanelLocation enum, location of the view in the viewport. """ if not isinstance(view, BaseViewportView): raise TypeError( 'View added to this layout needs to implement BaseViewportView.') self._views[view] = location def remove(self, view): """Removes a view. Args: view: renderer.BaseViewportView instance. """ self._views.pop(view, None) def clear(self): """Removes all attached components.""" self._views = dict() def render(self, context, viewport): """Renders the overlay on screen. Args: context: MjrContext instance. viewport: MJRRECT instance. """ for view, location in self._views.items(): view.render(context, viewport, location)
dm_control-main
dm_control/viewer/views.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 the base windowing system.""" from absl.testing import absltest from dm_control.viewer import user_input import mock # pylint: disable=g-import-not-at-top _OPEN_GL_MOCK = mock.MagicMock() _MOCKED_MODULES = { 'OpenGL': _OPEN_GL_MOCK, 'OpenGL.GL': _OPEN_GL_MOCK, } with mock.patch.dict('sys.modules', _MOCKED_MODULES): from dm_control.viewer.gui import base # pylint: enable=g-import-not-at-top _EPSILON = 1e-7 @mock.patch(base.__name__ + '.time') class DoubleClickDetectorTest(absltest.TestCase): def setUp(self): super().setUp() self.detector = base.DoubleClickDetector() self.double_click_event = (user_input.MOUSE_BUTTON_LEFT, user_input.PRESS) def test_two_rapid_clicks_yield_double_click_event(self, mock_time): mock_time.time.return_value = 0 self.assertFalse(self.detector.process(*self.double_click_event)) mock_time.time.return_value = base._DOUBLE_CLICK_INTERVAL - _EPSILON self.assertTrue(self.detector.process(*self.double_click_event)) def test_two_slow_clicks_dont_yield_double_click_event(self, mock_time): mock_time.time.return_value = 0 self.assertFalse(self.detector.process(*self.double_click_event)) mock_time.time.return_value = base._DOUBLE_CLICK_INTERVAL self.assertFalse(self.detector.process(*self.double_click_event)) def test_sequence_of_slow_clicks_followed_by_fast_click(self, mock_time): click_times = [(0., False), (base._DOUBLE_CLICK_INTERVAL * 2., False), (base._DOUBLE_CLICK_INTERVAL * 3. - _EPSILON, True)] for click_time, result in click_times: mock_time.time.return_value = click_time self.assertEqual(result, self.detector.process(*self.double_click_event)) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/viewer/gui/base_test.py
# Copyright 2018 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Viewer's windowing systems.""" from dm_control import _render # pylint: disable=g-import-not-at-top # pylint: disable=invalid-name RenderWindow = None try: from dm_control.viewer.gui import glfw_gui RenderWindow = glfw_gui.GlfwWindow except ImportError: pass if RenderWindow is None: def ErrorRenderWindow(*args, **kwargs): del args, kwargs raise ImportError( 'Cannot create a window because no windowing system could be imported') RenderWindow = ErrorRenderWindow del _render
dm_control-main
dm_control/viewer/gui/__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. # ============================================================================ """Windowing system that uses GLFW library.""" import functools from dm_control import _render from dm_control._render import glfw_renderer from dm_control.viewer import util from dm_control.viewer.gui import base from dm_control.viewer.gui import fullscreen_quad import glfw import numpy as np def _check_valid_backend(func): """Decorator which checks that GLFW is being used for offscreen rendering.""" @functools.wraps(func) def wrapped_func(*args, **kwargs): if _render.BACKEND != 'glfw': raise RuntimeError( '{func} may only be called if using GLFW for offscreen rendering, ' 'got `render.BACKEND={backend!r}`.'.format( func=func, backend=_render.BACKEND)) return func(*args, **kwargs) return wrapped_func class DoubleBufferedGlfwContext(glfw_renderer.GLFWContext): """Custom context manager for the GLFW based GUI.""" def __init__(self, width, height, title): self._title = title super().__init__(max_width=width, max_height=height) @_check_valid_backend def _platform_init(self, width, height): glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.VISIBLE, 1) glfw.window_hint(glfw.DOUBLEBUFFER, 1) self._context = glfw.create_window(width, height, self._title, None, None) self._destroy_window = glfw.destroy_window @property def window(self): return self._context class GlfwKeyboard(base.InputEventsProcessor): """Glfw keyboard device handler. Handles the keyboard input in a thread-safe way, and forwards the events to the registered callbacks. Attributes: on_key: Observable subject triggered when a key event is triggered. Expects a callback with signature: (key, scancode, activity, modifiers) """ def __init__(self, context): super().__init__() with context.make_current() as ctx: ctx.call(glfw.set_key_callback, context.window, self._handle_key_event) self.on_key = util.QuietSet() def _handle_key_event(self, window, key, scancode, activity, mods): """Broadcasts the notification to registered listeners. Args: window: The window that received the event. key: ID representing the key, a glfw.KEY_ constant. scancode: The system-specific scancode of the key. activity: glfw.PRESS, glfw.RELEASE or glfw.REPEAT. mods: Bit field describing which modifier keys were held down, such as Alt or Shift. """ del window, scancode self.add_event(self.on_key, key, activity, mods) class GlfwMouse(base.InputEventsProcessor): """Glfw mouse device handler. Handles the mouse input in a thread-safe way, forwarding the events to the registered callbacks. Attributes: on_move: Observable subject triggered when a mouse move is detected. Expects a callback with signature (position, translation). on_click: Observable subject triggered when a mouse click is detected. Expects a callback with signature (button, action, modifiers). on_double_click: Observable subject triggered when a mouse double click is detected. Expects a callback with signature (button, modifiers). on_scroll: Observable subject triggered when a mouse scroll is detected. Expects a callback with signature (scroll_value). """ def __init__(self, context): super().__init__() self.on_move = util.QuietSet() self.on_click = util.QuietSet() self.on_double_click = util.QuietSet() self.on_scroll = util.QuietSet() self._double_click_detector = base.DoubleClickDetector() with context.make_current() as ctx: framebuffer_width, window_width = ctx.call( self._glfw_setup, context.window) self._scale = framebuffer_width * 1.0 / window_width self._last_mouse_pos = np.zeros(2, int) self._double_clicks = {} def _glfw_setup(self, window): glfw.set_cursor_pos_callback(window, self._handle_move) glfw.set_mouse_button_callback(window, self._handle_button) glfw.set_scroll_callback(window, self._handle_scroll) framebuffer_width, _ = glfw.get_framebuffer_size(window) window_width, _ = glfw.get_window_size(window) return framebuffer_width, window_width @property def position(self): return self._last_mouse_pos def _handle_move(self, window, x, y): """Mouse movement callback. Args: window: Window object from glfw. x: Horizontal position of mouse, in pixels. y: Vertical position of mouse, in pixels. """ del window position = np.array([x, y], int) * self._scale delta = position - self._last_mouse_pos self._last_mouse_pos = position self.add_event(self.on_move, position, delta) def _handle_button(self, window, button, act, mods): """Mouse button click event handler.""" del window self.add_event(self.on_click, button, act, mods) if self._double_click_detector.process(button, act): self.add_event(self.on_double_click, button, mods) def _handle_scroll(self, window, x_offset, y_offset): """Mouse wheel scroll event handler.""" del window, x_offset self.add_event(self.on_scroll, y_offset) class GlfwWindow: """A GLFW based application window. Attributes: on_files_drop: An observable subject, instance of util.QuietSet. Attached listeners, callables taking one argument, will be invoked every time the user drops files onto the window. The callable will be passed an iterable with dropped file paths. is_full_screen: Boolean, whether the window is currently full-screen. """ def __init__(self, width, height, title, context=None): """Instance initializer. Args: width: Initial window width, in pixels. height: Initial window height, in pixels. title: A string with a window title. context: (Optional) A `render.GLFWContext` instance. Raises: RuntimeError: If GLFW initialization or window initialization fails. """ super().__init__() self._context = context or DoubleBufferedGlfwContext(width, height, title) if not self._context.window: raise RuntimeError('Failed to create window') self._oldsize = None with self._context.make_current() as ctx: self._fullscreen_quad = ctx.call(self._glfw_setup, self._context.window) self.on_files_drop = util.QuietSet() self._keyboard = GlfwKeyboard(self._context) self._mouse = GlfwMouse(self._context) def _glfw_setup(self, window): glfw.set_drop_callback(window, self._handle_file_drop) return fullscreen_quad.FullscreenQuadRenderer() @property def shape(self): """Returns a tuple with the shape of the window, (width, height).""" with self._context.make_current() as ctx: return ctx.call(glfw.get_framebuffer_size, self._context.window) @property def position(self): """Returns a tuple with top-left window corner's coordinates, (x, y).""" with self._context.make_current() as ctx: return ctx.call(glfw.get_window_pos, self._context.window) @property def keyboard(self): """Returns a GlfwKeyboard instance associated with the window.""" return self._keyboard @property def mouse(self): """Returns a GlfwMouse instance associated with the window.""" return self._mouse def set_title(self, title): """Sets the window title. Args: title: A string, title of the window. """ with self._context.make_current() as ctx: ctx.call(glfw.set_window_title, self._context.window, title) def set_full_screen(self, enable): """Expands the main application window to full screen or minimizes it. Args: enable: Boolean flag, True expands the window to full-screen mode, False minimizes it to its former size. """ if enable == self.is_full_screen: return if enable: self._oldsize = list(self.position) + list(self.shape) def enable_full_screen(window): display = glfw.get_primary_monitor() videomode = glfw.get_video_mode(display) glfw.set_window_monitor(window, display, 0, 0, videomode[0][0], videomode[0][1], videomode[2]) with self._context.make_current() as ctx: ctx.call(enable_full_screen, self._context.window) else: with self._context.make_current() as ctx: ctx.call(glfw.set_window_monitor, self._context.window, None, self._oldsize[0], self._oldsize[1], self._oldsize[2], self._oldsize[3], 0) self._oldsize = None def toggle_full_screen(self): """Expands the main application window to full screen or minimizes it.""" show_full_screen = not self.is_full_screen self.set_full_screen(show_full_screen) @property def is_full_screen(self): return self._oldsize is not None def free(self): """Closes the deleted window.""" self.close() def event_loop(self, tick_func): """Runs the window's event loop. This is a blocking call that won't exit until the window is closed. Args: tick_func: A callable, function to call every frame. """ while not glfw.window_should_close(self._context.window): self.update(tick_func) def update(self, render_func): """Updates the window and renders a new image. Args: render_func: A callable returning a 3D numpy array of bytes (np.uint8), with dimensions (width, height, 3). """ pixels = render_func() with self._context.make_current() as ctx: ctx.call( self._update_gui_on_render_thread, self._context.window, pixels) self._mouse.process_events() self._keyboard.process_events() def _update_gui_on_render_thread(self, window, pixels): self._fullscreen_quad.render(pixels, self.shape) glfw.swap_buffers(window) glfw.poll_events() def close(self): """Closes the window and releases associated resources.""" if self._context is not None: self._context.free() self._context = None def _handle_file_drop(self, window, paths): """Handles events of user dropping files onto the window. Args: window: GLFW window handle (unused). paths: An iterable with paths of files dropped onto the window. """ del window for listener in list(self.on_files_drop): listener(paths) def __del__(self): self.free()
dm_control-main
dm_control/viewer/gui/glfw_gui.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. # ============================================================================ """OpenGL utility for rendering numpy arrays as images on a quad surface.""" import ctypes import numpy as np from OpenGL import GL from OpenGL.GL import shaders # This array contains packed position and texture cooridnates of a fullscreen # quad. # It contains definition of 4 vertices that will be rendered as a triangle # strip. Each vertex is described by a tuple: # (VertexPosition.X, VertexPosition.Y, TextureCoord.U, TextureCoord.V) _FULLSCREEN_QUAD_VERTEX_POSITONS_AND_TEXTURE_COORDS = np.array([ -1, -1, 0, 1, -1, 1, 0, 0, 1, -1, 1, 1, 1, 1, 1, 0], dtype=np.float32) _FLOATS_PER_XY = 2 _FLOATS_PER_VERTEX = 4 _SIZE_OF_FLOAT = ctypes.sizeof(ctypes.c_float) _VERTEX_SHADER = """ #version 120 attribute vec2 position; attribute vec2 uv; void main() { gl_Position = vec4(position, 0, 1); gl_TexCoord[0].st = uv; } """ _FRAGMENT_SHADER = """ #version 120 uniform sampler2D tex; void main() { gl_FragColor = texture2D(tex, gl_TexCoord[0].st); } """ _VAR_POSITION = 'position' _VAR_UV = 'uv' _VAR_TEXTURE_SAMPLER = 'tex' class FullscreenQuadRenderer: """Renders pixmaps on a fullscreen quad using OpenGL.""" def __init__(self): """Initializes the fullscreen quad renderer.""" GL.glClearColor(0, 0, 0, 0) self._init_geometry() self._init_texture() self._init_shaders() def _init_geometry(self): """Initializes the fullscreen quad geometry.""" vertex_buffer = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vertex_buffer) GL.glBufferData( GL.GL_ARRAY_BUFFER, _FULLSCREEN_QUAD_VERTEX_POSITONS_AND_TEXTURE_COORDS.nbytes, _FULLSCREEN_QUAD_VERTEX_POSITONS_AND_TEXTURE_COORDS, GL.GL_STATIC_DRAW) def _init_texture(self): """Initializes the texture storage.""" self._texture = GL.glGenTextures(1) GL.glBindTexture(GL.GL_TEXTURE_2D, self._texture) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) def _init_shaders(self): """Initializes the shaders used to render the textures fullscreen quad.""" vs = shaders.compileShader(_VERTEX_SHADER, GL.GL_VERTEX_SHADER) fs = shaders.compileShader(_FRAGMENT_SHADER, GL.GL_FRAGMENT_SHADER) self._shader = shaders.compileProgram(vs, fs) stride = _FLOATS_PER_VERTEX * _SIZE_OF_FLOAT var_position = GL.glGetAttribLocation(self._shader, _VAR_POSITION) GL.glVertexAttribPointer( var_position, 2, GL.GL_FLOAT, GL.GL_FALSE, stride, None) GL.glEnableVertexAttribArray(var_position) var_uv = GL.glGetAttribLocation(self._shader, _VAR_UV) uv_offset = ctypes.c_void_p(_FLOATS_PER_XY * _SIZE_OF_FLOAT) GL.glVertexAttribPointer( var_uv, 2, GL.GL_FLOAT, GL.GL_FALSE, stride, uv_offset) GL.glEnableVertexAttribArray(var_uv) self._var_texture_sampler = GL.glGetUniformLocation( self._shader, _VAR_TEXTURE_SAMPLER) def render(self, pixmap, viewport_shape): """Renders the pixmap on a fullscreen quad. Args: pixmap: A 3D numpy array of bytes (np.uint8), with dimensions (width, height, 3). viewport_shape: A tuple of two elements, (width, height). """ GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glViewport(0, 0, *viewport_shape) GL.glUseProgram(self._shader) GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, self._texture) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGB, pixmap.shape[1], pixmap.shape[0], 0, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, pixmap) GL.glUniform1i(self._var_texture_sampler, 0) GL.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, 4)
dm_control-main
dm_control/viewer/gui/fullscreen_quad.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 the GLFW based windowing system.""" import contextlib from absl.testing import absltest from dm_control.viewer import user_input import mock import numpy as np _OPEN_GL_MOCK = mock.MagicMock() _GLFW_MOCK = mock.MagicMock() _MOCKED_MODULES = { 'OpenGL': _OPEN_GL_MOCK, 'OpenGL.GL': _OPEN_GL_MOCK, 'glfw': _GLFW_MOCK, } with mock.patch.dict('sys.modules', _MOCKED_MODULES): from dm_control.viewer.gui import glfw_gui # pylint: disable=g-import-not-at-top glfw_gui.base.GL = _OPEN_GL_MOCK glfw_gui.base.shaders = _OPEN_GL_MOCK glfw_gui.glfw = _GLFW_MOCK # Pretend we are using GLFW for offscreen rendering so that the runtime backend # check will succeed. glfw_gui._render.BACKEND = 'glfw' _EPSILON = 1e-7 class GlfwKeyboardTest(absltest.TestCase): def setUp(self): super().setUp() _GLFW_MOCK.reset_mock() self.context = mock.MagicMock() self.handler = glfw_gui.GlfwKeyboard(self.context) self.events = [ (1, user_input.KEY_T, 't', user_input.PRESS, user_input.MOD_ALT), (1, user_input.KEY_T, 't', user_input.RELEASE, user_input.MOD_ALT), (1, user_input.KEY_A, 't', user_input.PRESS, 0)] self.listener = mock.MagicMock() self.handler.on_key += [self.listener] def test_single_event(self): self.handler._handle_key_event(*self.events[0]) self.handler.process_events() self.listener.assert_called_once_with(user_input.KEY_T, user_input.PRESS, user_input.MOD_ALT) def test_sequence_of_events(self): for event in self.events: self.handler._handle_key_event(*event) self.handler.process_events() self.assertEqual(3, self.listener.call_count) for event, call_args in zip(self.events, self.listener.call_args_list): expected_event = tuple([event[1]] + list(event[-2:])) self.assertEqual(expected_event, call_args[0]) class FakePassthroughRenderingContext: def __init__(self): self.window = 0 def call(self, func, *args): return func(*args) class GlfwMouseTest(absltest.TestCase): @contextlib.contextmanager def fake_make_current(self): yield FakePassthroughRenderingContext() def setUp(self): super().setUp() _GLFW_MOCK.reset_mock() _GLFW_MOCK.get_framebuffer_size = mock.MagicMock(return_value=(256, 256)) _GLFW_MOCK.get_window_size = mock.MagicMock(return_value=(256, 256)) self.window = mock.MagicMock() self.window.make_current = mock.MagicMock( side_effect=self.fake_make_current) self.handler = glfw_gui.GlfwMouse(self.window) def test_moving_mouse(self): def move_handler(position, translation): self.position = position self.translation = translation self.new_position = [100, 100] self.handler._last_mouse_pos = np.array([99, 101], int) self.handler.on_move += move_handler self.handler._handle_move(self.window, self.new_position[0], self.new_position[1]) self.handler.process_events() np.testing.assert_array_equal(self.new_position, self.position) np.testing.assert_array_equal([1, -1], self.translation) def test_button_click(self): def click_handler(button, action, modifiers): self.button = button self.action = action self.modifiers = modifiers self.handler.on_click += click_handler self.handler._handle_button(self.window, user_input.MOUSE_BUTTON_LEFT, user_input.PRESS, user_input.MOD_SHIFT) self.handler.process_events() self.assertEqual(user_input.MOUSE_BUTTON_LEFT, self.button) self.assertEqual(user_input.PRESS, self.action) self.assertEqual(user_input.MOD_SHIFT, self.modifiers) def test_scroll(self): def scroll_handler(position): self.position = position self.handler.on_scroll += scroll_handler x_value = 10 y_value = 20 self.handler._handle_scroll(self.window, x_value, y_value) self.handler.process_events() # x_value gets ignored, it's the y_value - the vertical scroll - we're # interested in. self.assertEqual(y_value, self.position) class GlfwWindowTest(absltest.TestCase): WIDTH = 10 HEIGHT = 20 @contextlib.contextmanager def fake_make_current(self): yield FakePassthroughRenderingContext() def setUp(self): super().setUp() _GLFW_MOCK.reset_mock() _GLFW_MOCK.get_video_mode.return_value = (None, None, 60) _GLFW_MOCK.get_framebuffer_size.return_value = (4, 5) _GLFW_MOCK.get_window_size.return_value = (self.WIDTH, self.HEIGHT) self.context = mock.MagicMock() self.context.make_current = mock.MagicMock( side_effect=self.fake_make_current) self.window = glfw_gui.GlfwWindow( self.WIDTH, self.HEIGHT, 'title', self.context) def test_window_shape(self): expected_shape = (self.WIDTH, self.HEIGHT) _GLFW_MOCK.get_framebuffer_size.return_value = expected_shape self.assertEqual(expected_shape, self.window.shape) def test_window_position(self): expected_position = (1, 2) _GLFW_MOCK.get_window_pos.return_value = expected_position self.assertEqual(expected_position, self.window.position) def test_freeing_context(self): self.window.close = mock.MagicMock() self.window.free() self.window.close.assert_called_once() def test_close(self): self.window.close() self.context.free.assert_called_once() self.assertIsNone(self.window._context) def test_closing_window_that_has_already_been_closed(self): self.window._context = None self.window.close() self.assertEqual(0, _GLFW_MOCK.destroy_window.call_count) def test_file_drop(self): self.expected_paths = ['path1', 'path2'] def callback(paths): self.assertEqual(self.expected_paths, paths) was_called_mock = mock.MagicMock() self.window.on_files_drop += [callback, was_called_mock] self.window._handle_file_drop('window_handle', self.expected_paths) was_called_mock.assert_called_once() def test_setting_title(self): new_title = 'new_title' self.window.set_title(new_title) self.assertEqual(new_title, _GLFW_MOCK.set_window_title.call_args[0][1]) def test_enabling_full_screen(self): full_screen_pos = (0, 0) full_screen_size = (1, 2) window_size = (3, 4) window_pos = (5, 6) reserved_value = 7 full_size_mode = 8 _GLFW_MOCK.get_framebuffer_size.return_value = window_size _GLFW_MOCK.get_window_pos.return_value = window_pos _GLFW_MOCK.get_video_mode.return_value = ( full_screen_size, reserved_value, full_size_mode) self.window.set_full_screen(True) _GLFW_MOCK.set_window_monitor.assert_called_once() new_position = _GLFW_MOCK.set_window_monitor.call_args[0][2:4] new_size = _GLFW_MOCK.set_window_monitor.call_args[0][4:6] new_mode = _GLFW_MOCK.set_window_monitor.call_args[0][6] self.assertEqual(full_screen_pos, new_position) self.assertEqual(full_screen_size, new_size) self.assertEqual(full_size_mode, new_mode) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/viewer/gui/glfw_gui_test.py
# Copyright 2018 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Utilities and base classes used exclusively in the gui package.""" import abc import threading import time from dm_control.viewer import user_input _DOUBLE_CLICK_INTERVAL = 0.25 # seconds class InputEventsProcessor(metaclass=abc.ABCMeta): """Thread safe input events processor.""" def __init__(self): """Instance initializer.""" self._lock = threading.RLock() self._events = [] def add_event(self, receivers, *args): """Adds a new event to the processing queue.""" if not all(callable(receiver) for receiver in receivers): raise TypeError('Receivers are expected to be callables.') def event(): for receiver in list(receivers): receiver(*args) with self._lock: self._events.append(event) def process_events(self): """Invokes each of the events in the queue. Thread safe for queue access but not during event invocations. This method must be called regularly on the main thread. """ with self._lock: # Swap event buffers quickly so that we don't block the input thread for # too long. events_to_process = self._events self._events = [] # Now that we made the swap, process the received events in our own time. for event in events_to_process: event() class DoubleClickDetector: """Detects double click events.""" def __init__(self): self._double_clicks = {} def process(self, button, action): """Attempts to identify a mouse button click as a double click event.""" if action != user_input.PRESS: return False curr_time = time.time() timestamp = self._double_clicks.get(button, None) if timestamp is None: # No previous click registered. self._double_clicks[button] = curr_time return False else: time_elapsed = curr_time - timestamp if time_elapsed < _DOUBLE_CLICK_INTERVAL: # Double click discovered. self._double_clicks[button] = None return True else: # The previous click was too long ago, so discard it and start a fresh # timer. self._double_clicks[button] = curr_time return False
dm_control-main
dm_control/viewer/gui/base.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for the base rendering module.""" import threading from absl.testing import absltest from dm_control._render import base from dm_control._render import executor WIDTH = 1024 HEIGHT = 768 class ContextBaseTests(absltest.TestCase): class ContextMock(base.ContextBase): def _platform_init(self, max_width, max_height): self.init_thread = threading.current_thread() self.make_current_count = 0 self.max_width = max_width self.max_height = max_height self.free_thread = None def _platform_make_current(self): self.make_current_count += 1 self.make_current_thread = threading.current_thread() def _platform_free(self): self.free_thread = threading.current_thread() def setUp(self): super().setUp() self.context = ContextBaseTests.ContextMock(WIDTH, HEIGHT) def test_init(self): self.assertIs(self.context.init_thread, self.context.thread) self.assertEqual(self.context.max_width, WIDTH) self.assertEqual(self.context.max_height, HEIGHT) def test_make_current(self): self.assertEqual(self.context.make_current_count, 0) with self.context.make_current(): pass self.assertEqual(self.context.make_current_count, 1) self.assertIs(self.context.make_current_thread, self.context.thread) # Already current, shouldn't trigger a call to `_platform_make_current`. with self.context.make_current(): pass self.assertEqual(self.context.make_current_count, 1) self.assertIs(self.context.make_current_thread, self.context.thread) def test_thread_sharing(self): first_context = ContextBaseTests.ContextMock( WIDTH, HEIGHT, executor.PassthroughRenderExecutor) second_context = ContextBaseTests.ContextMock( WIDTH, HEIGHT, executor.PassthroughRenderExecutor) with first_context.make_current(): pass self.assertEqual(first_context.make_current_count, 1) with first_context.make_current(): pass self.assertEqual(first_context.make_current_count, 1) with second_context.make_current(): pass self.assertEqual(second_context.make_current_count, 1) with second_context.make_current(): pass self.assertEqual(second_context.make_current_count, 1) with first_context.make_current(): pass self.assertEqual(first_context.make_current_count, 2) with second_context.make_current(): pass self.assertEqual(second_context.make_current_count, 2) def test_free(self): with self.context.make_current(): pass thread = self.context.thread self.assertIn(id(self.context), base._CURRENT_THREAD_FOR_CONTEXT) self.assertIn(thread, base._CURRENT_CONTEXT_FOR_THREAD) self.context.free() self.assertIs(self.context.free_thread, thread) self.assertIsNone(self.context.thread) self.assertNotIn(id(self.context), base._CURRENT_THREAD_FOR_CONTEXT) self.assertNotIn(thread, base._CURRENT_CONTEXT_FOR_THREAD) def test_free_with_multiple_contexts(self): context1 = ContextBaseTests.ContextMock(WIDTH, HEIGHT, executor.PassthroughRenderExecutor) with context1.make_current(): pass context2 = ContextBaseTests.ContextMock(WIDTH, HEIGHT, executor.PassthroughRenderExecutor) with context2.make_current(): pass self.assertEqual(base._CURRENT_CONTEXT_FOR_THREAD[threading.main_thread()], id(context2)) self.assertIs(base._CURRENT_THREAD_FOR_CONTEXT[id(context2)], threading.main_thread()) context1.free() self.assertIsNone( base._CURRENT_CONTEXT_FOR_THREAD[self.context.free_thread]) self.assertIsNone(base._CURRENT_THREAD_FOR_CONTEXT[id(context2)]) def test_refcounting(self): thread = self.context.thread self.assertEqual(self.context._refcount, 0) self.context.increment_refcount() self.assertEqual(self.context._refcount, 1) # Context should not be freed yet, since its refcount is still positive. self.context.free() self.assertIsNone(self.context.free_thread) self.assertIs(self.context.thread, thread) # Decrement the refcount to zero. self.context.decrement_refcount() self.assertEqual(self.context._refcount, 0) # Now the context can be freed. self.context.free() self.assertIs(self.context.free_thread, thread) self.assertIsNone(self.context.thread) def test_del(self): self.assertIsNone(self.context.free_thread) self.context.__del__() self.assertIsNotNone(self.context.free_thread) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/_render/base_test.py
# Copyright 2018 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """String constants for the rendering module.""" # Name of the environment variable that selects a renderer platform. MUJOCO_GL = 'MUJOCO_GL' # Name of the environment variable that selects a platform for PyOpenGL. PYOPENGL_PLATFORM = 'PYOPENGL_PLATFORM' # Renderer platform specifiers. # All values in each tuple are synonyms for the MUJOCO_GL environment variable. # The first entry in each tuple is considered "canonical", and is the one # assigned to the _render.BACKEND variable. OSMESA = ('osmesa',) GLFW = ('glfw', 'on', 'enable', 'enabled', 'true', '1', '') EGL = ('egl',) NO_RENDERER = ('off', 'disable', 'disabled', 'false', '0')
dm_control-main
dm_control/_render/constants.py
# Copyright 2017-2018 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """OpenGL context management for rendering MuJoCo scenes. By default, the `Renderer` class will try to load one of the following rendering APIs, in descending order of priority: GLFW > EGL > OSMesa. It is also possible to select a specific backend by setting the `MUJOCO_GL=` environment variable to 'glfw', 'egl', or 'osmesa'. """ import collections import os from absl import logging from dm_control._render import constants BACKEND = os.environ.get(constants.MUJOCO_GL) # pylint: disable=g-import-not-at-top def _import_egl(): from dm_control._render.pyopengl.egl_renderer import EGLContext return EGLContext def _import_glfw(): from dm_control._render.glfw_renderer import GLFWContext return GLFWContext def _import_osmesa(): from dm_control._render.pyopengl.osmesa_renderer import OSMesaContext return OSMesaContext # pylint: enable=g-import-not-at-top def _no_renderer(): def no_renderer(*args, **kwargs): del args, kwargs raise RuntimeError('No OpenGL rendering backend is available.') return no_renderer _ALL_RENDERERS = ( (constants.GLFW, _import_glfw), (constants.EGL, _import_egl), (constants.OSMESA, _import_osmesa), ) _NO_RENDERER = ( (constants.NO_RENDERER, _no_renderer), ) if BACKEND is not None: # If a backend was specified, try importing it and error if unsuccessful. import_func = None for names, importer in _ALL_RENDERERS + _NO_RENDERER: if BACKEND in names: import_func = importer BACKEND = names[0] # canonicalize the renderer name break if import_func is None: all_names = set() for names, _ in _ALL_RENDERERS + _NO_RENDERER: all_names.update(names) raise RuntimeError( 'Environment variable {} must be one of {!r}: got {!r}.' .format(constants.MUJOCO_GL, sorted(all_names), BACKEND)) logging.info('MUJOCO_GL=%s, attempting to import specified OpenGL backend.', BACKEND) Renderer = import_func() else: logging.info('MUJOCO_GL is not set, so an OpenGL backend will be chosen ' 'automatically.') # Otherwise try importing them in descending order of priority until # successful. for names, import_func in _ALL_RENDERERS: try: Renderer = import_func() BACKEND = names[0] logging.info('Successfully imported OpenGL backend: %s', names[0]) break except ImportError: logging.info('Failed to import OpenGL backend: %s', names[0]) if BACKEND is None: logging.info('No OpenGL backend could be imported. Attempting to create a ' 'rendering context will result in a RuntimeError.') Renderer = _no_renderer() USING_GPU = BACKEND in constants.EGL + constants.GLFW
dm_control-main
dm_control/_render/__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. # ============================================================================ """An OpenGL renderer backed by GLFW.""" from dm_control._render import base from dm_control._render import executor # Re-raise any exceptions that occur during module import as `ImportError`s. # This simplifies the conditional imports in `render/__init__.py`. try: import glfw # pylint: disable=g-import-not-at-top except (ImportError, IOError, OSError) as exc: raise ImportError from exc try: glfw.init() except glfw.GLFWError as exc: raise ImportError from exc class GLFWContext(base.ContextBase): """An OpenGL context backed by GLFW.""" def __init__(self, max_width, max_height): # GLFWContext always uses `PassthroughRenderExecutor` rather than offloading # rendering calls to a separate thread because GLFW can only be safely used # from the main thread. super().__init__(max_width, max_height, executor.PassthroughRenderExecutor) def _platform_init(self, max_width, max_height): """Initializes this context. Args: max_width: Integer specifying the maximum framebuffer width in pixels. max_height: Integer specifying the maximum framebuffer height in pixels. """ glfw.window_hint(glfw.VISIBLE, 0) glfw.window_hint(glfw.DOUBLEBUFFER, 0) self._context = glfw.create_window(width=max_width, height=max_height, title='Invisible window', monitor=None, share=None) # This reference prevents `glfw.destroy_window` from being garbage-collected # before the last window is destroyed, otherwise we may get # `AttributeError`s when the `__del__` method is later called. self._destroy_window = glfw.destroy_window def _platform_make_current(self): glfw.make_context_current(self._context) def _platform_free(self): """Frees resources associated with this context.""" if self._context: if glfw.get_current_context() == self._context: glfw.make_context_current(None) self._destroy_window(self._context) self._context = None
dm_control-main
dm_control/_render/glfw_renderer.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for GLFWContext.""" import unittest from absl.testing import absltest from dm_control import _render from dm_control.mujoco import wrapper from dm_control.mujoco.testing import decorators import mock # pylint: disable=g-import-not-at-top MAX_WIDTH = 1024 MAX_HEIGHT = 1024 CONTEXT_PATH = _render.__name__ + '.glfw_renderer.glfw' @unittest.skipUnless( _render.BACKEND == _render.constants.GLFW[0], reason='GLFW beckend not selected.') class GLFWContextTest(absltest.TestCase): def test_init(self): mock_context = mock.MagicMock() with mock.patch(CONTEXT_PATH) as mock_glfw: mock_glfw.create_window.return_value = mock_context renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT) self.assertIs(renderer._context, mock_context) def test_make_current(self): mock_context = mock.MagicMock() with mock.patch(CONTEXT_PATH) as mock_glfw: mock_glfw.create_window.return_value = mock_context renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT) with renderer.make_current(): pass mock_glfw.make_context_current.assert_called_once_with(mock_context) def test_freeing(self): mock_context = mock.MagicMock() with mock.patch(CONTEXT_PATH) as mock_glfw: mock_glfw.create_window.return_value = mock_context renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT) renderer.free() mock_glfw.destroy_window.assert_called_once_with(mock_context) self.assertIsNone(renderer._context) @decorators.run_threaded(num_threads=1, calls_per_thread=20) def test_repeatedly_create_and_destroy_context(self): renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT) wrapper.MjrContext(wrapper.MjModel.from_xml_string('<mujoco/>'), renderer) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/_render/glfw_renderer_test.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Base class for OpenGL context handlers. `ContextBase` defines a common API that OpenGL rendering contexts should conform to. In addition, it provides a `make_current` context manager that: 1. Makes this OpenGL context current within the appropriate rendering thread. 2. Yields an object exposing a `call` method that can be used to execute OpenGL calls within the rendering thread. See the docstring for `dm_control.utils.render_executor` for further details regarding rendering threads. """ import abc import atexit import collections import contextlib import sys import weakref from absl import logging from dm_control._render import executor _CURRENT_CONTEXT_FOR_THREAD = collections.defaultdict(lambda: None) _CURRENT_THREAD_FOR_CONTEXT = collections.defaultdict(lambda: None) class ContextBase(metaclass=abc.ABCMeta): """Base class for managing OpenGL contexts.""" def __init__(self, max_width, max_height, render_executor_class=executor.RenderExecutor): """Initializes this context.""" logging.debug('Using render executor class: %s', render_executor_class.__name__) self._render_executor = render_executor_class() self._refcount = 0 self_weakref = weakref.ref(self) def _free_at_exit(): if self_weakref(): self_weakref()._free_unconditionally() # pylint: disable=protected-access atexit.register(_free_at_exit) with self._render_executor.execution_context() as ctx: ctx.call(self._platform_init, max_width, max_height) self._patients = [] def keep_alive(self, obj): self._patients.append(obj) def dont_keep_alive(self, obj): try: self._patients.remove(obj) except ValueError: pass def increment_refcount(self): self._refcount += 1 def decrement_refcount(self): self._refcount -= 1 @property def terminated(self): return self._render_executor.terminated @property def thread(self): return self._render_executor.thread def _free_on_executor_thread(self): # pylint: disable=missing-function-docstring current_ctx = _CURRENT_CONTEXT_FOR_THREAD[self._render_executor.thread] if current_ctx is not None: del _CURRENT_THREAD_FOR_CONTEXT[current_ctx] del _CURRENT_CONTEXT_FOR_THREAD[self._render_executor.thread] self._platform_make_current() try: dummy = [] while self._patients: patient = self._patients.pop() assert sys.getrefcount(patient) == sys.getrefcount(dummy) if hasattr(patient, 'free'): patient.free() del patient finally: self._platform_free() def free(self): """Frees resources associated with this context if its refcount is zero.""" if self._refcount == 0: self._free_unconditionally() def _free_unconditionally(self): self._render_executor.terminate(self._free_on_executor_thread) def __del__(self): self._free_unconditionally() @contextlib.contextmanager def make_current(self): """Context manager that makes this Renderer's OpenGL context current. Yields: An object that exposes a `call` method that can be used to call a function on the dedicated rendering thread. Raises: RuntimeError: If this context is already current on another thread. """ with self._render_executor.execution_context() as ctx: if _CURRENT_CONTEXT_FOR_THREAD[self._render_executor.thread] != id(self): if _CURRENT_THREAD_FOR_CONTEXT[id(self)]: raise RuntimeError( 'Cannot make context {!r} current on thread {!r}: ' 'this context is already current on another thread {!r}.' .format(self, self._render_executor.thread, _CURRENT_THREAD_FOR_CONTEXT[id(self)])) else: current_context = ( _CURRENT_CONTEXT_FOR_THREAD[self._render_executor.thread]) if current_context: del _CURRENT_THREAD_FOR_CONTEXT[current_context] _CURRENT_THREAD_FOR_CONTEXT[id(self)] = self._render_executor.thread _CURRENT_CONTEXT_FOR_THREAD[self._render_executor.thread] = id(self) ctx.call(self._platform_make_current) yield ctx @abc.abstractmethod def _platform_init(self, max_width, max_height): """Performs an implementation-specific context initialization.""" @abc.abstractmethod def _platform_make_current(self): """Make the OpenGL context current on the executing thread.""" @abc.abstractmethod def _platform_free(self): """Performs an implementation-specific context cleanup."""
dm_control-main
dm_control/_render/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. # ============================================================================ """An OpenGL renderer backed by OSMesa.""" import os from dm_control._render import base from dm_control._render import constants PYOPENGL_PLATFORM = os.environ.get(constants.PYOPENGL_PLATFORM) if not PYOPENGL_PLATFORM: os.environ[constants.PYOPENGL_PLATFORM] = constants.OSMESA[0] elif PYOPENGL_PLATFORM != constants.OSMESA[0]: raise ImportError( 'Cannot use OSMesa rendering platform. ' 'The PYOPENGL_PLATFORM environment variable is set to {!r} ' '(should be either unset or {!r}).' .format(PYOPENGL_PLATFORM, constants.OSMESA[0])) # pylint: disable=g-import-not-at-top from OpenGL import GL from OpenGL import osmesa from OpenGL.GL import arrays _DEPTH_BITS = 24 _STENCIL_BITS = 8 _ACCUM_BITS = 0 class OSMesaContext(base.ContextBase): """An OpenGL context backed by OSMesa.""" def __init__(self, *args, **kwargs): self._context = None super().__init__(*args, **kwargs) def _platform_init(self, max_width, max_height): """Initializes this OSMesa context.""" self._context = osmesa.OSMesaCreateContextExt( osmesa.OSMESA_RGBA, _DEPTH_BITS, _STENCIL_BITS, _ACCUM_BITS, None, # sharelist ) if not self._context: raise RuntimeError('Failed to create OSMesa GL context.') self._height = max_height self._width = max_width # Allocate a buffer to render into. self._buffer = arrays.GLfloatArray.zeros((max_height, max_width, 4)) def _platform_make_current(self): if self._context: success = osmesa.OSMesaMakeCurrent( self._context, self._buffer, GL.GL_FLOAT, self._width, self._height) if not success: raise RuntimeError('Failed to make OSMesa context current.') def _platform_free(self): """Frees resources associated with this context.""" if self._context and self._context == osmesa.OSMesaGetCurrentContext(): osmesa.OSMesaMakeCurrent(None, None, GL.GL_FLOAT, 0, 0) osmesa.OSMesaDestroyContext(self._context) self._buffer = None self._context = None
dm_control-main
dm_control/_render/pyopengl/osmesa_renderer.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 OpenGL renderer backed by EGL, provided through PyOpenGL.""" import atexit import ctypes import os from dm_control._render import base from dm_control._render import constants from dm_control._render import executor PYOPENGL_PLATFORM = os.environ.get(constants.PYOPENGL_PLATFORM) if not PYOPENGL_PLATFORM: os.environ[constants.PYOPENGL_PLATFORM] = constants.EGL[0] elif PYOPENGL_PLATFORM != constants.EGL[0]: raise ImportError( 'Cannot use EGL rendering platform. ' 'The PYOPENGL_PLATFORM environment variable is set to {!r} ' '(should be either unset or {!r}).' .format(PYOPENGL_PLATFORM, constants.EGL[0])) # pylint: disable=g-import-not-at-top from dm_control._render.pyopengl import egl_ext as EGL from OpenGL import error def create_initialized_headless_egl_display(): """Creates an initialized EGL display directly on a device.""" all_devices = EGL.eglQueryDevicesEXT() selected_device = os.environ.get('MUJOCO_EGL_DEVICE_ID', None) if selected_device is None: candidates = all_devices else: device_idx = int(selected_device) if not 0 <= device_idx < len(all_devices): raise RuntimeError( f'MUJOCO_EGL_DEVICE_ID must be an integer between 0 and ' f'{len(all_devices) - 1} (inclusive), got {device_idx}.') candidates = all_devices[device_idx:device_idx + 1] for device in candidates: display = EGL.eglGetPlatformDisplayEXT( EGL.EGL_PLATFORM_DEVICE_EXT, device, None) if display != EGL.EGL_NO_DISPLAY and EGL.eglGetError() == EGL.EGL_SUCCESS: # `eglInitialize` may or may not raise an exception on failure depending # on how PyOpenGL is configured. We therefore catch a `GLError` and also # manually check the output of `eglGetError()` here. try: initialized = EGL.eglInitialize(display, None, None) except error.GLError: pass else: if initialized == EGL.EGL_TRUE and EGL.eglGetError() == EGL.EGL_SUCCESS: return display return EGL.EGL_NO_DISPLAY EGL_DISPLAY = create_initialized_headless_egl_display() if EGL_DISPLAY == EGL.EGL_NO_DISPLAY: raise ImportError('Cannot initialize a headless EGL display.') atexit.register(EGL.eglTerminate, EGL_DISPLAY) EGL_ATTRIBUTES = ( EGL.EGL_RED_SIZE, 8, EGL.EGL_GREEN_SIZE, 8, EGL.EGL_BLUE_SIZE, 8, EGL.EGL_ALPHA_SIZE, 8, EGL.EGL_DEPTH_SIZE, 24, EGL.EGL_STENCIL_SIZE, 8, EGL.EGL_COLOR_BUFFER_TYPE, EGL.EGL_RGB_BUFFER, EGL.EGL_SURFACE_TYPE, EGL.EGL_PBUFFER_BIT, EGL.EGL_RENDERABLE_TYPE, EGL.EGL_OPENGL_BIT, EGL.EGL_NONE ) class EGLContext(base.ContextBase): """An OpenGL context backed by EGL.""" def __init__(self, max_width, max_height): # EGLContext currently only works with `PassthroughRenderExecutor`. # TODO(b/110927854) Make this work with the offloading executor. self._context = None super().__init__(max_width, max_height, executor.PassthroughRenderExecutor) def _platform_init(self, unused_max_width, unused_max_height): """Initialization this EGL context.""" num_configs = ctypes.c_long(0) config_size = 1 config = EGL.EGLConfig() EGL.eglReleaseThread() EGL.eglChooseConfig( EGL_DISPLAY, EGL_ATTRIBUTES, ctypes.byref(config), config_size, num_configs) if num_configs.value < 1: raise RuntimeError( 'EGL failed to find a framebuffer configuration that matches the ' 'desired attributes: {}'.format(EGL_ATTRIBUTES)) EGL.eglBindAPI(EGL.EGL_OPENGL_API) self._context = EGL.eglCreateContext( EGL_DISPLAY, config, EGL.EGL_NO_CONTEXT, None) if not self._context: raise RuntimeError('Cannot create an EGL context.') def _platform_make_current(self): if self._context: success = EGL.eglMakeCurrent( EGL_DISPLAY, EGL.EGL_NO_SURFACE, EGL.EGL_NO_SURFACE, self._context) if not success: raise RuntimeError('Failed to make the EGL context current.') def _platform_free(self): """Frees resources associated with this context.""" if self._context: current_context = EGL.eglGetCurrentContext() if current_context and self._context.address == current_context.address: EGL.eglMakeCurrent(EGL_DISPLAY, EGL.EGL_NO_SURFACE, EGL.EGL_NO_SURFACE, EGL.EGL_NO_CONTEXT) EGL.eglDestroyContext(EGL_DISPLAY, self._context) self._context = None
dm_control-main
dm_control/_render/pyopengl/egl_renderer.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 OSMesaContext.""" import unittest from absl.testing import absltest from dm_control import _render import mock from OpenGL import GL MAX_WIDTH = 640 MAX_HEIGHT = 480 CONTEXT_PATH = _render.__name__ + '.pyopengl.osmesa_renderer.osmesa' GL_ARRAYS_PATH = _render.__name__ + '.pyopengl.osmesa_renderer.arrays' @unittest.skipUnless( _render.BACKEND == _render.constants.OSMESA, reason='OSMesa backend not selected.') class OSMesaContextTest(absltest.TestCase): def test_init(self): mock_context = mock.MagicMock() with mock.patch(CONTEXT_PATH) as mock_osmesa: mock_osmesa.OSMesaCreateContextExt.return_value = mock_context renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT) self.assertIs(renderer._context, mock_context) renderer.free() def test_make_current(self): mock_context = mock.MagicMock() mock_buffer = mock.MagicMock() with mock.patch(CONTEXT_PATH) as mock_osmesa: with mock.patch(GL_ARRAYS_PATH) as mock_glarrays: mock_osmesa.OSMesaCreateContextExt.return_value = mock_context mock_glarrays.GLfloatArray.zeros.return_value = mock_buffer renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT) with renderer.make_current(): pass mock_osmesa.OSMesaMakeCurrent.assert_called_once_with( mock_context, mock_buffer, GL.GL_FLOAT, MAX_WIDTH, MAX_HEIGHT) renderer.free() def test_freeing(self): mock_context = mock.MagicMock() with mock.patch(CONTEXT_PATH) as mock_osmesa: mock_osmesa.OSMesaCreateContextExt.return_value = mock_context renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT) renderer.free() mock_osmesa.OSMesaDestroyContext.assert_called_once_with(mock_context) self.assertIsNone(renderer._context) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/_render/pyopengl/osmesa_renderer_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. # ============================================================================
dm_control-main
dm_control/_render/pyopengl/__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. # ============================================================================ """Extends OpenGL.EGL with definitions necessary for headless rendering.""" import ctypes from OpenGL.platform import ctypesloader # pylint: disable=g-bad-import-order try: # Nvidia driver seems to need libOpenGL.so (as opposed to libGL.so) # for multithreading to work properly. We load this in before everything else. ctypesloader.loadLibrary(ctypes.cdll, 'OpenGL', mode=ctypes.RTLD_GLOBAL) except OSError: pass # pylint: disable=g-import-not-at-top from OpenGL import EGL from OpenGL import error # From the EGL_EXT_device_enumeration extension. PFNEGLQUERYDEVICESEXTPROC = ctypes.CFUNCTYPE( EGL.EGLBoolean, EGL.EGLint, ctypes.POINTER(EGL.EGLDeviceEXT), ctypes.POINTER(EGL.EGLint), ) try: _eglQueryDevicesEXT = PFNEGLQUERYDEVICESEXTPROC( # pylint: disable=invalid-name EGL.eglGetProcAddress('eglQueryDevicesEXT')) except TypeError: raise ImportError('eglQueryDevicesEXT is not available.') # From the EGL_EXT_platform_device extension. EGL_PLATFORM_DEVICE_EXT = 0x313F PFNEGLGETPLATFORMDISPLAYEXTPROC = ctypes.CFUNCTYPE( EGL.EGLDisplay, EGL.EGLenum, ctypes.c_void_p, ctypes.POINTER(EGL.EGLint)) try: eglGetPlatformDisplayEXT = PFNEGLGETPLATFORMDISPLAYEXTPROC( # pylint: disable=invalid-name EGL.eglGetProcAddress('eglGetPlatformDisplayEXT')) except TypeError: raise ImportError('eglGetPlatformDisplayEXT is not available.') # Wrap raw _eglQueryDevicesEXT function into something more Pythonic. def eglQueryDevicesEXT(max_devices=10): # pylint: disable=invalid-name devices = (EGL.EGLDeviceEXT * max_devices)() num_devices = EGL.EGLint() success = _eglQueryDevicesEXT(max_devices, devices, num_devices) if success == EGL.EGL_TRUE: return [devices[i] for i in range(num_devices.value)] else: raise error.GLError(err=EGL.eglGetError(), baseOperation=eglQueryDevicesEXT, result=success) # Expose everything from upstream so that # we can use this as a drop-in replacement for OpenGL.EGL. # pylint: disable=wildcard-import,g-bad-import-order from OpenGL.EGL import *
dm_control-main
dm_control/_render/pyopengl/egl_ext.py
# Copyright 2017-2018 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for dm_control.utils.render_executor.""" import threading import time import unittest from absl.testing import absltest from absl.testing import parameterized from dm_control._render import executor import mock def enforce_timeout(timeout): def wrap(test_func): def wrapped_test(self, *args, **kwargs): thread = threading.Thread( target=test_func, args=((self,) + args), kwargs=kwargs) thread.daemon = True thread.start() thread.join(timeout=timeout) self.assertFalse( thread.is_alive(), msg='Test timed out after {} seconds.'.format(timeout)) return wrapped_test return wrap class RenderExecutorTest(parameterized.TestCase): def _make_executor(self, executor_type): if (executor_type == executor.NativeMutexOffloadingRenderExecutor and executor_type is None): raise unittest.SkipTest( 'NativeMutexOffloadingRenderExecutor is not available.') else: return executor_type() def test_passthrough_executor_thread(self): render_executor = self._make_executor(executor.PassthroughRenderExecutor) self.assertIs(render_executor.thread, threading.current_thread()) render_executor.terminate() @parameterized.parameters(executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) def test_offloading_executor_thread(self, executor_type): render_executor = self._make_executor(executor_type) self.assertIsNot(render_executor.thread, threading.current_thread()) render_executor.terminate() @parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) def test_call_on_correct_thread(self, executor_type): render_executor = self._make_executor(executor_type) with render_executor.execution_context() as ctx: actual_executed_thread = ctx.call(threading.current_thread) self.assertIs(actual_executed_thread, render_executor.thread) render_executor.terminate() @parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) def test_multithreaded(self, executor_type): render_executor = self._make_executor(executor_type) list_length = 5 shared_list = [None] * list_length def fill_list(thread_idx): def assign_value(i): shared_list[i] = thread_idx for _ in range(1000): with render_executor.execution_context() as ctx: for i in range(list_length): ctx.call(assign_value, i) # Other threads should be prevented from calling `assign_value` while # this thread is inside the `execution_context`. self.assertEqual(shared_list, [thread_idx] * list_length) threads = [threading.Thread(target=fill_list, args=(i,)) for i in range(9)] for thread in threads: thread.start() for thread in threads: thread.join() render_executor.terminate() @parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) def test_exception(self, executor_type): render_executor = self._make_executor(executor_type) message = 'fake error' def raise_value_error(): raise ValueError(message) with render_executor.execution_context() as ctx: with self.assertRaisesWithLiteralMatch(ValueError, message): ctx.call(raise_value_error) render_executor.terminate() @parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) def test_terminate(self, executor_type): render_executor = self._make_executor(executor_type) cleanup = mock.MagicMock() render_executor.terminate(cleanup) cleanup.assert_called_once_with() @parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) def test_call_outside_of_context(self, executor_type): render_executor = self._make_executor(executor_type) func = mock.MagicMock() with self.assertRaisesWithLiteralMatch( RuntimeError, executor.render_executor._NOT_IN_CONTEXT): render_executor.call(func) # Also test that the locked flag is properly cleared when leaving a context. with render_executor.execution_context(): render_executor.call(lambda: None) with self.assertRaisesWithLiteralMatch( RuntimeError, executor.render_executor._NOT_IN_CONTEXT): render_executor.call(func) func.assert_not_called() render_executor.terminate() @parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) def test_call_after_terminate(self, executor_type): render_executor = self._make_executor(executor_type) render_executor.terminate() func = mock.MagicMock() with self.assertRaisesWithLiteralMatch( RuntimeError, executor.render_executor._ALREADY_TERMINATED): with render_executor.execution_context() as ctx: ctx.call(func) func.assert_not_called() @parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) def test_locking(self, executor_type): render_executor = self._make_executor(executor_type) other_thread_context_entered = threading.Condition() other_thread_context_done = [False] def other_thread_func(): with render_executor.execution_context(): with other_thread_context_entered: other_thread_context_entered.notify() time.sleep(1) other_thread_context_done[0] = True other_thread = threading.Thread(target=other_thread_func) with other_thread_context_entered: other_thread.start() other_thread_context_entered.wait() with render_executor.execution_context(): self.assertTrue( other_thread_context_done[0], msg=('Main thread should not be able to enter the execution context ' 'until the other thread is done.')) @parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) @enforce_timeout(timeout=5.) def test_reentrant_locking(self, executor_type): render_executor = self._make_executor(executor_type) def triple_lock(render_executor): with render_executor.execution_context(): with render_executor.execution_context(): with render_executor.execution_context(): pass triple_lock(render_executor) @parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) @enforce_timeout(timeout=5.) def test_no_deadlock_in_callbacks(self, executor_type): render_executor = self._make_executor(executor_type) # This test times out in the event of a deadlock. def callback(): with render_executor.execution_context() as ctx: ctx.call(lambda: None) with render_executor.execution_context() as ctx: ctx.call(callback) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/_render/executor/render_executor_test.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """RenderExecutor executes OpenGL rendering calls on an appropriate thread. OpenGL calls must be made on the same thread as where an OpenGL context is made current on. With GPU rendering, migrating OpenGL contexts between threads can become expensive. We provide a thread-safe executor that maintains a thread on which an OpenGL context can be kept permanently current, and any other threads that wish to render with that context will have their rendering calls offloaded to the dedicated thread. For single-threaded applications, set the `DISABLE_RENDER_THREAD_OFFLOADING` environment variable before launching the Python interpreter. This will eliminate the overhead of unnecessary thread-switching. """ # pylint: disable=g-import-not-at-top import os _OFFLOAD = not bool(os.environ.get('DISABLE_RENDER_THREAD_OFFLOADING', '')) del os from dm_control._render.executor.render_executor import BaseRenderExecutor from dm_control._render.executor.render_executor import OffloadingRenderExecutor from dm_control._render.executor.render_executor import PassthroughRenderExecutor _EXECUTORS = (PassthroughRenderExecutor, OffloadingRenderExecutor) try: from dm_control._render.executor.native_mutex.render_executor import NativeMutexOffloadingRenderExecutor _EXECUTORS += (NativeMutexOffloadingRenderExecutor,) except ImportError: NativeMutexOffloadingRenderExecutor = None if _OFFLOAD: RenderExecutor = ( # pylint: disable=invalid-name NativeMutexOffloadingRenderExecutor or OffloadingRenderExecutor) else: RenderExecutor = PassthroughRenderExecutor # pylint: disable=invalid-name
dm_control-main
dm_control/_render/executor/__init__.py
# Copyright 2017-2018 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """RenderExecutors executes OpenGL rendering calls on an appropriate thread. The purpose of these classes is to ensure that OpenGL calls are made on the same thread as where an OpenGL context was made current. In a single-threaded setting, `PassthroughRenderExecutor` is essentially a no-op that executes rendering calls on the same thread. This is provided to minimize thread-switching overhead. In a multithreaded setting, `OffloadingRenderExecutor` maintains a separate dedicated thread on which the OpenGL context is created and made current. All subsequent rendering calls are then offloaded onto this dedicated thread. """ import abc import collections from concurrent import futures import contextlib import threading _NOT_IN_CONTEXT = 'Cannot be called outside of an `execution_context`.' _ALREADY_TERMINATED = 'This executor has already been terminated.' class _FakeLock: """An object with the same API as `threading.Lock` but that does nothing.""" def acquire(self, blocking=True): pass def release(self): pass def __enter__(self): pass def __exit__(self, exc_type, exc_value, traceback): del exc_type, exc_value, traceback _FAKE_LOCK = _FakeLock() class BaseRenderExecutor(metaclass=abc.ABCMeta): """An object that manages rendering calls for an OpenGL context. This class helps ensure that OpenGL calls are made on the correct thread. The usage pattern is as follows: ```python executor = SomeRenderExecutorClass() with executor.execution_context() as ctx: ctx.call(an_opengl_call, arg, kwarg=foo) result = ctx.call(another_opengl_call) ``` """ def __init__(self): self._locked = 0 self._terminated = False def _check_locked(self): if not self._locked: raise RuntimeError(_NOT_IN_CONTEXT) def _check_not_terminated(self): if self._terminated: raise RuntimeError(_ALREADY_TERMINATED) @contextlib.contextmanager def execution_context(self): """A context manager that allows calls to be offloaded to this executor.""" self._check_not_terminated() with self._lock_if_necessary: self._locked += 1 yield self self._locked -= 1 @property def terminated(self): return self._terminated @property @abc.abstractmethod def thread(self): pass @property @abc.abstractmethod def _lock_if_necessary(self): pass @abc.abstractmethod def call(self, *args, **kwargs): pass @abc.abstractmethod def terminate(self, cleanup_callable=None): pass class PassthroughRenderExecutor(BaseRenderExecutor): """A no-op render executor that executes on the calling thread.""" def __init__(self): super().__init__() self._mutex = threading.RLock() @property def thread(self): if not self._terminated: return threading.current_thread() else: return None @property def _lock_if_necessary(self): return self._mutex def call(self, func, *args, **kwargs): self._check_locked() return func(*args, **kwargs) def terminate(self, cleanup_callable=None): with self._lock_if_necessary: if not self._terminated: if cleanup_callable: cleanup_callable() self._terminated = True class _ThreadPoolExecutorPool: """A pool of reusable ThreadPoolExecutors.""" def __init__(self): self._deque = collections.deque() self._lock = threading.Lock() def acquire(self): with self._lock: if self._deque: return self._deque.popleft() else: return futures.ThreadPoolExecutor(max_workers=1) def release(self, thread_pool_executor): with self._lock: self._deque.append(thread_pool_executor) _THREAD_POOL_EXECUTOR_POOL = _ThreadPoolExecutorPool() class OffloadingRenderExecutor(BaseRenderExecutor): """A render executor that executes calls on a dedicated offload thread.""" def __init__(self): super().__init__() self._mutex = threading.RLock() self._executor = _THREAD_POOL_EXECUTOR_POOL.acquire() self._thread = self._executor.submit(threading.current_thread).result() @property def thread(self): return self._thread @property def _lock_if_necessary(self): if threading.current_thread() is self.thread: # If the offload thread needs to make a call to its own executor, for # example when a weakref callback is triggered during an offloaded call, # then we must not try to reacquire our own lock. # Otherwise, a deadlock ensues. return _FAKE_LOCK else: return self._mutex def call(self, func, *args, **kwargs): self._check_locked() return self._call_locked(func, *args, **kwargs) def _call_locked(self, func, *args, **kwargs): if threading.current_thread() is self.thread: # If the offload thread needs to make a call to its own executor, for # example when a weakref callback is triggered during an offloaded call, # we should just directly call the function. # Otherwise, a deadlock ensues. return func(*args, **kwargs) else: return self._executor.submit(func, *args, **kwargs).result() def terminate(self, cleanup_callable=None): if self._terminated: return with self._lock_if_necessary: if not self._terminated: if cleanup_callable: self._call_locked(cleanup_callable) _THREAD_POOL_EXECUTOR_POOL.release(self._executor) self._executor = None self._thread = None self._terminated = True
dm_control-main
dm_control/_render/executor/render_executor.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. # ============================================================================ """Misc helper functions needed by autowrap.py.""" import collections _MJXMACRO_SUFFIX = "_POINTERS" class Indenter: r"""Callable context manager for tracking string indentation levels. Example usage: ```python idt = Indenter() s = idt("level 0\n") with idt: s += idt("level 1\n") with idt: s += idt("level 2\n") s += idt("level 1 again\n") s += idt("back to level 0\n") print(s) ``` """ def __init__(self, level=0, indent_str=" "): """Initializes an Indenter. Args: level: The initial indentation level. indent_str: The string used to indent each line. """ self.indent_str = indent_str self.level = level def __enter__(self): self.level += 1 return self def __exit__(self, type_, value, traceback): self.level -= 1 def __call__(self, string): return indent(string, self.level, self.indent_str) def indent(s, n=1, indent_str=" "): """Inserts `n * indent_str` at the start of each non-empty line in `s`.""" p = n * indent_str return "".join((p + l) if l.lstrip() else l for l in s.splitlines(True)) class UniqueOrderedDict(collections.OrderedDict): """Subclass of `OrderedDict` that enforces the uniqueness of keys.""" def __setitem__(self, k, v): existing_v = self.get(k) if existing_v is None: super().__setitem__(k, v) elif v != existing_v: raise ValueError("Key '{}' already exists.".format(k)) def macro_struct_name(name, suffix=None): """Converts mjxmacro struct names, e.g. "MJDATA_POINTERS" to "mjdata".""" if suffix is None: suffix = _MJXMACRO_SUFFIX return name[:-len(suffix)].lower() def is_macro_pointer(name): """Returns True if the mjxmacro struct name contains pointer sizes.""" return name.endswith(_MJXMACRO_SUFFIX) def try_coerce_to_num(s, try_types=(int, float)): """Try to coerce string to Python numeric type, return None if empty.""" if not s: return None for try_type in try_types: try: return try_type(s.rstrip("UuFf")) except (ValueError, AttributeError): continue return s def recursive_dict_lookup(key, try_dict, max_depth=10): """Recursively map dictionary keys to values.""" if max_depth < 0: raise KeyError("Maximum recursion depth exceeded") while key in try_dict: key = try_dict[key] return recursive_dict_lookup(key, try_dict, max_depth - 1) return key def comment_line(string, width=79, fill_char="-"): """Wraps `string` in a padded comment line.""" return "# {0:{2}^{1}}\n".format(string, width - 2, fill_char)
dm_control-main
dm_control/autowrap/codegen_util.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================
dm_control-main
dm_control/autowrap/__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. # ============================================================================ """pyparsing definitions and helper functions for parsing MuJoCo headers.""" import pyparsing as pp # NB: Don't enable parser memoization (`pp.ParserElement.enablePackrat()`), # since this results in a ~6x slowdown. NONE = "None" CTYPES_CHAR = "ctypes.c_char" C_TO_CTYPES = { # integers "int": "ctypes.c_int", "unsigned int": "ctypes.c_uint", "char": CTYPES_CHAR, "unsigned char": "ctypes.c_ubyte", "size_t": "ctypes.c_size_t", # floats "float": "ctypes.c_float", "double": "ctypes.c_double", # pointers "void": NONE, } CTYPES_PTRS = {NONE: "ctypes.c_void_p"} CTYPES_TO_NUMPY = { # integers "ctypes.c_int": "np.intc", "ctypes.c_uint": "np.uintc", "ctypes.c_ubyte": "np.ubyte", # floats "ctypes.c_float": "np.float32", "ctypes.c_double": "np.float64", } # Helper functions for constructing recursive parsers. # ------------------------------------------------------------------------------ def _nested_scopes(opening, closing, body): """Constructs a parser for (possibly nested) scopes.""" scope = pp.Forward() scope << pp.Group( # pylint: disable=expression-not-assigned opening + pp.ZeroOrMore(body | scope)("members") + closing) return scope def _nested_if_else(if_, pred, else_, endif, match_if_true, match_if_false): """Constructs a parser for (possibly nested) if...(else)...endif blocks.""" ifelse = pp.Forward() ifelse << pp.Group( # pylint: disable=expression-not-assigned if_ + pred("predicate") + pp.ZeroOrMore(match_if_true | ifelse)("if_true") + pp.Optional(else_ + pp.ZeroOrMore(match_if_false | ifelse)("if_false")) + endif) return ifelse # Some common string patterns to suppress. # ------------------------------------------------------------------------------ (LPAREN, RPAREN, LBRACK, RBRACK, LBRACE, RBRACE, SEMI, COMMA, EQUAL, FSLASH, BSLASH) = list(map(pp.Suppress, "()[]{};,=/\\")) X = (pp.Keyword("X") | pp.Keyword("XMJV")).suppress() EOL = pp.LineEnd().suppress() # Comments, continuation. # ------------------------------------------------------------------------------ COMMENT = pp.Combine( pp.Suppress("//") + pp.Optional(pp.White()).suppress() + pp.SkipTo(pp.LineEnd())) MULTILINE_COMMENT = pp.delimitedList( COMMENT.copy().setWhitespaceChars(" \t"), delim=EOL) CONTINUATION = (BSLASH + pp.LineEnd()).suppress() # Preprocessor directives. # ------------------------------------------------------------------------------ DEFINE = pp.Keyword("#define").suppress() IFDEF = pp.Keyword("#ifdef").suppress() IFNDEF = pp.Keyword("#ifndef").suppress() ELSE = pp.Keyword("#else").suppress() ENDIF = pp.Keyword("#endif").suppress() # Variable names, types, literals etc. # ------------------------------------------------------------------------------ NAME = pp.Word(pp.alphanums + "_") INT = pp.Word(pp.nums + "UuLl") FLOAT = pp.Word(pp.nums + ".+-EeFf") NUMBER = FLOAT | INT # Dimensions can be of the form `[3]`, `[constant_name]` or `[2*constant_name]` ARRAY_DIM = pp.Combine( LBRACK + (INT | NAME) + pp.Optional(pp.Literal("*")) + pp.Optional(INT | NAME) + RBRACK) PTR = pp.Literal("*") EXTERN = pp.Keyword("extern") NATIVE_TYPENAME = pp.MatchFirst([pp.Keyword(n) for n in C_TO_CTYPES.keys()]) # Macros. # ------------------------------------------------------------------------------ HDR_GUARD = DEFINE + "THIRD_PARTY_MUJOCO_HDRS_" # e.g. "#define mjUSEDOUBLE" DEF_FLAG = pp.Group( DEFINE + NAME("name") + (COMMENT("comment") | EOL)).ignore(HDR_GUARD) # e.g. "#define mjMINVAL 1E-14 // minimum value in any denominator" DEF_CONST = pp.Group( DEFINE + NAME("name") + (NUMBER | NAME)("value") + (COMMENT("comment") | EOL)) # e.g. "X( mjtNum*, name_textadr, ntext, 1 )" XDIM = pp.delimitedList( ( pp.Suppress(pp.Keyword("MJ_M") + LPAREN) + NAME + pp.Suppress(RPAREN) ) | NAME | INT, delim="*", combine=True) XMEMBER = pp.Group( X + LPAREN + (NATIVE_TYPENAME | NAME)("typename") + pp.Optional(PTR("ptr")) + COMMA + NAME("name") + COMMA + pp.delimitedList(XDIM, delim=COMMA)("dims") + RPAREN) XMACRO = pp.Group( pp.Optional(COMMENT("comment")) + DEFINE + NAME("name") + CONTINUATION + pp.delimitedList(XMEMBER, delim=CONTINUATION)("members")) # Type/variable declarations. # ------------------------------------------------------------------------------ TYPEDEF = pp.Keyword("typedef").suppress() STRUCT = pp.Keyword("struct") UNION = pp.Keyword("union") ENUM = pp.Keyword("enum").suppress() # e.g. "typedef unsigned char mjtByte; // used for true/false" TYPE_DECL = pp.Group( TYPEDEF + pp.Optional(STRUCT) + (NATIVE_TYPENAME | NAME)("typename") + pp.Optional(PTR("ptr")) + NAME("name") + SEMI + pp.Optional(COMMENT("comment"))) # Declarations of flags/constants/types. UNCOND_DECL = DEF_FLAG | DEF_CONST | TYPE_DECL # Declarations inside (possibly nested) #if(n)def... #else... #endif... blocks. COND_DECL = _nested_if_else(IFDEF, NAME, ELSE, ENDIF, UNCOND_DECL, UNCOND_DECL) # Note: this doesn't work for '#if defined(FLAG)' blocks # e.g. "mjtNum gravity[3]; // gravitational acceleration" STRUCT_MEMBER = pp.Group( pp.Optional(STRUCT("struct")) + (NATIVE_TYPENAME | NAME)("typename") + pp.Optional(PTR("ptr")) + NAME("name") + pp.ZeroOrMore(ARRAY_DIM)("size") + SEMI + pp.Optional(COMMENT("comment"))) # Struct declaration within a union (non-nested). UNION_STRUCT_DECL = pp.Group( STRUCT("struct") + pp.Optional(NAME("typename")) + pp.Optional(COMMENT("comment")) + LBRACE + pp.OneOrMore(STRUCT_MEMBER)("members") + RBRACE + pp.Optional(NAME("name")) + SEMI) ANONYMOUS_UNION_DECL = pp.Group( pp.Optional(MULTILINE_COMMENT("comment")) + UNION("anonymous_union") + LBRACE + pp.OneOrMore( UNION_STRUCT_DECL | STRUCT_MEMBER | COMMENT.suppress())("members") + RBRACE + SEMI) # Multiple (possibly nested) struct declarations. NESTED_STRUCTS = _nested_scopes( opening=(STRUCT + pp.Optional(NAME("typename")) + pp.Optional(COMMENT("comment")) + LBRACE), closing=(RBRACE + pp.Optional(NAME("name")) + SEMI), body=pp.OneOrMore( STRUCT_MEMBER | ANONYMOUS_UNION_DECL | COMMENT.suppress())("members")) BIT_LSHIFT = INT("bit_lshift_a") + pp.Suppress("<<") + INT("bit_lshift_b") ENUM_LINE = pp.Group( NAME("name") + pp.Optional(EQUAL + (INT("value") ^ BIT_LSHIFT)) + pp.Optional(COMMA) + pp.Optional(COMMENT("comment"))) ENUM_DECL = pp.Group( TYPEDEF + ENUM + NAME("typename") + pp.Optional(COMMENT("comment")) + LBRACE + pp.OneOrMore(ENUM_LINE | COMMENT.suppress())("members") + RBRACE + pp.Optional(NAME("name")) + SEMI) # Function declarations. # ------------------------------------------------------------------------------ MJAPI = pp.Keyword("MJAPI").suppress() CONST = pp.Keyword("const") VOID = pp.Group(pp.Keyword("void") + ~PTR).suppress() ARG = pp.Group( pp.Optional(CONST("is_const")) + (NATIVE_TYPENAME | NAME)("typename") + pp.Optional(PTR("ptr")) + NAME("name") + pp.Optional(ARRAY_DIM("size"))) RET = pp.Group( pp.Optional(CONST("is_const")) + (NATIVE_TYPENAME | NAME)("typename") + pp.Optional(PTR("ptr"))) FUNCTION_DECL = ( (VOID | RET("return_value")) + NAME("name") + LPAREN + (VOID | pp.delimitedList(ARG, delim=COMMA)("arguments")) + RPAREN + SEMI) MJAPI_FUNCTION_DECL = pp.Group( pp.Optional(MULTILINE_COMMENT("comment")) + pp.LineStart() + MJAPI + FUNCTION_DECL) # e.g. # // predicate function: set enable/disable based on item category # typedef int (*mjfItemEnable)(int category, void* data); FUNCTION_PTR_TYPE_DECL = pp.Group( pp.Optional(MULTILINE_COMMENT("comment")) + TYPEDEF + RET("return_type") + LPAREN + PTR + NAME("typename") + RPAREN + LPAREN + (VOID | pp.delimitedList(ARG, delim=COMMA)("arguments")) + RPAREN + SEMI) # Global variables. # ------------------------------------------------------------------------------ MJAPI_STRING_ARRAY = ( MJAPI + EXTERN + CONST + pp.Keyword("char") + PTR + NAME("name") + pp.OneOrMore(ARRAY_DIM)("dims") + SEMI) MJAPI_FUNCTION_PTR = MJAPI + EXTERN + NAME("typename") + NAME("name") + SEMI
dm_control-main
dm_control/autowrap/header_parsing.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. # ============================================================================ """Parses MuJoCo header files and generates Python bindings.""" import os import pprint import textwrap from absl import logging from dm_control.autowrap import codegen_util from dm_control.autowrap import header_parsing import pyparsing class BindingGenerator: """Parses declarations from MuJoCo headers and generates Python bindings.""" def __init__(self, enums_dict=None, consts_dict=None, typedefs_dict=None, hints_dict=None, index_dict=None): """Constructs a new HeaderParser instance. The optional arguments listed below can be used to passing in dict-like objects specifying pre-defined declarations. By default empty UniqueOrderedDicts will be instantiated and then populated according to the contents of the headers. Args: enums_dict: Nested mappings from {enum_name: {member_name: value}}. consts_dict: Mapping from {const_name: value}. typedefs_dict: Mapping from {type_name: ctypes_typename}. hints_dict: Mapping from {var_name: shape_tuple}. index_dict: Mapping from {lowercase_struct_name: {var_name: shape_tuple}}. """ self.enums_dict = (enums_dict if enums_dict is not None else codegen_util.UniqueOrderedDict()) self.consts_dict = (consts_dict if consts_dict is not None else codegen_util.UniqueOrderedDict()) self.typedefs_dict = (typedefs_dict if typedefs_dict is not None else codegen_util.UniqueOrderedDict()) self.hints_dict = (hints_dict if hints_dict is not None else codegen_util.UniqueOrderedDict()) self.index_dict = (index_dict if index_dict is not None else codegen_util.UniqueOrderedDict()) def get_consts_and_enums(self): consts_and_enums = self.consts_dict.copy() for enum in self.enums_dict.values(): consts_and_enums.update(enum) return consts_and_enums def resolve_size(self, old_size): """Resolves an array size identifier. The following conversions will be attempted: * If `old_size` is an integer it will be returned as-is. * If `old_size` is a string of the form `"3"` it will be cast to an int. * If `old_size` is a string in `self.consts_dict` then the value of the constant will be returned. * If `old_size` is a string of the form `"3*constant_name"` then the result of `3*constant_value` will be returned. * If `old_size` is a string that does not specify an int constant and cannot be cast to an int (e.g. an identifier for a dynamic dimension, such as `"ncontact"`) then it will be returned as-is. Args: old_size: An int or string. Returns: An int or string. """ if isinstance(old_size, int): return old_size # If it's already an int then there's nothing left to do elif "*" in old_size: # If it's a string specifying a product (such as "2*mjMAXLINEPNT"), # recursively resolve the components to ints and calculate the result. size = 1 sizes = [] is_int = True for part in old_size.split("*"): dim = self.resolve_size(part) sizes.append(dim) if not isinstance(dim, int): is_int = False else: size *= dim if is_int: return size else: return tuple(sizes) else: # Recursively dereference any sizes declared in header macros size = codegen_util.recursive_dict_lookup(old_size, self.get_consts_and_enums()) # Try to coerce the result to an int, return a string if this fails return codegen_util.try_coerce_to_num(size, try_types=(int,)) def get_shape_tuple(self, old_size, squeeze=False): """Generates a shape tuple from parser results. Args: old_size: Either a `pyparsing.ParseResults`, or a valid int or string input to `self.resolve_size` (see method docstring for further details). squeeze: If True, any dimensions that are statically defined as 1 will be removed from the shape tuple. Returns: A shape tuple containing ints for dimensions that are statically defined, and string size identifiers for dimensions that can only be determined at runtime. """ if isinstance(old_size, pyparsing.ParseResults): # For multi-dimensional arrays, convert each dimension separately shape = tuple(self.resolve_size(dim) for dim in old_size) else: shape = (self.resolve_size(old_size),) if squeeze: shape = tuple(d for d in shape if d != 1) # Remove singleton dimensions return shape def resolve_typename(self, old_ctypes_typename): """Gets a qualified ctypes typename from typedefs_dict and C_TO_CTYPES.""" # Recursively dereference any typenames declared in self.typedefs_dict new_ctypes_typename = codegen_util.recursive_dict_lookup( old_ctypes_typename, self.typedefs_dict) # Try to convert to a ctypes native typename new_ctypes_typename = header_parsing.C_TO_CTYPES.get( new_ctypes_typename, new_ctypes_typename) if new_ctypes_typename == old_ctypes_typename: logging.warning("Could not resolve typename '%s'", old_ctypes_typename) return new_ctypes_typename # Parsing functions. # ---------------------------------------------------------------------------- def parse_hints(self, xmacro_src): """Parses mjxmacro.h, update self.hints_dict.""" parser = header_parsing.XMACRO for tokens, _, _ in parser.scanString(xmacro_src): for xmacro in tokens: for member in xmacro.members: # "Squeeze out" singleton dimensions. shape = self.get_shape_tuple(member.dims, squeeze=True) self.hints_dict.update({member.name: shape}) if codegen_util.is_macro_pointer(xmacro.name): struct_name = codegen_util.macro_struct_name(xmacro.name) if struct_name not in self.index_dict: self.index_dict[struct_name] = {} self.index_dict[struct_name].update({member.name: shape}) def parse_enums(self, src): """Parses mj*.h, update self.enums_dict.""" parser = header_parsing.ENUM_DECL for tokens, _, _ in parser.scanString(src): for enum in tokens: members = codegen_util.UniqueOrderedDict() value = 0 for member in enum.members: # Leftward bitshift if member.bit_lshift_a: value = int(member.bit_lshift_a) << int(member.bit_lshift_b) # Assignment elif member.value: value = int(member.value) # Implicit count else: value += 1 members.update({member.name: value}) self.enums_dict.update({enum.name: members}) def parse_consts_typedefs(self, src): """Updates self.consts_dict, self.typedefs_dict.""" parser = (header_parsing.COND_DECL | header_parsing.UNCOND_DECL) for tokens, _, _ in parser.scanString(src): self.recurse_into_conditionals(tokens) def recurse_into_conditionals(self, tokens): """Called recursively within nested #if(n)def... #else... #endif blocks.""" for token in tokens: # Another nested conditional block if token.predicate: if (token.predicate in self.get_consts_and_enums() and self.get_consts_and_enums()[token.predicate]): self.recurse_into_conditionals(token.if_true) else: self.recurse_into_conditionals(token.if_false) # One or more declarations else: if token.typename: self.typedefs_dict.update({token.name: token.typename}) elif token.value: value = codegen_util.try_coerce_to_num(token.value) # Avoid adding function aliases. if isinstance(value, str): continue else: self.consts_dict.update({token.name: value}) else: self.consts_dict.update({token.name: True}) # Code generation methods # ---------------------------------------------------------------------------- def make_header(self, imports=()): """Returns a header string for an auto-generated Python source file.""" docstring = textwrap.dedent(""" \"\"\"Automatically generated by {scriptname:}. MuJoCo header version: {mujoco_version:} \"\"\" """.format(scriptname=os.path.split(__file__)[-1], mujoco_version=self.consts_dict["mjVERSION_HEADER"])) docstring = docstring[1:] # Strip the leading line break. return "\n".join([docstring] + list(imports) + ["\n"]) def write_consts(self, fname): """Write constants.""" imports = [ "# pylint: disable=invalid-name", ] with open(fname, "w") as f: f.write(self.make_header(imports)) f.write(codegen_util.comment_line("Constants") + "\n") for name, value in self.consts_dict.items(): f.write("{0} = {1}\n".format(name, value)) f.write("\n" + codegen_util.comment_line("End of generated code")) def write_enums(self, fname): """Write enum definitions.""" with open(fname, "w") as f: imports = [ "import collections", "# pylint: disable=invalid-name", "# pylint: disable=line-too-long", ] f.write(self.make_header(imports)) f.write(codegen_util.comment_line("Enums")) for enum_name, members in self.enums_dict.items(): fields = ["\"{}\"".format(name) for name in members.keys()] values = [str(value) for value in members.values()] s = textwrap.dedent(""" {0} = collections.namedtuple( "{0}", [{1}] )({2}) """).format(enum_name, ",\n ".join(fields), ", ".join(values)) f.write(s) f.write("\n" + codegen_util.comment_line("End of generated code")) def write_index_dict(self, fname): """Write file containing array shape information for indexing.""" pp = pprint.PrettyPrinter() output_string = pp.pformat(dict(self.index_dict)) indent = codegen_util.Indenter() imports = [ "# pylint: disable=bad-continuation", "# pylint: disable=line-too-long", ] with open(fname, "w") as f: f.write(self.make_header(imports)) f.write("array_sizes = (\n") with indent: f.write(output_string) f.write("\n)") f.write("\n" + codegen_util.comment_line("End of generated code"))
dm_control-main
dm_control/autowrap/binding_generator.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. # ============================================================================ r"""Automatically generates ctypes Python bindings for MuJoCo. Parses the following MuJoCo header files: mjdata.h mjmodel.h mjrender.h mjui.h mjvisualize.h mjxmacro.h mujoco.h; generates the following Python source files: constants.py: constants enums.py: enums sizes.py: size information for dynamically-shaped arrays Example usage: autowrap --header_paths='/path/to/mjmodel.h /path/to/mjdata.h ...' \ --output_dir=/path/to/mjbindings """ import collections import io import os from absl import app from absl import flags from absl import logging from dm_control.autowrap import binding_generator from dm_control.autowrap import codegen_util _MJMODEL_H = "mjmodel.h" _MJXMACRO_H = "mjxmacro.h" FLAGS = flags.FLAGS flags.DEFINE_spaceseplist( "header_paths", None, "Space-separated list of paths to MuJoCo header files.") flags.DEFINE_string("output_dir", None, "Path to output directory for wrapper source files.") def main(unused_argv): special_header_paths = {} # Get the path to the mjmodel and mjxmacro header files. # These header files need special handling. for header in (_MJMODEL_H, _MJXMACRO_H): for path in FLAGS.header_paths: if path.endswith(header): special_header_paths[header] = path break if header not in special_header_paths: logging.fatal("List of inputs must contain a path to %s", header) # Make sure mjmodel.h is parsed first, since it is included by other headers. srcs = codegen_util.UniqueOrderedDict() sorted_header_paths = sorted(FLAGS.header_paths) sorted_header_paths.remove(special_header_paths[_MJMODEL_H]) sorted_header_paths.insert(0, special_header_paths[_MJMODEL_H]) for p in sorted_header_paths: with io.open(p, "r", errors="ignore") as f: srcs[p] = f.read() # consts_dict should be a codegen_util.UniqueOrderedDict. # This is a temporary workaround due to the fact that the parser does not yet # handle nested `#if define(predicate)` blocks, which results in some # constants being parsed twice. We therefore can't enforce the uniqueness of # the keys in `consts_dict`. As of MuJoCo v1.30 there is only a single problem # block beginning on line 10 in mujoco.h, and a single constant is affected # (MJAPI). consts_dict = collections.OrderedDict() # These are commented in `mjdata.h` but have no macros in `mjxmacro.h`. hints_dict = codegen_util.UniqueOrderedDict({"buffer": ("nbuffer",), "stack": ("nstack",)}) parser = binding_generator.BindingGenerator( consts_dict=consts_dict, hints_dict=hints_dict) # Parse enums. for pth, src in srcs.items(): if pth is not special_header_paths[_MJXMACRO_H]: parser.parse_enums(src) # Parse constants and type declarations. for pth, src in srcs.items(): if pth is not special_header_paths[_MJXMACRO_H]: parser.parse_consts_typedefs(src) # Get shape hints from mjxmacro.h. parser.parse_hints(srcs[special_header_paths[_MJXMACRO_H]]) # Create the output directory if it doesn't already exist. if not os.path.exists(FLAGS.output_dir): os.makedirs(FLAGS.output_dir) # Generate Python source files and write them to the output directory. parser.write_consts(os.path.join(FLAGS.output_dir, "constants.py")) parser.write_enums(os.path.join(FLAGS.output_dir, "enums.py")) parser.write_index_dict(os.path.join(FLAGS.output_dir, "sizes.py")) if __name__ == "__main__": flags.mark_flag_as_required("header_paths") flags.mark_flag_as_required("output_dir") app.run(main)
dm_control-main
dm_control/autowrap/autowrap.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. # ============================================================================ """Quadruped Domain.""" import collections from dm_control import mujoco from dm_control.mujoco.wrapper import mjbindings from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.utils import containers from dm_control.utils import rewards from dm_control.utils import xml_tools from lxml import etree import numpy as np from scipy import ndimage enums = mjbindings.enums mjlib = mjbindings.mjlib _DEFAULT_TIME_LIMIT = 20 _CONTROL_TIMESTEP = .02 # Horizontal speeds above which the move reward is 1. _RUN_SPEED = 5 _WALK_SPEED = 0.5 # Constants related to terrain generation. _HEIGHTFIELD_ID = 0 _TERRAIN_SMOOTHNESS = 0.15 # 0.0: maximally bumpy; 1.0: completely smooth. _TERRAIN_BUMP_SCALE = 2 # Spatial scale of terrain bumps (in meters). # Named model elements. _TOES = ['toe_front_left', 'toe_back_left', 'toe_back_right', 'toe_front_right'] _WALLS = ['wall_px', 'wall_py', 'wall_nx', 'wall_ny'] SUITE = containers.TaggedTasks() def make_model(floor_size=None, terrain=False, rangefinders=False, walls_and_ball=False): """Returns the model XML string.""" xml_string = common.read_model('quadruped.xml') parser = etree.XMLParser(remove_blank_text=True) mjcf = etree.XML(xml_string, parser) # Set floor size. if floor_size is not None: floor_geom = mjcf.find('.//geom[@name=\'floor\']') floor_geom.attrib['size'] = f'{floor_size} {floor_size} .5' # Remove walls, ball and target. if not walls_and_ball: for wall in _WALLS: wall_geom = xml_tools.find_element(mjcf, 'geom', wall) wall_geom.getparent().remove(wall_geom) # Remove ball. ball_body = xml_tools.find_element(mjcf, 'body', 'ball') ball_body.getparent().remove(ball_body) # Remove target. target_site = xml_tools.find_element(mjcf, 'site', 'target') target_site.getparent().remove(target_site) # Remove terrain. if not terrain: terrain_geom = xml_tools.find_element(mjcf, 'geom', 'terrain') terrain_geom.getparent().remove(terrain_geom) # Remove rangefinders if they're not used, as range computations can be # expensive, especially in a scene with heightfields. if not rangefinders: rangefinder_sensors = mjcf.findall('.//rangefinder') for rf in rangefinder_sensors: rf.getparent().remove(rf) return etree.tostring(mjcf, pretty_print=True) @SUITE.add() def walk(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Walk task.""" xml_string = make_model(floor_size=_DEFAULT_TIME_LIMIT * _WALK_SPEED) physics = Physics.from_xml_string(xml_string, common.ASSETS) task = Move(desired_speed=_WALK_SPEED, random=random) environment_kwargs = environment_kwargs or {} return control.Environment(physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) @SUITE.add() def run(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Run task.""" xml_string = make_model(floor_size=_DEFAULT_TIME_LIMIT * _RUN_SPEED) physics = Physics.from_xml_string(xml_string, common.ASSETS) task = Move(desired_speed=_RUN_SPEED, random=random) environment_kwargs = environment_kwargs or {} return control.Environment(physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) @SUITE.add() def escape(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Escape task.""" xml_string = make_model(floor_size=40, terrain=True, rangefinders=True) physics = Physics.from_xml_string(xml_string, common.ASSETS) task = Escape(random=random) environment_kwargs = environment_kwargs or {} return control.Environment(physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) @SUITE.add() def fetch(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Fetch task.""" xml_string = make_model(walls_and_ball=True) physics = Physics.from_xml_string(xml_string, common.ASSETS) task = Fetch(random=random) environment_kwargs = environment_kwargs or {} return control.Environment(physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) class Physics(mujoco.Physics): """Physics simulation with additional features for the Quadruped domain.""" def _reload_from_data(self, data): super()._reload_from_data(data) # Clear cached sensor names when the physics is reloaded. self._sensor_types_to_names = {} self._hinge_names = [] def _get_sensor_names(self, *sensor_types): try: sensor_names = self._sensor_types_to_names[sensor_types] except KeyError: [sensor_ids] = np.where(np.in1d(self.model.sensor_type, sensor_types)) sensor_names = [self.model.id2name(s_id, 'sensor') for s_id in sensor_ids] self._sensor_types_to_names[sensor_types] = sensor_names return sensor_names def torso_upright(self): """Returns the dot-product of the torso z-axis and the global z-axis.""" return np.asarray(self.named.data.xmat['torso', 'zz']) def torso_velocity(self): """Returns the velocity of the torso, in the local frame.""" return self.named.data.sensordata['velocimeter'].copy() def egocentric_state(self): """Returns the state without global orientation or position.""" if not self._hinge_names: [hinge_ids] = np.nonzero(self.model.jnt_type == enums.mjtJoint.mjJNT_HINGE) self._hinge_names = [self.model.id2name(j_id, 'joint') for j_id in hinge_ids] return np.hstack((self.named.data.qpos[self._hinge_names], self.named.data.qvel[self._hinge_names], self.data.act)) def toe_positions(self): """Returns toe positions in egocentric frame.""" torso_frame = self.named.data.xmat['torso'].reshape(3, 3) torso_pos = self.named.data.xpos['torso'] torso_to_toe = self.named.data.xpos[_TOES] - torso_pos return torso_to_toe.dot(torso_frame) def force_torque(self): """Returns scaled force/torque sensor readings at the toes.""" force_torque_sensors = self._get_sensor_names(enums.mjtSensor.mjSENS_FORCE, enums.mjtSensor.mjSENS_TORQUE) return np.arcsinh(self.named.data.sensordata[force_torque_sensors]) def imu(self): """Returns IMU-like sensor readings.""" imu_sensors = self._get_sensor_names(enums.mjtSensor.mjSENS_GYRO, enums.mjtSensor.mjSENS_ACCELEROMETER) return self.named.data.sensordata[imu_sensors] def rangefinder(self): """Returns scaled rangefinder sensor readings.""" rf_sensors = self._get_sensor_names(enums.mjtSensor.mjSENS_RANGEFINDER) rf_readings = self.named.data.sensordata[rf_sensors] no_intersection = -1.0 return np.where(rf_readings == no_intersection, 1.0, np.tanh(rf_readings)) def origin_distance(self): """Returns the distance from the origin to the workspace.""" return np.asarray(np.linalg.norm(self.named.data.site_xpos['workspace'])) def origin(self): """Returns origin position in the torso frame.""" torso_frame = self.named.data.xmat['torso'].reshape(3, 3) torso_pos = self.named.data.xpos['torso'] return -torso_pos.dot(torso_frame) def ball_state(self): """Returns ball position and velocity relative to the torso frame.""" data = self.named.data torso_frame = data.xmat['torso'].reshape(3, 3) ball_rel_pos = data.xpos['ball'] - data.xpos['torso'] ball_rel_vel = data.qvel['ball_root'][:3] - data.qvel['root'][:3] ball_rot_vel = data.qvel['ball_root'][3:] ball_state = np.vstack((ball_rel_pos, ball_rel_vel, ball_rot_vel)) return ball_state.dot(torso_frame).ravel() def target_position(self): """Returns target position in torso frame.""" torso_frame = self.named.data.xmat['torso'].reshape(3, 3) torso_pos = self.named.data.xpos['torso'] torso_to_target = self.named.data.site_xpos['target'] - torso_pos return torso_to_target.dot(torso_frame) def ball_to_target_distance(self): """Returns horizontal distance from the ball to the target.""" ball_to_target = (self.named.data.site_xpos['target'] - self.named.data.xpos['ball']) return np.linalg.norm(ball_to_target[:2]) def self_to_ball_distance(self): """Returns horizontal distance from the quadruped workspace to the ball.""" self_to_ball = (self.named.data.site_xpos['workspace'] -self.named.data.xpos['ball']) return np.linalg.norm(self_to_ball[:2]) def _find_non_contacting_height(physics, orientation, x_pos=0.0, y_pos=0.0): """Find a height with no contacts given a body orientation. Args: physics: An instance of `Physics`. orientation: A quaternion. x_pos: A float. Position along global x-axis. y_pos: A float. Position along global y-axis. Raises: RuntimeError: If a non-contacting configuration has not been found after 10,000 attempts. """ z_pos = 0.0 # Start embedded in the floor. num_contacts = 1 num_attempts = 0 # Move up in 1cm increments until no contacts. while num_contacts > 0: try: with physics.reset_context(): physics.named.data.qpos['root'][:3] = x_pos, y_pos, z_pos physics.named.data.qpos['root'][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 num_attempts += 1 if num_attempts > 10000: raise RuntimeError('Failed to find a non-contacting configuration.') def _common_observations(physics): """Returns the observations common to all tasks.""" obs = collections.OrderedDict() obs['egocentric_state'] = physics.egocentric_state() obs['torso_velocity'] = physics.torso_velocity() obs['torso_upright'] = physics.torso_upright() obs['imu'] = physics.imu() obs['force_torque'] = physics.force_torque() return obs def _upright_reward(physics, deviation_angle=0): """Returns a reward proportional to how upright the torso is. Args: physics: an instance of `Physics`. 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)) return rewards.tolerance( physics.torso_upright(), bounds=(deviation, float('inf')), sigmoid='linear', margin=1 + deviation, value_at_margin=0) class Move(base.Task): """A quadruped task solved by moving forward at a designated speed.""" def __init__(self, desired_speed, random=None): """Initializes an instance of `Move`. Args: desired_speed: A float. If this value is zero, reward is given simply for standing upright. Otherwise this specifies the horizontal velocity at which the velocity-dependent reward component is maximized. random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). """ self._desired_speed = desired_speed super().__init__(random=random) def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode. Args: physics: An instance of `Physics`. """ # Initial configuration. orientation = self.random.randn(4) orientation /= np.linalg.norm(orientation) _find_non_contacting_height(physics, orientation) super().initialize_episode(physics) def get_observation(self, physics): """Returns an observation to the agent.""" return _common_observations(physics) def get_reward(self, physics): """Returns a reward to the agent.""" # Move reward term. move_reward = rewards.tolerance( physics.torso_velocity()[0], bounds=(self._desired_speed, float('inf')), margin=self._desired_speed, value_at_margin=0.5, sigmoid='linear') return _upright_reward(physics) * move_reward class Escape(base.Task): """A quadruped task solved by escaping a bowl-shaped terrain.""" def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode. Args: physics: An instance of `Physics`. """ # Get heightfield resolution, assert that it is square. res = physics.model.hfield_nrow[_HEIGHTFIELD_ID] assert res == physics.model.hfield_ncol[_HEIGHTFIELD_ID] # 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), .04, 1) bowl_shape = .5 - np.cos(2*np.pi*radius)/2 # Random smooth bumps. terrain_size = 2 * physics.model.hfield_size[_HEIGHTFIELD_ID, 0] bump_res = int(terrain_size / _TERRAIN_BUMP_SCALE) bumps = self.random.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.model.hfield_adr[_HEIGHTFIELD_ID] physics.model.hfield_data[start_idx:start_idx+res**2] = terrain.ravel() super().initialize_episode(physics) # 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, _HEIGHTFIELD_ID) # Initial configuration. orientation = self.random.randn(4) orientation /= np.linalg.norm(orientation) _find_non_contacting_height(physics, orientation) def get_observation(self, physics): """Returns an observation to the agent.""" obs = _common_observations(physics) obs['origin'] = physics.origin() obs['rangefinder'] = physics.rangefinder() return obs def get_reward(self, physics): """Returns a reward to the agent.""" # Escape reward term. terrain_size = physics.model.hfield_size[_HEIGHTFIELD_ID, 0] escape_reward = rewards.tolerance( physics.origin_distance(), bounds=(terrain_size, float('inf')), margin=terrain_size, value_at_margin=0, sigmoid='linear') return _upright_reward(physics, deviation_angle=20) * escape_reward class Fetch(base.Task): """A quadruped task solved by bringing a ball to the origin.""" def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode. Args: physics: An instance of `Physics`. """ # Initial configuration, random azimuth and horizontal position. azimuth = self.random.uniform(0, 2*np.pi) orientation = np.array((np.cos(azimuth/2), 0, 0, np.sin(azimuth/2))) spawn_radius = 0.9 * physics.named.model.geom_size['floor', 0] x_pos, y_pos = self.random.uniform(-spawn_radius, spawn_radius, size=(2,)) _find_non_contacting_height(physics, orientation, x_pos, y_pos) # Initial ball state. physics.named.data.qpos['ball_root'][:2] = self.random.uniform( -spawn_radius, spawn_radius, size=(2,)) physics.named.data.qpos['ball_root'][2] = 2 physics.named.data.qvel['ball_root'][:2] = 5*self.random.randn(2) super().initialize_episode(physics) def get_observation(self, physics): """Returns an observation to the agent.""" obs = _common_observations(physics) obs['ball_state'] = physics.ball_state() obs['target_position'] = physics.target_position() return obs def get_reward(self, physics): """Returns a reward to the agent.""" # Reward for moving close to the ball. arena_radius = physics.named.model.geom_size['floor', 0] * np.sqrt(2) workspace_radius = physics.named.model.site_size['workspace', 0] ball_radius = physics.named.model.geom_size['ball', 0] reach_reward = rewards.tolerance( physics.self_to_ball_distance(), bounds=(0, workspace_radius+ball_radius), sigmoid='linear', margin=arena_radius, value_at_margin=0) # Reward for bringing the ball to the target. target_radius = physics.named.model.site_size['target', 0] fetch_reward = rewards.tolerance( physics.ball_to_target_distance(), bounds=(0, target_radius), sigmoid='linear', margin=arena_radius, value_at_margin=0) reach_then_fetch = reach_reward * (0.5 + 0.5*fetch_reward) return _upright_reward(physics) * reach_then_fetch
dm_control-main
dm_control/suite/quadruped.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. # ============================================================================ """Humanoid_CMU Domain.""" import collections from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.suite.utils import randomizers from dm_control.utils import containers from dm_control.utils import rewards import numpy as np _DEFAULT_TIME_LIMIT = 20 _CONTROL_TIMESTEP = 0.02 # Height of head above which stand reward is 1. _STAND_HEIGHT = 1.4 # Horizontal speeds above which move reward is 1. _WALK_SPEED = 1 _RUN_SPEED = 10 SUITE = containers.TaggedTasks() def get_model_and_assets(): """Returns a tuple containing the model XML string and a dict of assets.""" return common.read_model('humanoid_CMU.xml'), common.ASSETS @SUITE.add() def stand(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Stand task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = HumanoidCMU(move_speed=0, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) @SUITE.add() def walk(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Walk task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = HumanoidCMU(move_speed=_WALK_SPEED, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) @SUITE.add() def run(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Run task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = HumanoidCMU(move_speed=_RUN_SPEED, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) class Physics(mujoco.Physics): """Physics simulation with additional features for the humanoid_CMU domain.""" def thorax_upright(self): """Returns projection from y-axes of thorax to the z-axes of world.""" return self.named.data.xmat['thorax', 'zy'] def head_height(self): """Returns the height of the head.""" return self.named.data.xpos['head', 'z'] def center_of_mass_position(self): """Returns position of the center-of-mass.""" return self.named.data.subtree_com['thorax'] def center_of_mass_velocity(self): """Returns the velocity of the center-of-mass.""" return self.named.data.sensordata['thorax_subtreelinvel'].copy() def torso_vertical_orientation(self): """Returns the z-projection of the thorax orientation matrix.""" return self.named.data.xmat['thorax', ['zx', 'zy', 'zz']] def joint_angles(self): """Returns the state without global orientation or position.""" return self.data.qpos[7:].copy() # Skip the 7 DoFs of the free root joint. def extremities(self): """Returns end effector positions in egocentric frame.""" torso_frame = self.named.data.xmat['thorax'].reshape(3, 3) torso_pos = self.named.data.xpos['thorax'] positions = [] for side in ('l', 'r'): for limb in ('hand', 'foot'): torso_to_limb = self.named.data.xpos[side + limb] - torso_pos positions.append(torso_to_limb.dot(torso_frame)) return np.hstack(positions) class HumanoidCMU(base.Task): """A task for the CMU Humanoid.""" def __init__(self, move_speed, random=None): """Initializes an instance of `Humanoid_CMU`. Args: move_speed: A float. If this value is zero, reward is given simply for standing up. Otherwise this specifies a target horizontal velocity for the walking task. random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). """ self._move_speed = move_speed super().__init__(random=random) def initialize_episode(self, physics): """Sets a random collision-free configuration at the start of each episode. Args: physics: An instance of `Physics`. """ penetrating = True while penetrating: randomizers.randomize_limited_and_rotational_joints( physics, self.random) # Check for collisions. physics.after_reset() penetrating = physics.data.ncon > 0 super().initialize_episode(physics) def get_observation(self, physics): """Returns a set of egocentric features.""" obs = collections.OrderedDict() obs['joint_angles'] = physics.joint_angles() obs['head_height'] = physics.head_height() obs['extremities'] = physics.extremities() obs['torso_vertical'] = physics.torso_vertical_orientation() obs['com_velocity'] = physics.center_of_mass_velocity() obs['velocity'] = physics.velocity() return obs def get_reward(self, physics): """Returns a reward to the agent.""" standing = rewards.tolerance(physics.head_height(), bounds=(_STAND_HEIGHT, float('inf')), margin=_STAND_HEIGHT/4) upright = rewards.tolerance(physics.thorax_upright(), bounds=(0.9, float('inf')), sigmoid='linear', margin=1.9, value_at_margin=0) stand_reward = standing * upright small_control = rewards.tolerance(physics.control(), margin=1, value_at_margin=0, sigmoid='quadratic').mean() small_control = (4 + small_control) / 5 if self._move_speed == 0: horizontal_velocity = physics.center_of_mass_velocity()[[0, 1]] dont_move = rewards.tolerance(horizontal_velocity, margin=2).mean() return small_control * stand_reward * dont_move else: com_velocity = np.linalg.norm(physics.center_of_mass_velocity()[[0, 1]]) move = rewards.tolerance(com_velocity, bounds=(self._move_speed, float('inf')), margin=self._move_speed, value_at_margin=0, sigmoid='linear') move = (5*move + 1) / 6 return small_control * stand_reward * move
dm_control-main
dm_control/suite/humanoid_CMU.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. # ============================================================================ """Humanoid Domain.""" import collections from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.suite.utils import randomizers from dm_control.utils import containers from dm_control.utils import rewards import numpy as np _DEFAULT_TIME_LIMIT = 25 _CONTROL_TIMESTEP = .025 # Height of head above which stand reward is 1. _STAND_HEIGHT = 1.4 # Horizontal speeds above which move reward is 1. _WALK_SPEED = 1 _RUN_SPEED = 10 SUITE = containers.TaggedTasks() def get_model_and_assets(): """Returns a tuple containing the model XML string and a dict of assets.""" return common.read_model('humanoid.xml'), common.ASSETS @SUITE.add('benchmarking') def stand(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Stand task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Humanoid(move_speed=0, pure_state=False, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) @SUITE.add('benchmarking') def walk(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Walk task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Humanoid(move_speed=_WALK_SPEED, pure_state=False, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) @SUITE.add('benchmarking') def run(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Run task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Humanoid(move_speed=_RUN_SPEED, pure_state=False, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) @SUITE.add() def run_pure_state(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Run task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Humanoid(move_speed=_RUN_SPEED, pure_state=True, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) class Physics(mujoco.Physics): """Physics simulation with additional features for the Walker domain.""" def torso_upright(self): """Returns projection from z-axes of torso to the z-axes of world.""" return self.named.data.xmat['torso', 'zz'] def head_height(self): """Returns the height of the torso.""" return self.named.data.xpos['head', 'z'] def center_of_mass_position(self): """Returns position of the center-of-mass.""" return self.named.data.subtree_com['torso'].copy() def center_of_mass_velocity(self): """Returns the velocity of the center-of-mass.""" return self.named.data.sensordata['torso_subtreelinvel'].copy() def torso_vertical_orientation(self): """Returns the z-projection of the torso orientation matrix.""" return self.named.data.xmat['torso', ['zx', 'zy', 'zz']] def joint_angles(self): """Returns the state without global orientation or position.""" return self.data.qpos[7:].copy() # Skip the 7 DoFs of the free root joint. def extremities(self): """Returns end effector positions in egocentric frame.""" torso_frame = self.named.data.xmat['torso'].reshape(3, 3) torso_pos = self.named.data.xpos['torso'] positions = [] for side in ('left_', 'right_'): for limb in ('hand', 'foot'): torso_to_limb = self.named.data.xpos[side + limb] - torso_pos positions.append(torso_to_limb.dot(torso_frame)) return np.hstack(positions) class Humanoid(base.Task): """A humanoid task.""" def __init__(self, move_speed, pure_state, random=None): """Initializes an instance of `Humanoid`. Args: move_speed: A float. If this value is zero, reward is given simply for standing up. Otherwise this specifies a target horizontal velocity for the walking task. pure_state: A bool. Whether the observations consist of the pure MuJoCo state or includes some useful features thereof. random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). """ self._move_speed = move_speed self._pure_state = pure_state super().__init__(random=random) def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode. Args: physics: An instance of `Physics`. """ # Find a collision-free random initial configuration. penetrating = True while penetrating: randomizers.randomize_limited_and_rotational_joints(physics, self.random) # Check for collisions. physics.after_reset() penetrating = physics.data.ncon > 0 super().initialize_episode(physics) def get_observation(self, physics): """Returns either the pure state or a set of egocentric features.""" obs = collections.OrderedDict() if self._pure_state: obs['position'] = physics.position() obs['velocity'] = physics.velocity() else: obs['joint_angles'] = physics.joint_angles() obs['head_height'] = physics.head_height() obs['extremities'] = physics.extremities() obs['torso_vertical'] = physics.torso_vertical_orientation() obs['com_velocity'] = physics.center_of_mass_velocity() obs['velocity'] = physics.velocity() return obs def get_reward(self, physics): """Returns a reward to the agent.""" standing = rewards.tolerance(physics.head_height(), bounds=(_STAND_HEIGHT, float('inf')), margin=_STAND_HEIGHT/4) upright = rewards.tolerance(physics.torso_upright(), bounds=(0.9, float('inf')), sigmoid='linear', margin=1.9, value_at_margin=0) stand_reward = standing * upright small_control = rewards.tolerance(physics.control(), margin=1, value_at_margin=0, sigmoid='quadratic').mean() small_control = (4 + small_control) / 5 if self._move_speed == 0: horizontal_velocity = physics.center_of_mass_velocity()[[0, 1]] dont_move = rewards.tolerance(horizontal_velocity, margin=2).mean() return small_control * stand_reward * dont_move else: com_velocity = np.linalg.norm(physics.center_of_mass_velocity()[[0, 1]]) move = rewards.tolerance(com_velocity, bounds=(self._move_speed, float('inf')), margin=self._move_speed, value_at_margin=0, sigmoid='linear') move = (5*move + 1) / 6 return small_control * stand_reward * move
dm_control-main
dm_control/suite/humanoid.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. # ============================================================================ """Ball-in-Cup Domain.""" import collections from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.utils import containers _DEFAULT_TIME_LIMIT = 20 # (seconds) _CONTROL_TIMESTEP = .02 # (seconds) SUITE = containers.TaggedTasks() def get_model_and_assets(): """Returns a tuple containing the model XML string and a dict of assets.""" return common.read_model('ball_in_cup.xml'), common.ASSETS @SUITE.add('benchmarking', 'easy') def catch(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Ball-in-Cup task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = BallInCup(random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) class Physics(mujoco.Physics): """Physics with additional features for the Ball-in-Cup domain.""" def ball_to_target(self): """Returns the vector from the ball to the target.""" target = self.named.data.site_xpos['target', ['x', 'z']] ball = self.named.data.xpos['ball', ['x', 'z']] return target - ball def in_target(self): """Returns 1 if the ball is in the target, 0 otherwise.""" ball_to_target = abs(self.ball_to_target()) target_size = self.named.model.site_size['target', [0, 2]] ball_size = self.named.model.geom_size['ball', 0] return float(all(ball_to_target < target_size - ball_size)) class BallInCup(base.Task): """The Ball-in-Cup task. Put the ball in the cup.""" def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode. Args: physics: An instance of `Physics`. """ # Find a collision-free random initial position of the ball. penetrating = True while penetrating: # Assign a random ball position. physics.named.data.qpos['ball_x'] = self.random.uniform(-.2, .2) physics.named.data.qpos['ball_z'] = self.random.uniform(.2, .5) # Check for collisions. physics.after_reset() penetrating = physics.data.ncon > 0 super().initialize_episode(physics) def get_observation(self, physics): """Returns an observation of the state.""" obs = collections.OrderedDict() obs['position'] = physics.position() obs['velocity'] = physics.velocity() return obs def get_reward(self, physics): """Returns a sparse reward.""" return physics.in_target()
dm_control-main
dm_control/suite/ball_in_cup.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. # ============================================================================ """Planar Manipulator domain.""" import collections from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.utils import containers from dm_control.utils import rewards from dm_control.utils import xml_tools from lxml import etree import numpy as np _CLOSE = .01 # (Meters) Distance below which a thing is considered close. _CONTROL_TIMESTEP = .01 # (Seconds) _TIME_LIMIT = 10 # (Seconds) _P_IN_HAND = .1 # Probabillity of object-in-hand initial state _P_IN_TARGET = .1 # Probabillity of object-in-target initial state _ARM_JOINTS = ['arm_root', 'arm_shoulder', 'arm_elbow', 'arm_wrist', 'finger', 'fingertip', 'thumb', 'thumbtip'] _ALL_PROPS = frozenset(['ball', 'target_ball', 'cup', 'peg', 'target_peg', 'slot']) _TOUCH_SENSORS = ['palm_touch', 'finger_touch', 'thumb_touch', 'fingertip_touch', 'thumbtip_touch'] SUITE = containers.TaggedTasks() def make_model(use_peg, insert): """Returns a tuple containing the model XML string and a dict of assets.""" xml_string = common.read_model('manipulator.xml') parser = etree.XMLParser(remove_blank_text=True) mjcf = etree.XML(xml_string, parser) # Select the desired prop. if use_peg: required_props = ['peg', 'target_peg'] if insert: required_props += ['slot'] else: required_props = ['ball', 'target_ball'] if insert: required_props += ['cup'] # Remove unused props for unused_prop in _ALL_PROPS.difference(required_props): prop = xml_tools.find_element(mjcf, 'body', unused_prop) prop.getparent().remove(prop) return etree.tostring(mjcf, pretty_print=True), common.ASSETS @SUITE.add('benchmarking', 'hard') def bring_ball(fully_observable=True, time_limit=_TIME_LIMIT, random=None, environment_kwargs=None): """Returns manipulator bring task with the ball prop.""" use_peg = False insert = False physics = Physics.from_xml_string(*make_model(use_peg, insert)) task = Bring(use_peg=use_peg, insert=insert, fully_observable=fully_observable, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, control_timestep=_CONTROL_TIMESTEP, time_limit=time_limit, **environment_kwargs) @SUITE.add('hard') def bring_peg(fully_observable=True, time_limit=_TIME_LIMIT, random=None, environment_kwargs=None): """Returns manipulator bring task with the peg prop.""" use_peg = True insert = False physics = Physics.from_xml_string(*make_model(use_peg, insert)) task = Bring(use_peg=use_peg, insert=insert, fully_observable=fully_observable, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, control_timestep=_CONTROL_TIMESTEP, time_limit=time_limit, **environment_kwargs) @SUITE.add('hard') def insert_ball(fully_observable=True, time_limit=_TIME_LIMIT, random=None, environment_kwargs=None): """Returns manipulator insert task with the ball prop.""" use_peg = False insert = True physics = Physics.from_xml_string(*make_model(use_peg, insert)) task = Bring(use_peg=use_peg, insert=insert, fully_observable=fully_observable, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, control_timestep=_CONTROL_TIMESTEP, time_limit=time_limit, **environment_kwargs) @SUITE.add('hard') def insert_peg(fully_observable=True, time_limit=_TIME_LIMIT, random=None, environment_kwargs=None): """Returns manipulator insert task with the peg prop.""" use_peg = True insert = True physics = Physics.from_xml_string(*make_model(use_peg, insert)) task = Bring(use_peg=use_peg, insert=insert, fully_observable=fully_observable, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, control_timestep=_CONTROL_TIMESTEP, time_limit=time_limit, **environment_kwargs) class Physics(mujoco.Physics): """Physics with additional features for the Planar Manipulator domain.""" def bounded_joint_pos(self, joint_names): """Returns joint positions as (sin, cos) values.""" joint_pos = self.named.data.qpos[joint_names] return np.vstack([np.sin(joint_pos), np.cos(joint_pos)]).T def joint_vel(self, joint_names): """Returns joint velocities.""" return self.named.data.qvel[joint_names] def body_2d_pose(self, body_names, orientation=True): """Returns positions and/or orientations of bodies.""" if not isinstance(body_names, str): body_names = np.array(body_names).reshape(-1, 1) # Broadcast indices. pos = self.named.data.xpos[body_names, ['x', 'z']] if orientation: ori = self.named.data.xquat[body_names, ['qw', 'qy']] return np.hstack([pos, ori]) else: return pos def touch(self): return np.log1p(self.named.data.sensordata[_TOUCH_SENSORS]) def site_distance(self, site1, site2): site1_to_site2 = np.diff(self.named.data.site_xpos[[site2, site1]], axis=0) return np.linalg.norm(site1_to_site2) class Bring(base.Task): """A Bring `Task`: bring the prop to the target.""" def __init__(self, use_peg, insert, fully_observable, random=None): """Initialize an instance of the `Bring` task. Args: use_peg: A `bool`, whether to replace the ball prop with the peg prop. insert: A `bool`, whether to insert the prop in a receptacle. fully_observable: A `bool`, whether the observation should contain the position and velocity of the object being manipulated and the target location. random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). """ self._use_peg = use_peg self._target = 'target_peg' if use_peg else 'target_ball' self._object = 'peg' if self._use_peg else 'ball' self._object_joints = ['_'.join([self._object, dim]) for dim in 'xzy'] self._receptacle = 'slot' if self._use_peg else 'cup' self._insert = insert self._fully_observable = fully_observable super().__init__(random=random) def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode.""" # Local aliases choice = self.random.choice uniform = self.random.uniform model = physics.named.model data = physics.named.data # Find a collision-free random initial configuration. penetrating = True while penetrating: # Randomise angles of arm joints. is_limited = model.jnt_limited[_ARM_JOINTS].astype(bool) joint_range = model.jnt_range[_ARM_JOINTS] lower_limits = np.where(is_limited, joint_range[:, 0], -np.pi) upper_limits = np.where(is_limited, joint_range[:, 1], np.pi) angles = uniform(lower_limits, upper_limits) data.qpos[_ARM_JOINTS] = angles # Symmetrize hand. data.qpos['finger'] = data.qpos['thumb'] # Randomise target location. target_x = uniform(-.4, .4) target_z = uniform(.1, .4) if self._insert: target_angle = uniform(-np.pi/3, np.pi/3) model.body_pos[self._receptacle, ['x', 'z']] = target_x, target_z model.body_quat[self._receptacle, ['qw', 'qy']] = [ np.cos(target_angle/2), np.sin(target_angle/2)] else: target_angle = uniform(-np.pi, np.pi) model.body_pos[self._target, ['x', 'z']] = target_x, target_z model.body_quat[self._target, ['qw', 'qy']] = [ np.cos(target_angle/2), np.sin(target_angle/2)] # Randomise object location. object_init_probs = [_P_IN_HAND, _P_IN_TARGET, 1-_P_IN_HAND-_P_IN_TARGET] init_type = choice(['in_hand', 'in_target', 'uniform'], p=object_init_probs) if init_type == 'in_target': object_x = target_x object_z = target_z object_angle = target_angle elif init_type == 'in_hand': physics.after_reset() object_x = data.site_xpos['grasp', 'x'] object_z = data.site_xpos['grasp', 'z'] grasp_direction = data.site_xmat['grasp', ['xx', 'zx']] object_angle = np.pi-np.arctan2(grasp_direction[1], grasp_direction[0]) else: object_x = uniform(-.5, .5) object_z = uniform(0, .7) object_angle = uniform(0, 2*np.pi) data.qvel[self._object + '_x'] = uniform(-5, 5) data.qpos[self._object_joints] = object_x, object_z, object_angle # Check for collisions. physics.after_reset() penetrating = physics.data.ncon > 0 super().initialize_episode(physics) def get_observation(self, physics): """Returns either features or only sensors (to be used with pixels).""" obs = collections.OrderedDict() obs['arm_pos'] = physics.bounded_joint_pos(_ARM_JOINTS) obs['arm_vel'] = physics.joint_vel(_ARM_JOINTS) obs['touch'] = physics.touch() if self._fully_observable: obs['hand_pos'] = physics.body_2d_pose('hand') obs['object_pos'] = physics.body_2d_pose(self._object) obs['object_vel'] = physics.joint_vel(self._object_joints) obs['target_pos'] = physics.body_2d_pose(self._target) return obs def _is_close(self, distance): return rewards.tolerance(distance, (0, _CLOSE), _CLOSE*2) def _peg_reward(self, physics): """Returns a reward for bringing the peg prop to the target.""" grasp = self._is_close(physics.site_distance('peg_grasp', 'grasp')) pinch = self._is_close(physics.site_distance('peg_pinch', 'pinch')) grasping = (grasp + pinch) / 2 bring = self._is_close(physics.site_distance('peg', 'target_peg')) bring_tip = self._is_close(physics.site_distance('target_peg_tip', 'peg_tip')) bringing = (bring + bring_tip) / 2 return max(bringing, grasping/3) def _ball_reward(self, physics): """Returns a reward for bringing the ball prop to the target.""" return self._is_close(physics.site_distance('ball', 'target_ball')) def get_reward(self, physics): """Returns a reward to the agent.""" if self._use_peg: return self._peg_reward(physics) else: return self._ball_reward(physics)
dm_control-main
dm_control/suite/manipulator.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests specific to the LQR domain.""" import math from absl import logging from absl.testing import absltest from absl.testing import parameterized from dm_control.suite import lqr from dm_control.suite import lqr_solver import numpy as np class LqrTest(parameterized.TestCase): @parameterized.named_parameters( ('lqr_2_1', lqr.lqr_2_1), ('lqr_6_2', lqr.lqr_6_2)) def test_lqr_optimal_policy(self, make_env): env = make_env() p, k, beta = lqr_solver.solve(env) self.assertPolicyisOptimal(env, p, k, beta) def assertPolicyisOptimal(self, env, p, k, beta): tolerance = 1e-3 n_steps = int(math.ceil(math.log10(tolerance) / math.log10(beta))) logging.info('%d timesteps for %g convergence.', n_steps, tolerance) total_loss = 0.0 timestep = env.reset() initial_state = np.hstack((timestep.observation['position'], timestep.observation['velocity'])) logging.info('Measuring total cost over %d steps.', n_steps) for _ in range(n_steps): x = np.hstack((timestep.observation['position'], timestep.observation['velocity'])) # u = k*x is the optimal policy u = k.dot(x) total_loss += 1 - (timestep.reward or 0.0) timestep = env.step(u) logging.info('Analytical expected total cost is .5*x^T*p*x.') expected_loss = .5 * initial_state.T.dot(p).dot(initial_state) logging.info('Comparing measured and predicted costs.') np.testing.assert_allclose(expected_loss, total_loss, rtol=tolerance) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/suite/lqr_test.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Procedurally generated LQR domain.""" import collections import os from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.utils import containers from dm_control.utils import xml_tools from lxml import etree import numpy as np from dm_control.utils import io as resources _DEFAULT_TIME_LIMIT = float('inf') _CONTROL_COST_COEF = 0.1 SUITE = containers.TaggedTasks() def get_model_and_assets(n_bodies, n_actuators, random): """Returns the model description as an XML string and a dict of assets. Args: n_bodies: An int, number of bodies of the LQR. n_actuators: An int, number of actuated bodies of the LQR. `n_actuators` should be less or equal than `n_bodies`. random: A `numpy.random.RandomState` instance. Returns: A tuple `(model_xml_string, assets)`, where `assets` is a dict consisting of `{filename: contents_string}` pairs. """ return _make_model(n_bodies, n_actuators, random), common.ASSETS @SUITE.add() def lqr_2_1(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns an LQR environment with 2 bodies of which the first is actuated.""" return _make_lqr(n_bodies=2, n_actuators=1, control_cost_coef=_CONTROL_COST_COEF, time_limit=time_limit, random=random, environment_kwargs=environment_kwargs) @SUITE.add() def lqr_6_2(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns an LQR environment with 6 bodies of which first 2 are actuated.""" return _make_lqr(n_bodies=6, n_actuators=2, control_cost_coef=_CONTROL_COST_COEF, time_limit=time_limit, random=random, environment_kwargs=environment_kwargs) def _make_lqr(n_bodies, n_actuators, control_cost_coef, time_limit, random, environment_kwargs): """Returns a LQR environment. Args: n_bodies: An int, number of bodies of the LQR. n_actuators: An int, number of actuated bodies of the LQR. `n_actuators` should be less or equal than `n_bodies`. control_cost_coef: A number, the coefficient of the control cost. time_limit: An int, maximum time for each episode in seconds. random: Either an existing `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically. environment_kwargs: A `dict` specifying keyword arguments for the environment, or None. Returns: A LQR environment with `n_bodies` bodies of which first `n_actuators` are actuated. """ if not isinstance(random, np.random.RandomState): random = np.random.RandomState(random) model_string, assets = get_model_and_assets(n_bodies, n_actuators, random=random) physics = Physics.from_xml_string(model_string, assets=assets) task = LQRLevel(control_cost_coef, random=random) environment_kwargs = environment_kwargs or {} return control.Environment(physics, task, time_limit=time_limit, **environment_kwargs) def _make_body(body_id, stiffness_range, damping_range, random): """Returns an `etree.Element` defining a body. Args: body_id: Id of the created body. stiffness_range: A tuple of (stiffness_lower_bound, stiffness_uppder_bound). The stiffness of the joint is drawn uniformly from this range. damping_range: A tuple of (damping_lower_bound, damping_upper_bound). The damping of the joint is drawn uniformly from this range. random: A `numpy.random.RandomState` instance. Returns: A new instance of `etree.Element`. A body element with two children: joint and geom. """ body_name = 'body_{}'.format(body_id) joint_name = 'joint_{}'.format(body_id) geom_name = 'geom_{}'.format(body_id) body = etree.Element('body', name=body_name) body.set('pos', '.25 0 0') joint = etree.SubElement(body, 'joint', name=joint_name) body.append(etree.Element('geom', name=geom_name)) joint.set('stiffness', str(random.uniform(stiffness_range[0], stiffness_range[1]))) joint.set('damping', str(random.uniform(damping_range[0], damping_range[1]))) return body def _make_model(n_bodies, n_actuators, random, stiffness_range=(15, 25), damping_range=(0, 0)): """Returns an MJCF XML string defining a model of springs and dampers. Args: n_bodies: An integer, the number of bodies (DoFs) in the system. n_actuators: An integer, the number of actuated bodies. random: A `numpy.random.RandomState` instance. stiffness_range: A tuple containing minimum and maximum stiffness. Each joint's stiffness is sampled uniformly from this interval. damping_range: A tuple containing minimum and maximum damping. Each joint's damping is sampled uniformly from this interval. Returns: An MJCF string describing the linear system. Raises: ValueError: If the number of bodies or actuators is erronous. """ if n_bodies < 1 or n_actuators < 1: raise ValueError('At least 1 body and 1 actuator required.') if n_actuators > n_bodies: raise ValueError('At most 1 actuator per body.') file_path = os.path.join(os.path.dirname(__file__), 'lqr.xml') with resources.GetResourceAsFile(file_path) as xml_file: mjcf = xml_tools.parse(xml_file) parent = mjcf.find('./worldbody') actuator = etree.SubElement(mjcf.getroot(), 'actuator') tendon = etree.SubElement(mjcf.getroot(), 'tendon') for body in range(n_bodies): # Inserting body. child = _make_body(body, stiffness_range, damping_range, random) site_name = 'site_{}'.format(body) child.append(etree.Element('site', name=site_name)) if body == 0: child.set('pos', '.25 0 .1') # Add actuators to the first n_actuators bodies. if body < n_actuators: # Adding actuator. joint_name = 'joint_{}'.format(body) motor_name = 'motor_{}'.format(body) child.find('joint').set('name', joint_name) actuator.append(etree.Element('motor', name=motor_name, joint=joint_name)) # Add a tendon between consecutive bodies (for visualisation purposes only). if body < n_bodies - 1: child_site_name = 'site_{}'.format(body + 1) tendon_name = 'tendon_{}'.format(body) spatial = etree.SubElement(tendon, 'spatial', name=tendon_name) spatial.append(etree.Element('site', site=site_name)) spatial.append(etree.Element('site', site=child_site_name)) parent.append(child) parent = child return etree.tostring(mjcf, pretty_print=True) class Physics(mujoco.Physics): """Physics simulation with additional features for the LQR domain.""" def state_norm(self): """Returns the norm of the physics state.""" return np.linalg.norm(self.state()) class LQRLevel(base.Task): """A Linear Quadratic Regulator `Task`.""" _TERMINAL_TOL = 1e-6 def __init__(self, control_cost_coef, random=None): """Initializes an LQR level with cost = sum(states^2) + c*sum(controls^2). Args: control_cost_coef: The coefficient of the control cost. random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). Raises: ValueError: If the control cost coefficient is not positive. """ if control_cost_coef <= 0: raise ValueError('control_cost_coef must be positive.') self._control_cost_coef = control_cost_coef super().__init__(random=random) @property def control_cost_coef(self): return self._control_cost_coef def initialize_episode(self, physics): """Random state sampled from a unit sphere.""" ndof = physics.model.nq unit = self.random.randn(ndof) physics.data.qpos[:] = np.sqrt(2) * unit / np.linalg.norm(unit) super().initialize_episode(physics) def get_observation(self, physics): """Returns an observation of the state.""" obs = collections.OrderedDict() obs['position'] = physics.position() obs['velocity'] = physics.velocity() return obs def get_reward(self, physics): """Returns a quadratic state and control reward.""" position = physics.position() state_cost = 0.5 * np.dot(position, position) control_signal = physics.control() control_l2_norm = 0.5 * np.dot(control_signal, control_signal) return 1 - (state_cost + control_l2_norm * self._control_cost_coef) def get_evaluation(self, physics): """Returns a sparse evaluation reward that is not used for learning.""" return float(physics.state_norm() <= 0.01) def get_termination(self, physics): """Terminates when the state norm is smaller than epsilon.""" if physics.state_norm() < self._TERMINAL_TOL: return 0.0
dm_control-main
dm_control/suite/lqr.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. # ============================================================================ r"""Optimal policy for LQR levels. LQR control problem is described in https://en.wikipedia.org/wiki/Linear-quadratic_regulator#Infinite-horizon.2C_discrete-time_LQR """ from dm_control.mujoco import wrapper import numpy as np import scipy.linalg as scipy_linalg def solve(env): """Returns the optimal value and policy for LQR problem. Args: env: An instance of `control.EnvironmentV2` with LQR level. Returns: p: A numpy array, the Hessian of the optimal total cost-to-go (value function at state x) is V(x) = .5 * x' * p * x. k: A numpy array which gives the optimal linear policy u = k * x. beta: The maximum eigenvalue of (a + b * k). Under optimal policy, at timestep n the state tends to 0 like beta^n. Raises: RuntimeError: If the controlled system is unstable. """ n = env.physics.model.nq # number of DoFs m = env.physics.model.nu # number of controls # Compute the mass matrix. mass = np.zeros((n, n)) wrapper.mjbindings.mjlib.mj_fullM(env.physics.model.ptr, mass, env.physics.data.qM) # Compute input matrices a, b, q and r to the DARE solvers. # State transition matrix a. stiffness = np.diag(env.physics.model.jnt_stiffness.ravel()) damping = np.diag(env.physics.model.dof_damping.ravel()) dt = env.physics.model.opt.timestep j = np.linalg.solve(-mass, np.hstack((stiffness, damping))) a = np.eye(2 * n) + dt * np.vstack( (dt * j + np.hstack((np.zeros((n, n)), np.eye(n))), j)) # Control transition matrix b. b = env.physics.data.actuator_moment.T bc = np.linalg.solve(mass, b) b = dt * np.vstack((dt * bc, bc)) # State cost Hessian q. q = np.diag(np.hstack([np.ones(n), np.zeros(n)])) # Control cost Hessian r. r = env.task.control_cost_coef * np.eye(m) # Solve the discrete algebraic Riccati equation. p = scipy_linalg.solve_discrete_are(a, b, q, r) k = -np.linalg.solve(b.T.dot(p.dot(b)) + r, b.T.dot(p.dot(a))) # Under optimal policy, state tends to 0 like beta^n_timesteps beta = np.abs(np.linalg.eigvals(a + b.dot(k))).max() if beta >= 1.0: raise RuntimeError('Controlled system is unstable.') return p, k, beta
dm_control-main
dm_control/suite/lqr_solver.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. # ============================================================================ """Reacher domain.""" import collections from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.suite.utils import randomizers from dm_control.utils import containers from dm_control.utils import rewards import numpy as np SUITE = containers.TaggedTasks() _DEFAULT_TIME_LIMIT = 20 _BIG_TARGET = .05 _SMALL_TARGET = .015 def get_model_and_assets(): """Returns a tuple containing the model XML string and a dict of assets.""" return common.read_model('reacher.xml'), common.ASSETS @SUITE.add('benchmarking', 'easy') def easy(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns reacher with sparse reward with 5e-2 tol and randomized target.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Reacher(target_size=_BIG_TARGET, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, **environment_kwargs) @SUITE.add('benchmarking') def hard(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns reacher with sparse reward with 1e-2 tol and randomized target.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Reacher(target_size=_SMALL_TARGET, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, **environment_kwargs) class Physics(mujoco.Physics): """Physics simulation with additional features for the Reacher domain.""" def finger_to_target(self): """Returns the vector from target to finger in global coordinates.""" return (self.named.data.geom_xpos['target', :2] - self.named.data.geom_xpos['finger', :2]) def finger_to_target_dist(self): """Returns the signed distance between the finger and target surface.""" return np.linalg.norm(self.finger_to_target()) class Reacher(base.Task): """A reacher `Task` to reach the target.""" def __init__(self, target_size, random=None): """Initialize an instance of `Reacher`. Args: target_size: A `float`, tolerance to determine whether finger reached the target. random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). """ self._target_size = target_size super().__init__(random=random) def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode.""" physics.named.model.geom_size['target', 0] = self._target_size randomizers.randomize_limited_and_rotational_joints(physics, self.random) # Randomize target position angle = self.random.uniform(0, 2 * np.pi) radius = self.random.uniform(.05, .20) physics.named.model.geom_pos['target', 'x'] = radius * np.sin(angle) physics.named.model.geom_pos['target', 'y'] = radius * np.cos(angle) super().initialize_episode(physics) def get_observation(self, physics): """Returns an observation of the state and the target position.""" obs = collections.OrderedDict() obs['position'] = physics.position() obs['to_target'] = physics.finger_to_target() obs['velocity'] = physics.velocity() return obs def get_reward(self, physics): radii = physics.named.model.geom_size[['target', 'finger'], 0].sum() return rewards.tolerance(physics.finger_to_target_dist(), (0, radii))
dm_control-main
dm_control/suite/reacher.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. # ============================================================================ """Planar Walker Domain.""" import collections from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.suite.utils import randomizers from dm_control.utils import containers from dm_control.utils import rewards _DEFAULT_TIME_LIMIT = 25 _CONTROL_TIMESTEP = .025 # Minimal height of torso over foot above which stand reward is 1. _STAND_HEIGHT = 1.2 # Horizontal speeds (meters/second) above which move reward is 1. _WALK_SPEED = 1 _RUN_SPEED = 8 SUITE = containers.TaggedTasks() def get_model_and_assets(): """Returns a tuple containing the model XML string and a dict of assets.""" return common.read_model('walker.xml'), common.ASSETS @SUITE.add('benchmarking') def stand(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Stand task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = PlanarWalker(move_speed=0, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) @SUITE.add('benchmarking') def walk(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Walk task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = PlanarWalker(move_speed=_WALK_SPEED, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) @SUITE.add('benchmarking') def run(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Run task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = PlanarWalker(move_speed=_RUN_SPEED, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) class Physics(mujoco.Physics): """Physics simulation with additional features for the Walker domain.""" def torso_upright(self): """Returns projection from z-axes of torso to the z-axes of world.""" return self.named.data.xmat['torso', 'zz'] def torso_height(self): """Returns the height of the torso.""" return self.named.data.xpos['torso', 'z'] def horizontal_velocity(self): """Returns the horizontal velocity of the center-of-mass.""" return self.named.data.sensordata['torso_subtreelinvel'][0] def orientations(self): """Returns planar orientations of all bodies.""" return self.named.data.xmat[1:, ['xx', 'xz']].ravel() class PlanarWalker(base.Task): """A planar walker task.""" def __init__(self, move_speed, random=None): """Initializes an instance of `PlanarWalker`. Args: move_speed: A float. If this value is zero, reward is given simply for standing up. Otherwise this specifies a target horizontal velocity for the walking task. random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). """ self._move_speed = move_speed super().__init__(random=random) def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode. In 'standing' mode, use initial orientation and small velocities. In 'random' mode, randomize joint angles and let fall to the floor. Args: physics: An instance of `Physics`. """ randomizers.randomize_limited_and_rotational_joints(physics, self.random) super().initialize_episode(physics) def get_observation(self, physics): """Returns an observation of body orientations, height and velocites.""" obs = collections.OrderedDict() obs['orientations'] = physics.orientations() obs['height'] = physics.torso_height() obs['velocity'] = physics.velocity() return obs def get_reward(self, physics): """Returns a reward to the agent.""" standing = rewards.tolerance(physics.torso_height(), bounds=(_STAND_HEIGHT, float('inf')), margin=_STAND_HEIGHT/2) upright = (1 + physics.torso_upright()) / 2 stand_reward = (3*standing + upright) / 4 if self._move_speed == 0: return stand_reward else: move_reward = rewards.tolerance(physics.horizontal_velocity(), bounds=(self._move_speed, float('inf')), margin=self._move_speed/2, value_at_margin=0.5, sigmoid='linear') return stand_reward * (5*move_reward + 1) / 6
dm_control-main
dm_control/suite/walker.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. # ============================================================================ """A collection of MuJoCo-based Reinforcement Learning environments.""" import collections import inspect import itertools from dm_control.rl import control from dm_control.suite import acrobot from dm_control.suite import ball_in_cup from dm_control.suite import cartpole from dm_control.suite import cheetah from dm_control.suite import dog from dm_control.suite import finger from dm_control.suite import fish from dm_control.suite import hopper from dm_control.suite import humanoid from dm_control.suite import humanoid_CMU from dm_control.suite import lqr from dm_control.suite import manipulator from dm_control.suite import pendulum from dm_control.suite import point_mass from dm_control.suite import quadruped from dm_control.suite import reacher from dm_control.suite import stacker from dm_control.suite import swimmer from dm_control.suite import walker # Find all domains imported. _DOMAINS = {name: module for name, module in locals().items() if inspect.ismodule(module) and hasattr(module, 'SUITE')} def _get_tasks(tag): """Returns a sequence of (domain name, task name) pairs for the given tag.""" result = [] for domain_name in sorted(_DOMAINS.keys()): domain = _DOMAINS[domain_name] if tag is None: tasks_in_domain = domain.SUITE else: tasks_in_domain = domain.SUITE.tagged(tag) for task_name in tasks_in_domain.keys(): result.append((domain_name, task_name)) return tuple(result) def _get_tasks_by_domain(tasks): """Returns a dict mapping from task name to a tuple of domain names.""" result = collections.defaultdict(list) for domain_name, task_name in tasks: result[domain_name].append(task_name) return {k: tuple(v) for k, v in result.items()} # A sequence containing all (domain name, task name) pairs. ALL_TASKS = _get_tasks(tag=None) # Subsets of ALL_TASKS, generated via the tag mechanism. BENCHMARKING = _get_tasks('benchmarking') EASY = _get_tasks('easy') HARD = _get_tasks('hard') EXTRA = tuple(sorted(set(ALL_TASKS) - set(BENCHMARKING))) NO_REWARD_VIZ = _get_tasks('no_reward_visualization') REWARD_VIZ = tuple(sorted(set(ALL_TASKS) - set(NO_REWARD_VIZ))) # A mapping from each domain name to a sequence of its task names. TASKS_BY_DOMAIN = _get_tasks_by_domain(ALL_TASKS) def load(domain_name, task_name, task_kwargs=None, environment_kwargs=None, visualize_reward=False): """Returns an environment from a domain name, task name and optional settings. ```python env = suite.load('cartpole', 'balance') ``` Args: domain_name: A string containing the name of a domain. task_name: A string containing the name of a task. task_kwargs: Optional `dict` of keyword arguments for the task. environment_kwargs: Optional `dict` specifying keyword arguments for the environment. visualize_reward: Optional `bool`. If `True`, object colours in rendered frames are set to indicate the reward at each step. Default `False`. Returns: The requested environment. """ return build_environment(domain_name, task_name, task_kwargs, environment_kwargs, visualize_reward) def build_environment(domain_name, task_name, task_kwargs=None, environment_kwargs=None, visualize_reward=False): """Returns an environment from the suite given a domain name and a task name. Args: domain_name: A string containing the name of a domain. task_name: A string containing the name of a task. task_kwargs: Optional `dict` specifying keyword arguments for the task. environment_kwargs: Optional `dict` specifying keyword arguments for the environment. visualize_reward: Optional `bool`. If `True`, object colours in rendered frames are set to indicate the reward at each step. Default `False`. Raises: ValueError: If the domain or task doesn't exist. Returns: An instance of the requested environment. """ if domain_name not in _DOMAINS: raise ValueError('Domain {!r} does not exist.'.format(domain_name)) domain = _DOMAINS[domain_name] if task_name not in domain.SUITE: raise ValueError('Level {!r} does not exist in domain {!r}.'.format( task_name, domain_name)) task_kwargs = task_kwargs or {} if environment_kwargs is not None: task_kwargs = dict(task_kwargs, environment_kwargs=environment_kwargs) env = domain.SUITE[task_name](**task_kwargs) env.task.visualize_reward = visualize_reward return env
dm_control-main
dm_control/suite/__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. # ============================================================================ """Planar Stacker domain.""" import collections from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.utils import containers from dm_control.utils import rewards from dm_control.utils import xml_tools from lxml import etree import numpy as np _CLOSE = .01 # (Meters) Distance below which a thing is considered close. _CONTROL_TIMESTEP = .01 # (Seconds) _TIME_LIMIT = 10 # (Seconds) _ARM_JOINTS = ['arm_root', 'arm_shoulder', 'arm_elbow', 'arm_wrist', 'finger', 'fingertip', 'thumb', 'thumbtip'] SUITE = containers.TaggedTasks() def make_model(n_boxes): """Returns a tuple containing the model XML string and a dict of assets.""" xml_string = common.read_model('stacker.xml') parser = etree.XMLParser(remove_blank_text=True) mjcf = etree.XML(xml_string, parser) # Remove unused boxes for b in range(n_boxes, 4): box = xml_tools.find_element(mjcf, 'body', 'box' + str(b)) box.getparent().remove(box) return etree.tostring(mjcf, pretty_print=True), common.ASSETS @SUITE.add('hard') def stack_2(fully_observable=True, time_limit=_TIME_LIMIT, random=None, environment_kwargs=None): """Returns stacker task with 2 boxes.""" n_boxes = 2 physics = Physics.from_xml_string(*make_model(n_boxes=n_boxes)) task = Stack(n_boxes=n_boxes, fully_observable=fully_observable, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, control_timestep=_CONTROL_TIMESTEP, time_limit=time_limit, **environment_kwargs) @SUITE.add('hard') def stack_4(fully_observable=True, time_limit=_TIME_LIMIT, random=None, environment_kwargs=None): """Returns stacker task with 4 boxes.""" n_boxes = 4 physics = Physics.from_xml_string(*make_model(n_boxes=n_boxes)) task = Stack(n_boxes=n_boxes, fully_observable=fully_observable, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, control_timestep=_CONTROL_TIMESTEP, time_limit=time_limit, **environment_kwargs) class Physics(mujoco.Physics): """Physics with additional features for the Planar Manipulator domain.""" def bounded_joint_pos(self, joint_names): """Returns joint positions as (sin, cos) values.""" joint_pos = self.named.data.qpos[joint_names] return np.vstack([np.sin(joint_pos), np.cos(joint_pos)]).T def joint_vel(self, joint_names): """Returns joint velocities.""" return self.named.data.qvel[joint_names] def body_2d_pose(self, body_names, orientation=True): """Returns positions and/or orientations of bodies.""" if not isinstance(body_names, str): body_names = np.array(body_names).reshape(-1, 1) # Broadcast indices. pos = self.named.data.xpos[body_names, ['x', 'z']] if orientation: ori = self.named.data.xquat[body_names, ['qw', 'qy']] return np.hstack([pos, ori]) else: return pos def touch(self): return np.log1p(self.data.sensordata) def site_distance(self, site1, site2): site1_to_site2 = np.diff(self.named.data.site_xpos[[site2, site1]], axis=0) return np.linalg.norm(site1_to_site2) class Stack(base.Task): """A Stack `Task`: stack the boxes.""" def __init__(self, n_boxes, fully_observable, random=None): """Initialize an instance of the `Stack` task. Args: n_boxes: An `int`, number of boxes to stack. fully_observable: A `bool`, whether the observation should contain the positions and velocities of the boxes and the location of the target. random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). """ self._n_boxes = n_boxes self._box_names = ['box' + str(b) for b in range(n_boxes)] self._box_joint_names = [] for name in self._box_names: for dim in 'xyz': self._box_joint_names.append('_'.join([name, dim])) self._fully_observable = fully_observable super().__init__(random=random) def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode.""" # Local aliases randint = self.random.randint uniform = self.random.uniform model = physics.named.model data = physics.named.data # Find a collision-free random initial configuration. penetrating = True while penetrating: # Randomise angles of arm joints. is_limited = model.jnt_limited[_ARM_JOINTS].astype(bool) joint_range = model.jnt_range[_ARM_JOINTS] lower_limits = np.where(is_limited, joint_range[:, 0], -np.pi) upper_limits = np.where(is_limited, joint_range[:, 1], np.pi) angles = uniform(lower_limits, upper_limits) data.qpos[_ARM_JOINTS] = angles # Symmetrize hand. data.qpos['finger'] = data.qpos['thumb'] # Randomise target location. target_height = 2*randint(self._n_boxes) + 1 box_size = model.geom_size['target', 0] model.body_pos['target', 'z'] = box_size * target_height model.body_pos['target', 'x'] = uniform(-.37, .37) # Randomise box locations. for name in self._box_names: data.qpos[name + '_x'] = uniform(.1, .3) data.qpos[name + '_z'] = uniform(0, .7) data.qpos[name + '_y'] = uniform(0, 2*np.pi) # Check for collisions. physics.after_reset() penetrating = physics.data.ncon > 0 super().initialize_episode(physics) def get_observation(self, physics): """Returns either features or only sensors (to be used with pixels).""" obs = collections.OrderedDict() obs['arm_pos'] = physics.bounded_joint_pos(_ARM_JOINTS) obs['arm_vel'] = physics.joint_vel(_ARM_JOINTS) obs['touch'] = physics.touch() if self._fully_observable: obs['hand_pos'] = physics.body_2d_pose('hand') obs['box_pos'] = physics.body_2d_pose(self._box_names) obs['box_vel'] = physics.joint_vel(self._box_joint_names) obs['target_pos'] = physics.body_2d_pose('target', orientation=False) return obs def get_reward(self, physics): """Returns a reward to the agent.""" box_size = physics.named.model.geom_size['target', 0] min_box_to_target_distance = min(physics.site_distance(name, 'target') for name in self._box_names) box_is_close = rewards.tolerance(min_box_to_target_distance, margin=2*box_size) hand_to_target_distance = physics.site_distance('grasp', 'target') hand_is_far = rewards.tolerance(hand_to_target_distance, bounds=(.1, float('inf')), margin=_CLOSE) return box_is_close * hand_is_far
dm_control-main
dm_control/suite/stacker.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. # ============================================================================ """Cheetah Domain.""" import collections from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.utils import containers from dm_control.utils import rewards # How long the simulation will run, in seconds. _DEFAULT_TIME_LIMIT = 10 # Running speed above which reward is 1. _RUN_SPEED = 10 SUITE = containers.TaggedTasks() def get_model_and_assets(): """Returns a tuple containing the model XML string and a dict of assets.""" return common.read_model('cheetah.xml'), common.ASSETS @SUITE.add('benchmarking') def run(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the run task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Cheetah(random=random) environment_kwargs = environment_kwargs or {} return control.Environment(physics, task, time_limit=time_limit, **environment_kwargs) class Physics(mujoco.Physics): """Physics simulation with additional features for the Cheetah domain.""" def speed(self): """Returns the horizontal speed of the Cheetah.""" return self.named.data.sensordata['torso_subtreelinvel'][0] class Cheetah(base.Task): """A `Task` to train a running Cheetah.""" def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode.""" # The indexing below assumes that all joints have a single DOF. assert physics.model.nq == physics.model.njnt is_limited = physics.model.jnt_limited == 1 lower, upper = physics.model.jnt_range[is_limited].T physics.data.qpos[is_limited] = self.random.uniform(lower, upper) # Stabilize the model before the actual simulation. physics.step(nstep=200) physics.data.time = 0 self._timeout_progress = 0 super().initialize_episode(physics) def get_observation(self, physics): """Returns an observation of the state, ignoring horizontal position.""" obs = collections.OrderedDict() # Ignores horizontal position to maintain translational invariance. obs['position'] = physics.data.qpos[1:].copy() obs['velocity'] = physics.velocity() return obs def get_reward(self, physics): """Returns a reward to the agent.""" return rewards.tolerance(physics.speed(), bounds=(_RUN_SPEED, float('inf')), margin=_RUN_SPEED, value_at_margin=0, sigmoid='linear')
dm_control-main
dm_control/suite/cheetah.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. # ============================================================================ """Point-mass domain.""" import collections from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.suite.utils import randomizers from dm_control.utils import containers from dm_control.utils import rewards import numpy as np _DEFAULT_TIME_LIMIT = 20 SUITE = containers.TaggedTasks() def get_model_and_assets(): """Returns a tuple containing the model XML string and a dict of assets.""" return common.read_model('point_mass.xml'), common.ASSETS @SUITE.add('benchmarking', 'easy') def easy(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the easy point_mass task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = PointMass(randomize_gains=False, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, **environment_kwargs) @SUITE.add() def hard(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the hard point_mass task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = PointMass(randomize_gains=True, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, **environment_kwargs) class Physics(mujoco.Physics): """physics for the point_mass domain.""" def mass_to_target(self): """Returns the vector from mass to target in global coordinate.""" return (self.named.data.geom_xpos['target'] - self.named.data.geom_xpos['pointmass']) def mass_to_target_dist(self): """Returns the distance from mass to the target.""" return np.linalg.norm(self.mass_to_target()) class PointMass(base.Task): """A point_mass `Task` to reach target with smooth reward.""" def __init__(self, randomize_gains, random=None): """Initialize an instance of `PointMass`. Args: randomize_gains: A `bool`, whether to randomize the actuator gains. random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). """ self._randomize_gains = randomize_gains super().__init__(random=random) def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode. If _randomize_gains is True, the relationship between the controls and the joints is randomized, so that each control actuates a random linear combination of joints. Args: physics: An instance of `mujoco.Physics`. """ randomizers.randomize_limited_and_rotational_joints(physics, self.random) if self._randomize_gains: dir1 = self.random.randn(2) dir1 /= np.linalg.norm(dir1) # Find another actuation direction that is not 'too parallel' to dir1. parallel = True while parallel: dir2 = self.random.randn(2) dir2 /= np.linalg.norm(dir2) parallel = abs(np.dot(dir1, dir2)) > 0.9 physics.model.wrap_prm[[0, 1]] = dir1 physics.model.wrap_prm[[2, 3]] = dir2 super().initialize_episode(physics) def get_observation(self, physics): """Returns an observation of the state.""" obs = collections.OrderedDict() obs['position'] = physics.position() obs['velocity'] = physics.velocity() return obs def get_reward(self, physics): """Returns a reward to the agent.""" target_size = physics.named.model.geom_size['target', 0] near_target = rewards.tolerance(physics.mass_to_target_dist(), bounds=(0, target_size), margin=target_size) control_reward = rewards.tolerance(physics.control(), margin=1, value_at_margin=0, sigmoid='quadratic').mean() small_control = (control_reward + 4) / 5 return near_target * small_control
dm_control-main
dm_control/suite/point_mass.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. # ============================================================================ """Cartpole domain.""" import collections from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.utils import containers from dm_control.utils import rewards from lxml import etree import numpy as np _DEFAULT_TIME_LIMIT = 10 SUITE = containers.TaggedTasks() def get_model_and_assets(num_poles=1): """Returns a tuple containing the model XML string and a dict of assets.""" return _make_model(num_poles), common.ASSETS @SUITE.add('benchmarking') def balance(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Cartpole Balance task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Balance(swing_up=False, sparse=False, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, **environment_kwargs) @SUITE.add('benchmarking') def balance_sparse(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the sparse reward variant of the Cartpole Balance task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Balance(swing_up=False, sparse=True, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, **environment_kwargs) @SUITE.add('benchmarking') def swingup(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Cartpole Swing-Up task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Balance(swing_up=True, sparse=False, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, **environment_kwargs) @SUITE.add('benchmarking') def swingup_sparse(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the sparse reward variant of the Cartpole Swing-Up task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Balance(swing_up=True, sparse=True, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, **environment_kwargs) @SUITE.add() def two_poles(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Cartpole Balance task with two poles.""" physics = Physics.from_xml_string(*get_model_and_assets(num_poles=2)) task = Balance(swing_up=True, sparse=False, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, **environment_kwargs) @SUITE.add() def three_poles(time_limit=_DEFAULT_TIME_LIMIT, random=None, num_poles=3, sparse=False, environment_kwargs=None): """Returns the Cartpole Balance task with three or more poles.""" physics = Physics.from_xml_string(*get_model_and_assets(num_poles=num_poles)) task = Balance(swing_up=True, sparse=sparse, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, **environment_kwargs) def _make_model(n_poles): """Generates an xml string defining a cart with `n_poles` bodies.""" xml_string = common.read_model('cartpole.xml') if n_poles == 1: return xml_string mjcf = etree.fromstring(xml_string) parent = mjcf.find('./worldbody/body/body') # Find first pole. # Make chain of poles. for pole_index in range(2, n_poles+1): child = etree.Element('body', name='pole_{}'.format(pole_index), pos='0 0 1', childclass='pole') etree.SubElement(child, 'joint', name='hinge_{}'.format(pole_index)) etree.SubElement(child, 'geom', name='pole_{}'.format(pole_index)) parent.append(child) parent = child # Move plane down. floor = mjcf.find('./worldbody/geom') floor.set('pos', '0 0 {}'.format(1 - n_poles - .05)) # Move cameras back. cameras = mjcf.findall('./worldbody/camera') cameras[0].set('pos', '0 {} 1'.format(-1 - 2*n_poles)) cameras[1].set('pos', '0 {} 2'.format(-2*n_poles)) return etree.tostring(mjcf, pretty_print=True) class Physics(mujoco.Physics): """Physics simulation with additional features for the Cartpole domain.""" def cart_position(self): """Returns the position of the cart.""" return self.named.data.qpos['slider'][0] def angular_vel(self): """Returns the angular velocity of the pole.""" return self.data.qvel[1:] def pole_angle_cosine(self): """Returns the cosine of the pole angle.""" return self.named.data.xmat[2:, 'zz'] def bounded_position(self): """Returns the state, with pole angle split into sin/cos.""" return np.hstack((self.cart_position(), self.named.data.xmat[2:, ['zz', 'xz']].ravel())) class Balance(base.Task): """A Cartpole `Task` to balance the pole. State is initialized either close to the target configuration or at a random configuration. """ _CART_RANGE = (-.25, .25) _ANGLE_COSINE_RANGE = (.995, 1) def __init__(self, swing_up, sparse, random=None): """Initializes an instance of `Balance`. Args: swing_up: A `bool`, which if `True` sets the cart to the middle of the slider and the pole pointing towards the ground. Otherwise, sets the cart to a random position on the slider and the pole to a random near-vertical position. sparse: A `bool`, whether to return a sparse or a smooth reward. random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). """ self._sparse = sparse self._swing_up = swing_up super().__init__(random=random) def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode. Initializes the cart and pole according to `swing_up`, and in both cases adds a small random initial velocity to break symmetry. Args: physics: An instance of `Physics`. """ nv = physics.model.nv if self._swing_up: physics.named.data.qpos['slider'] = .01*self.random.randn() physics.named.data.qpos['hinge_1'] = np.pi + .01*self.random.randn() physics.named.data.qpos[2:] = .1*self.random.randn(nv - 2) else: physics.named.data.qpos['slider'] = self.random.uniform(-.1, .1) physics.named.data.qpos[1:] = self.random.uniform(-.034, .034, nv - 1) physics.named.data.qvel[:] = 0.01 * self.random.randn(physics.model.nv) super().initialize_episode(physics) def get_observation(self, physics): """Returns an observation of the (bounded) physics state.""" obs = collections.OrderedDict() obs['position'] = physics.bounded_position() obs['velocity'] = physics.velocity() return obs def _get_reward(self, physics, sparse): if sparse: cart_in_bounds = rewards.tolerance(physics.cart_position(), self._CART_RANGE) angle_in_bounds = rewards.tolerance(physics.pole_angle_cosine(), self._ANGLE_COSINE_RANGE).prod() return cart_in_bounds * angle_in_bounds else: upright = (physics.pole_angle_cosine() + 1) / 2 centered = rewards.tolerance(physics.cart_position(), margin=2) centered = (1 + centered) / 2 small_control = rewards.tolerance(physics.control(), margin=1, value_at_margin=0, sigmoid='quadratic')[0] small_control = (4 + small_control) / 5 small_velocity = rewards.tolerance(physics.angular_vel(), margin=5).min() small_velocity = (1 + small_velocity) / 2 return upright.mean() * small_control * small_velocity * centered def get_reward(self, physics): """Returns a sparse or a smooth reward, as specified in the constructor.""" return self._get_reward(physics, sparse=self._sparse)
dm_control-main
dm_control/suite/cartpole.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. # ============================================================================ """Hopper domain.""" import collections from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.suite.utils import randomizers from dm_control.utils import containers from dm_control.utils import rewards import numpy as np SUITE = containers.TaggedTasks() _CONTROL_TIMESTEP = .02 # (Seconds) # Default duration of an episode, in seconds. _DEFAULT_TIME_LIMIT = 20 # Minimal height of torso over foot above which stand reward is 1. _STAND_HEIGHT = 0.6 # Hopping speed above which hop reward is 1. _HOP_SPEED = 2 def get_model_and_assets(): """Returns a tuple containing the model XML string and a dict of assets.""" return common.read_model('hopper.xml'), common.ASSETS @SUITE.add('benchmarking') def stand(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns a Hopper that strives to stand upright, balancing its pose.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Hopper(hopping=False, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) @SUITE.add('benchmarking') def hop(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns a Hopper that strives to hop forward.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Hopper(hopping=True, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) class Physics(mujoco.Physics): """Physics simulation with additional features for the Hopper domain.""" def height(self): """Returns height of torso with respect to foot.""" return (self.named.data.xipos['torso', 'z'] - self.named.data.xipos['foot', 'z']) def speed(self): """Returns horizontal speed of the Hopper.""" return self.named.data.sensordata['torso_subtreelinvel'][0] def touch(self): """Returns the signals from two foot touch sensors.""" return np.log1p(self.named.data.sensordata[['touch_toe', 'touch_heel']]) class Hopper(base.Task): """A Hopper's `Task` to train a standing and a jumping Hopper.""" def __init__(self, hopping, random=None): """Initialize an instance of `Hopper`. Args: hopping: Boolean, if True the task is to hop forwards, otherwise it is to balance upright. random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). """ self._hopping = hopping super().__init__(random=random) def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode.""" randomizers.randomize_limited_and_rotational_joints(physics, self.random) self._timeout_progress = 0 super().initialize_episode(physics) def get_observation(self, physics): """Returns an observation of positions, velocities and touch sensors.""" obs = collections.OrderedDict() # Ignores horizontal position to maintain translational invariance: obs['position'] = physics.data.qpos[1:].copy() obs['velocity'] = physics.velocity() obs['touch'] = physics.touch() return obs def get_reward(self, physics): """Returns a reward applicable to the performed task.""" standing = rewards.tolerance(physics.height(), (_STAND_HEIGHT, 2)) if self._hopping: hopping = rewards.tolerance(physics.speed(), bounds=(_HOP_SPEED, float('inf')), margin=_HOP_SPEED/2, value_at_margin=0.5, sigmoid='linear') return standing * hopping else: small_control = rewards.tolerance(physics.control(), margin=1, value_at_margin=0, sigmoid='quadratic').mean() small_control = (small_control + 4) / 5 return standing * small_control
dm_control-main
dm_control/suite/hopper.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. # ============================================================================ """Dog Domain.""" import collections import os from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.utils import containers from dm_control.utils import rewards from dm_control.utils import xml_tools from lxml import etree import numpy as np from dm_control.utils import io as resources _DEFAULT_TIME_LIMIT = 15 _CONTROL_TIMESTEP = .015 # Angle (in degrees) of local z from global z below which upright reward is 1. _MAX_UPRIGHT_ANGLE = 30 _MIN_UPRIGHT_COSINE = np.cos(np.deg2rad(_MAX_UPRIGHT_ANGLE)) # Standing reward is 1 for body-over-foot height that is at least this fraction # of the height at the default pose. _STAND_HEIGHT_FRACTION = 0.9 # Torques which enforce joint range limits should stay below this value. _EXCESSIVE_LIMIT_TORQUES = 150 # Horizontal speed above which Move reward is 1. _WALK_SPEED = 1 _TROT_SPEED = 3 _RUN_SPEED = 9 _HINGE_TYPE = mujoco.wrapper.mjbindings.enums.mjtJoint.mjJNT_HINGE _LIMIT_TYPE = mujoco.wrapper.mjbindings.enums.mjtConstraint.mjCNSTR_LIMIT_JOINT SUITE = containers.TaggedTasks() _ASSET_DIR = os.path.join(os.path.dirname(__file__), 'dog_assets') def make_model(floor_size, remove_ball): """Sets floor size, removes ball and walls (Stand and Move tasks).""" xml_string = common.read_model('dog.xml') parser = etree.XMLParser(remove_blank_text=True) mjcf = etree.XML(xml_string, parser) # set floor size. floor = xml_tools.find_element(mjcf, 'geom', 'floor') floor.attrib['size'] = str(floor_size) + ' ' + str(floor_size) + ' .1' if remove_ball: # Remove ball, target and walls. ball = xml_tools.find_element(mjcf, 'body', 'ball') ball.getparent().remove(ball) target = xml_tools.find_element(mjcf, 'geom', 'target') target.getparent().remove(target) ball_cam = xml_tools.find_element(mjcf, 'camera', 'ball') ball_cam.getparent().remove(ball_cam) head_cam = xml_tools.find_element(mjcf, 'camera', 'head') head_cam.getparent().remove(head_cam) for wall_name in ['px', 'nx', 'py', 'ny']: wall = xml_tools.find_element(mjcf, 'geom', 'wall_' + wall_name) wall.getparent().remove(wall) return etree.tostring(mjcf, pretty_print=True) def get_model_and_assets(floor_size=10, remove_ball=True): """Returns a tuple containing the model XML string and a dict of assets.""" assets = common.ASSETS.copy() _, _, filenames = next(resources.WalkResources(_ASSET_DIR)) for filename in filenames: assets[filename] = resources.GetResource(os.path.join(_ASSET_DIR, filename)) return make_model(floor_size, remove_ball), assets @SUITE.add('no_reward_visualization') def stand(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Stand task.""" floor_size = _WALK_SPEED * _DEFAULT_TIME_LIMIT physics = Physics.from_xml_string(*get_model_and_assets(floor_size)) task = Stand(random=random) environment_kwargs = environment_kwargs or {} return control.Environment(physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) @SUITE.add('no_reward_visualization') def walk(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Walk task.""" move_speed = _WALK_SPEED floor_size = move_speed * _DEFAULT_TIME_LIMIT physics = Physics.from_xml_string(*get_model_and_assets(floor_size)) task = Move(move_speed=move_speed, random=random) environment_kwargs = environment_kwargs or {} return control.Environment(physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) @SUITE.add('no_reward_visualization') def trot(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Trot task.""" move_speed = _TROT_SPEED floor_size = move_speed * _DEFAULT_TIME_LIMIT physics = Physics.from_xml_string(*get_model_and_assets(floor_size)) task = Move(move_speed=move_speed, random=random) environment_kwargs = environment_kwargs or {} return control.Environment(physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) @SUITE.add('no_reward_visualization') def run(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Run task.""" move_speed = _RUN_SPEED floor_size = move_speed * _DEFAULT_TIME_LIMIT physics = Physics.from_xml_string(*get_model_and_assets(floor_size)) task = Move(move_speed=move_speed, random=random) environment_kwargs = environment_kwargs or {} return control.Environment(physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) @SUITE.add('no_reward_visualization', 'hard') def fetch(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Fetch task.""" physics = Physics.from_xml_string(*get_model_and_assets(remove_ball=False)) task = Fetch(random=random) environment_kwargs = environment_kwargs or {} return control.Environment(physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) class Physics(mujoco.Physics): """Physics simulation with additional features for the Dog domain.""" def torso_pelvis_height(self): """Returns the height of the torso.""" return self.named.data.xpos[['torso', 'pelvis'], 'z'] def z_projection(self): """Returns rotation-invariant projection of local frames to the world z.""" return np.vstack((self.named.data.xmat['skull', ['zx', 'zy', 'zz']], self.named.data.xmat['torso', ['zx', 'zy', 'zz']], self.named.data.xmat['pelvis', ['zx', 'zy', 'zz']])) def upright(self): """Returns projection from local z-axes to the z-axis of world.""" return self.z_projection()[:, 2] def center_of_mass_velocity(self): """Returns the velocity of the center-of-mass.""" return self.named.data.sensordata['torso_linvel'] def torso_com_velocity(self): """Returns the velocity of the center-of-mass in the torso frame.""" torso_frame = self.named.data.xmat['torso'].reshape(3, 3).copy() return self.center_of_mass_velocity().dot(torso_frame) def com_forward_velocity(self): """Returns the com velocity in the torso's forward direction.""" return self.torso_com_velocity()[0] def joint_angles(self): """Returns the configuration of all hinge joints (skipping free joints).""" hinge_joints = self.model.jnt_type == _HINGE_TYPE qpos_index = self.model.jnt_qposadr[hinge_joints] return self.data.qpos[qpos_index].copy() def joint_velocities(self): """Returns the velocity of all hinge joints (skipping free joints).""" hinge_joints = self.model.jnt_type == _HINGE_TYPE qvel_index = self.model.jnt_dofadr[hinge_joints] return self.data.qvel[qvel_index].copy() def inertial_sensors(self): """Returns inertial sensor readings.""" return self.named.data.sensordata[['accelerometer', 'velocimeter', 'gyro']] def touch_sensors(self): """Returns touch readings.""" return self.named.data.sensordata[['palm_L', 'palm_R', 'sole_L', 'sole_R']] def foot_forces(self): """Returns touch readings.""" return self.named.data.sensordata[['foot_L', 'foot_R', 'hand_L', 'hand_R']] def ball_in_head_frame(self): """Returns the ball position and velocity in the frame of the head.""" head_frame = self.named.data.site_xmat['head'].reshape(3, 3) head_pos = self.named.data.site_xpos['head'] ball_pos = self.named.data.geom_xpos['ball'] head_to_ball = ball_pos - head_pos head_vel, _ = self.data.object_velocity('head', 'site') ball_vel, _ = self.data.object_velocity('ball', 'geom') head_to_ball_vel = ball_vel - head_vel return np.hstack((head_to_ball.dot(head_frame), head_to_ball_vel.dot(head_frame))) def target_in_head_frame(self): """Returns the target position in the frame of the head.""" head_frame = self.named.data.site_xmat['head'].reshape(3, 3) head_pos = self.named.data.site_xpos['head'] target_pos = self.named.data.geom_xpos['target'] head_to_target = target_pos - head_pos return head_to_target.dot(head_frame) def ball_to_mouth_distance(self): """Returns the distance from the ball to the mouth.""" ball_pos = self.named.data.geom_xpos['ball'] upper_bite_pos = self.named.data.site_xpos['upper_bite'] lower_bite_pos = self.named.data.site_xpos['lower_bite'] upper_dist = np.linalg.norm(ball_pos - upper_bite_pos) lower_dist = np.linalg.norm(ball_pos - lower_bite_pos) return 0.5*(upper_dist + lower_dist) def ball_to_target_distance(self): """Returns the distance from the ball to the target.""" ball_pos, target_pos = self.named.data.geom_xpos[['ball', 'target']] return np.linalg.norm(ball_pos - target_pos) class Stand(base.Task): """A dog stand task generating upright posture.""" def __init__(self, random=None, observe_reward_factors=False): """Initializes an instance of `Stand`. Args: random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). observe_reward_factors: Boolean, whether the factorised reward is a key in the observation dict returned to the agent. """ self._observe_reward_factors = observe_reward_factors super().__init__(random=random) def initialize_episode(self, physics): """Randomizes initial root velocities and actuator states. Args: physics: An instance of `Physics`. """ physics.reset() # Measure stand heights from default pose, above which stand reward is 1. self._stand_height = physics.torso_pelvis_height() * _STAND_HEIGHT_FRACTION # Measure body weight. body_mass = physics.named.model.body_subtreemass['torso'] self._body_weight = -physics.model.opt.gravity[2] * body_mass # Randomize horizontal orientation. azimuth = self.random.uniform(0, 2*np.pi) orientation = np.array((np.cos(azimuth/2), 0, 0, np.sin(azimuth/2))) physics.named.data.qpos['root'][3:] = orientation # Randomize root velocities in horizontal plane. physics.data.qvel[0] = 2 * self.random.randn() physics.data.qvel[1] = 2 * self.random.randn() physics.data.qvel[5] = 2 * self.random.randn() # Randomize actuator states. assert physics.model.nu == physics.model.na for actuator_id in range(physics.model.nu): ctrlrange = physics.model.actuator_ctrlrange[actuator_id] physics.data.act[actuator_id] = self.random.uniform(*ctrlrange) def get_observation_components(self, physics): """Returns the observations for the Stand task.""" obs = collections.OrderedDict() obs['joint_angles'] = physics.joint_angles() obs['joint_velocites'] = physics.joint_velocities() obs['torso_pelvis_height'] = physics.torso_pelvis_height() obs['z_projection'] = physics.z_projection().flatten() obs['torso_com_velocity'] = physics.torso_com_velocity() obs['inertial_sensors'] = physics.inertial_sensors() obs['foot_forces'] = physics.foot_forces() obs['touch_sensors'] = physics.touch_sensors() obs['actuator_state'] = physics.data.act.copy() return obs def get_observation(self, physics): """Returns the observation, possibly adding reward factors.""" obs = self.get_observation_components(physics) if self._observe_reward_factors: obs['reward_factors'] = self.get_reward_factors(physics) return obs def get_reward_factors(self, physics): """Returns the factorized reward.""" # Keep the torso at standing height. torso = rewards.tolerance(physics.torso_pelvis_height()[0], bounds=(self._stand_height[0], float('inf')), margin=self._stand_height[0]) # Keep the pelvis at standing height. pelvis = rewards.tolerance(physics.torso_pelvis_height()[1], bounds=(self._stand_height[1], float('inf')), margin=self._stand_height[1]) # Keep head, torso and pelvis upright. upright = rewards.tolerance(physics.upright(), bounds=(_MIN_UPRIGHT_COSINE, float('inf')), sigmoid='linear', margin=_MIN_UPRIGHT_COSINE+1, value_at_margin=0) # Reward for foot touch forces up to bodyweight. touch = rewards.tolerance(physics.touch_sensors().sum(), bounds=(self._body_weight, float('inf')), margin=self._body_weight, sigmoid='linear', value_at_margin=0.9) return np.hstack((torso, pelvis, upright, touch)) def get_reward(self, physics): """Returns the reward, product of reward factors.""" return np.prod(self.get_reward_factors(physics)) class Move(Stand): """A dog move task for generating locomotion.""" def __init__(self, move_speed, random, observe_reward_factors=False): """Initializes an instance of `Move`. Args: move_speed: A float. Specifies a target horizontal velocity. random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). observe_reward_factors: Boolean, whether the factorised reward is a component of the observation dict. """ self._move_speed = move_speed super().__init__(random, observe_reward_factors) def get_reward_factors(self, physics): """Returns the factorized reward.""" standing = super().get_reward_factors(physics) speed_margin = max(1.0, self._move_speed) forward = rewards.tolerance(physics.com_forward_velocity(), bounds=(self._move_speed, 2*self._move_speed), margin=speed_margin, value_at_margin=0, sigmoid='linear') forward = (4*forward + 1) / 5 return np.hstack((standing, forward)) class Fetch(Stand): """A dog fetch task to fetch a thrown ball.""" def __init__(self, random, observe_reward_factors=False): """Initializes an instance of `Move`. Args: random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). observe_reward_factors: Boolean, whether the factorised reward is a component of the observation dict. """ super().__init__(random, observe_reward_factors) def initialize_episode(self, physics): super().initialize_episode(physics) # Set initial ball state: flying towards the center at an upward angle. radius = 0.75 * physics.named.model.geom_size['floor', 0] azimuth = self.random.uniform(0, 2*np.pi) position = (radius*np.sin(azimuth), radius*np.cos(azimuth), 0.05) physics.named.data.qpos['ball_root'][:3] = position vertical_height = self.random.uniform(0, 3) # Equating kinetic and potential energy: mv^2/2 = m*g*h -> v = sqrt(2gh) gravity = -physics.model.opt.gravity[2] vertical_velocity = np.sqrt(2 * gravity * vertical_height) horizontal_speed = self.random.uniform(0, 5) # Pointing towards the center, with some noise. direction = np.array((-np.sin(azimuth) + 0.05*self.random.randn(), -np.cos(azimuth) + 0.05*self.random.randn())) horizontal_velocity = horizontal_speed * direction velocity = np.hstack((horizontal_velocity, vertical_velocity)) physics.named.data.qvel['ball_root'][:3] = velocity def get_observation_components(self, physics): """Returns the common observations for the Stand task.""" obs = super().get_observation_components(physics) obs['ball_state'] = physics.ball_in_head_frame() obs['target_position'] = physics.target_in_head_frame() return obs def get_reward_factors(self, physics): """Returns a reward to the agent.""" standing = super().get_reward_factors(physics) # Reward for bringing mouth close to ball. bite_radius = physics.named.model.site_size['upper_bite', 0] bite_margin = 2 reach_ball = rewards.tolerance(physics.ball_to_mouth_distance(), bounds=(0, bite_radius), sigmoid='reciprocal', margin=bite_margin) reach_ball = (6*reach_ball + 1) / 7 # Reward for bringing the ball close to the target. target_radius = physics.named.model.geom_size['target', 0] bring_margin = physics.named.model.geom_size['floor', 0] ball_near_target = rewards.tolerance( physics.ball_to_target_distance(), bounds=(0, target_radius), sigmoid='reciprocal', margin=bring_margin) fetch_ball = (ball_near_target + 1) / 2 # Let go of the ball if it's been fetched. if physics.ball_to_target_distance() < 2*target_radius: reach_ball = 1 return np.hstack((standing, reach_ball, fetch_ball))
dm_control-main
dm_control/suite/dog.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. # ============================================================================ """Control suite environments explorer.""" from absl import app from absl import flags from dm_control import suite from dm_control.suite.wrappers import action_noise from dm_control import viewer _ALL_NAMES = ['.'.join(domain_task) for domain_task in suite.ALL_TASKS] flags.DEFINE_enum('environment_name', None, _ALL_NAMES, 'Optional \'domain_name.task_name\' pair specifying the ' 'environment to load. If unspecified a prompt will appear to ' 'select one.') flags.DEFINE_bool('timeout', True, 'Whether episodes should have a time limit.') flags.DEFINE_bool('visualize_reward', True, 'Whether to vary the colors of geoms according to the ' 'current reward value.') flags.DEFINE_float('action_noise', 0., 'Standard deviation of Gaussian noise to apply to actions, ' 'expressed as a fraction of the max-min range for each ' 'action dimension. Defaults to 0, i.e. no noise.') FLAGS = flags.FLAGS 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 if environment_name is None: print('\n '.join(['Available environments:'] + _ALL_NAMES)) environment_name = prompt_environment_name( 'Please select an environment name: ', _ALL_NAMES) index = _ALL_NAMES.index(environment_name) domain_name, task_name = suite.ALL_TASKS[index] task_kwargs = {} if not FLAGS.timeout: task_kwargs['time_limit'] = float('inf') def loader(): env = suite.load( domain_name=domain_name, task_name=task_name, task_kwargs=task_kwargs) env.task.visualize_reward = FLAGS.visualize_reward if FLAGS.action_noise > 0: env = action_noise.Wrapper(env, scale=FLAGS.action_noise) return env viewer.launch(loader) if __name__ == '__main__': app.run(main)
dm_control-main
dm_control/suite/explore.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. # ============================================================================ """Acrobot domain.""" import collections from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.utils import containers from dm_control.utils import rewards import numpy as np _DEFAULT_TIME_LIMIT = 10 SUITE = containers.TaggedTasks() def get_model_and_assets(): """Returns a tuple containing the model XML string and a dict of assets.""" return common.read_model('acrobot.xml'), common.ASSETS @SUITE.add('benchmarking') def swingup(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns Acrobot balance task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Balance(sparse=False, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, **environment_kwargs) @SUITE.add('benchmarking') def swingup_sparse(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns Acrobot sparse balance.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Balance(sparse=True, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, **environment_kwargs) class Physics(mujoco.Physics): """Physics simulation with additional features for the Acrobot domain.""" def horizontal(self): """Returns horizontal (x) component of body frame z-axes.""" return self.named.data.xmat[['upper_arm', 'lower_arm'], 'xz'] def vertical(self): """Returns vertical (z) component of body frame z-axes.""" return self.named.data.xmat[['upper_arm', 'lower_arm'], 'zz'] def to_target(self): """Returns the distance from the tip to the target.""" tip_to_target = (self.named.data.site_xpos['target'] - self.named.data.site_xpos['tip']) return np.linalg.norm(tip_to_target) def orientations(self): """Returns the sines and cosines of the pole angles.""" return np.concatenate((self.horizontal(), self.vertical())) class Balance(base.Task): """An Acrobot `Task` to swing up and balance the pole.""" def __init__(self, sparse, random=None): """Initializes an instance of `Balance`. Args: sparse: A `bool` specifying whether to use a sparse (indicator) reward. random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). """ self._sparse = sparse super().__init__(random=random) def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode. Shoulder and elbow are set to a random position between [-pi, pi). Args: physics: An instance of `Physics`. """ physics.named.data.qpos[ ['shoulder', 'elbow']] = self.random.uniform(-np.pi, np.pi, 2) super().initialize_episode(physics) def get_observation(self, physics): """Returns an observation of pole orientation and angular velocities.""" obs = collections.OrderedDict() obs['orientations'] = physics.orientations() obs['velocity'] = physics.velocity() return obs def _get_reward(self, physics, sparse): target_radius = physics.named.model.site_size['target', 0] return rewards.tolerance(physics.to_target(), bounds=(0, target_radius), margin=0 if sparse else 1) def get_reward(self, physics): """Returns a sparse or a smooth reward, as specified in the constructor.""" return self._get_reward(physics, sparse=self._sparse)
dm_control-main
dm_control/suite/acrobot.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for dm_control.suite domains.""" from absl.testing import absltest from absl.testing import parameterized from dm_control import suite from dm_control.mujoco.wrapper.mjbindings import constants from dm_control.rl import control import mock import numpy as np _DOMAINS_AND_TASKS = [ dict(domain=domain, task=task) for domain, task in suite.ALL_TASKS ] def uniform_random_policy(action_spec, random=None): lower_bounds = action_spec.minimum upper_bounds = action_spec.maximum # Draw values between -1 and 1 for actions where the min/max is set to # MuJoCo's internal limit. lower_bounds = np.where( np.abs(lower_bounds) >= constants.mjMAXVAL, -1.0, lower_bounds) upper_bounds = np.where( np.abs(upper_bounds) >= constants.mjMAXVAL, 1.0, upper_bounds) random_state = np.random.RandomState(random) def policy(time_step): del time_step # Unused. return random_state.uniform(lower_bounds, upper_bounds) return policy def step_environment(env, policy, num_episodes=5, max_steps_per_episode=10): for _ in range(num_episodes): step_count = 0 time_step = env.reset() yield time_step while not time_step.last(): action = policy(time_step) time_step = env.step(action) step_count += 1 yield time_step if step_count >= max_steps_per_episode: break def make_trajectory(domain, task, seed, **trajectory_kwargs): env = suite.load(domain, task, task_kwargs={'random': seed}) policy = uniform_random_policy(env.action_spec(), random=seed) return step_environment(env, policy, **trajectory_kwargs) class SuiteTest(parameterized.TestCase): """Tests run on all the tasks registered.""" def test_constants(self): num_tasks = sum(len(tasks) for tasks in suite.TASKS_BY_DOMAIN.values()) self.assertLen(suite.ALL_TASKS, num_tasks) def _validate_observation(self, observation_dict, observation_spec): obs = observation_dict.copy() for name, spec in observation_spec.items(): arr = obs.pop(name) self.assertEqual(arr.shape, spec.shape) self.assertEqual(arr.dtype, spec.dtype) self.assertTrue( np.all(np.isfinite(arr)), msg='{!r} has non-finite value(s): {!r}'.format(name, arr)) self.assertEmpty( obs, msg='Observation contains arrays(s) that are not in the spec: {!r}' .format(obs)) def _validate_reward_range(self, time_step): if time_step.first(): self.assertIsNone(time_step.reward) else: self.assertIsInstance(time_step.reward, float) self.assertBetween(time_step.reward, 0, 1) def _validate_discount(self, time_step): if time_step.first(): self.assertIsNone(time_step.discount) else: self.assertIsInstance(time_step.discount, float) self.assertBetween(time_step.discount, 0, 1) def _validate_control_range(self, lower_bounds, upper_bounds): for b in lower_bounds: self.assertEqual(b, -1.0) for b in upper_bounds: self.assertEqual(b, 1.0) @parameterized.parameters(_DOMAINS_AND_TASKS) def test_components_have_names(self, domain, task): env = suite.load(domain, task) model = env.physics.model object_types_and_size_fields = [ ('body', 'nbody'), ('joint', 'njnt'), ('geom', 'ngeom'), ('site', 'nsite'), ('camera', 'ncam'), ('light', 'nlight'), ('mesh', 'nmesh'), ('hfield', 'nhfield'), ('texture', 'ntex'), ('material', 'nmat'), ('equality', 'neq'), ('tendon', 'ntendon'), ('actuator', 'nu'), ('sensor', 'nsensor'), ('numeric', 'nnumeric'), ('text', 'ntext'), ('tuple', 'ntuple'), ] for object_type, size_field in object_types_and_size_fields: for idx in range(getattr(model, size_field)): object_name = model.id2name(idx, object_type) self.assertNotEqual(object_name, '', msg='Model {!r} contains unnamed {!r} with ID {}.' .format(model.name, object_type, idx)) @parameterized.parameters(_DOMAINS_AND_TASKS) def test_model_has_at_least_2_cameras(self, domain, task): env = suite.load(domain, task) model = env.physics.model self.assertGreaterEqual(model.ncam, 2, 'Model {!r} should have at least 2 cameras, has {}.' .format(model.name, model.ncam)) @parameterized.parameters(_DOMAINS_AND_TASKS) def test_task_conforms_to_spec(self, domain, task): """Tests that the environment timesteps conform to specifications.""" is_benchmark = (domain, task) in suite.BENCHMARKING env = suite.load(domain, task) observation_spec = env.observation_spec() action_spec = env.action_spec() # Check action bounds. if is_benchmark: self._validate_control_range(action_spec.minimum, action_spec.maximum) # Step through the environment, applying random actions sampled within the # valid range and check the observations, rewards, and discounts. policy = uniform_random_policy(action_spec) for time_step in step_environment(env, policy): self._validate_observation(time_step.observation, observation_spec) self._validate_discount(time_step) if is_benchmark: self._validate_reward_range(time_step) @parameterized.parameters(_DOMAINS_AND_TASKS) def test_environment_is_deterministic(self, domain, task): """Tests that identical seeds and actions produce identical trajectories.""" seed = 0 # Iterate over two trajectories generated using identical sequences of # random actions, and with identical task random states. Check that the # observations, rewards, discounts and step types are identical. trajectory1 = make_trajectory(domain=domain, task=task, seed=seed) trajectory2 = make_trajectory(domain=domain, task=task, seed=seed) for time_step1, time_step2 in zip(trajectory1, trajectory2): self.assertEqual(time_step1.step_type, time_step2.step_type) self.assertEqual(time_step1.reward, time_step2.reward) self.assertEqual(time_step1.discount, time_step2.discount) for key in time_step1.observation.keys(): np.testing.assert_array_equal( time_step1.observation[key], time_step2.observation[key], err_msg='Observation {!r} is not equal.'.format(key)) def assertCorrectColors(self, physics, reward): colors = physics.named.model.mat_rgba for material_name in ('self', 'effector', 'target'): highlight = colors[material_name + '_highlight'] default = colors[material_name + '_default'] blend_coef = reward ** 4 expected = blend_coef * highlight + (1.0 - blend_coef) * default actual = colors[material_name] err_msg = ('Material {!r} has unexpected color.\nExpected: {!r}\n' 'Actual: {!r}'.format(material_name, expected, actual)) np.testing.assert_array_almost_equal(expected, actual, err_msg=err_msg) @parameterized.parameters(*suite.REWARD_VIZ) def test_visualize_reward(self, domain, task): env = suite.load(domain, task) env.task.visualize_reward = True action = np.zeros(env.action_spec().shape) with mock.patch.object(env.task, 'get_reward') as mock_get_reward: mock_get_reward.return_value = -3.0 # Rewards < 0 should be clipped. env.reset() mock_get_reward.assert_called_with(env.physics) self.assertCorrectColors(env.physics, reward=0.0) mock_get_reward.reset_mock() mock_get_reward.return_value = 0.5 env.step(action) mock_get_reward.assert_called_with(env.physics) self.assertCorrectColors(env.physics, reward=mock_get_reward.return_value) mock_get_reward.reset_mock() mock_get_reward.return_value = 2.0 # Rewards > 1 should be clipped. env.step(action) mock_get_reward.assert_called_with(env.physics) self.assertCorrectColors(env.physics, reward=1.0) mock_get_reward.reset_mock() mock_get_reward.return_value = 0.25 env.reset() mock_get_reward.assert_called_with(env.physics) self.assertCorrectColors(env.physics, reward=mock_get_reward.return_value) @parameterized.parameters(_DOMAINS_AND_TASKS) def test_task_supports_environment_kwargs(self, domain, task): env = suite.load(domain, task, environment_kwargs=dict(flat_observation=True)) # Check that the kwargs are actually passed through to the environment. self.assertSetEqual(set(env.observation_spec()), {control.FLAT_OBSERVATION_KEY}) @parameterized.parameters(_DOMAINS_AND_TASKS) def test_observation_arrays_dont_share_memory(self, domain, task): env = suite.load(domain, task) first_timestep = env.reset() action = np.zeros(env.action_spec().shape) second_timestep = env.step(action) for name, first_array in first_timestep.observation.items(): second_array = second_timestep.observation[name] self.assertFalse( np.may_share_memory(first_array, second_array), msg='Consecutive observations of {!r} may share memory.'.format(name)) @parameterized.parameters(_DOMAINS_AND_TASKS) def test_observations_dont_contain_constant_elements(self, domain, task): env = suite.load(domain, task) trajectory = make_trajectory(domain=domain, task=task, seed=0, num_episodes=2, max_steps_per_episode=1000) observations = {name: [] for name in env.observation_spec()} for time_step in trajectory: for name, array in time_step.observation.items(): observations[name].append(array) failures = [] for name, array_list in observations.items(): # Sampling random uniform actions generally isn't sufficient to trigger # these touch sensors. if (domain in ('manipulator', 'stacker', 'finger') and name == 'touch' or domain == 'quadruped' and name == 'force_torque'): continue stacked_arrays = np.array(array_list) is_constant = np.all(stacked_arrays == stacked_arrays[0], axis=0) has_constant_elements = ( is_constant if np.isscalar(is_constant) else np.any(is_constant)) if has_constant_elements: failures.append((name, is_constant)) self.assertEmpty( failures, msg='The following observation(s) contain constant elements:\n{}' .format('\n'.join(':\t'.join([name, str(is_constant)]) for (name, is_constant) in failures))) @parameterized.parameters(_DOMAINS_AND_TASKS) def test_initial_state_is_randomized(self, domain, task): env = suite.load(domain, task, task_kwargs={'random': 42}) obs1 = env.reset().observation obs2 = env.reset().observation self.assertFalse( all(np.all(obs1[k] == obs2[k]) for k in obs1), 'Two consecutive initial states have identical observations.\n' 'First: {}\nSecond: {}'.format(obs1, obs2)) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/suite/suite_test.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for the dm_control.suite loader.""" from absl.testing import absltest from dm_control import suite from dm_control.rl import control class LoaderTest(absltest.TestCase): def test_load_without_kwargs(self): env = suite.load('cartpole', 'swingup') self.assertIsInstance(env, control.Environment) def test_load_with_kwargs(self): env = suite.load('cartpole', 'swingup', task_kwargs={'time_limit': 40, 'random': 99}) self.assertIsInstance(env, control.Environment) class LoaderConstantsTest(absltest.TestCase): def testSuiteConstants(self): self.assertNotEmpty(suite.BENCHMARKING) self.assertNotEmpty(suite.EASY) self.assertNotEmpty(suite.HARD) self.assertNotEmpty(suite.EXTRA) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/suite/loader_test.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Pendulum domain.""" import collections from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.utils import containers from dm_control.utils import rewards import numpy as np _DEFAULT_TIME_LIMIT = 20 _ANGLE_BOUND = 8 _COSINE_BOUND = np.cos(np.deg2rad(_ANGLE_BOUND)) SUITE = containers.TaggedTasks() def get_model_and_assets(): """Returns a tuple containing the model XML string and a dict of assets.""" return common.read_model('pendulum.xml'), common.ASSETS @SUITE.add('benchmarking') def swingup(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns pendulum swingup task .""" physics = Physics.from_xml_string(*get_model_and_assets()) task = SwingUp(random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, **environment_kwargs) class Physics(mujoco.Physics): """Physics simulation with additional features for the Pendulum domain.""" def pole_vertical(self): """Returns vertical (z) component of pole frame.""" return self.named.data.xmat['pole', 'zz'] def angular_velocity(self): """Returns the angular velocity of the pole.""" return self.named.data.qvel['hinge'].copy() def pole_orientation(self): """Returns both horizontal and vertical components of pole frame.""" return self.named.data.xmat['pole', ['zz', 'xz']] class SwingUp(base.Task): """A Pendulum `Task` to swing up and balance the pole.""" def __init__(self, random=None): """Initialize an instance of `Pendulum`. Args: random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). """ super().__init__(random=random) def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode. Pole is set to a random angle between [-pi, pi). Args: physics: An instance of `Physics`. """ physics.named.data.qpos['hinge'] = self.random.uniform(-np.pi, np.pi) super().initialize_episode(physics) def get_observation(self, physics): """Returns an observation. Observations are states concatenating pole orientation and angular velocity and pixels from fixed camera. Args: physics: An instance of `physics`, Pendulum physics. Returns: A `dict` of observation. """ obs = collections.OrderedDict() obs['orientation'] = physics.pole_orientation() obs['velocity'] = physics.angular_velocity() return obs def get_reward(self, physics): return rewards.tolerance(physics.pole_vertical(), (_COSINE_BOUND, 1))
dm_control-main
dm_control/suite/pendulum.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. # ============================================================================ """Fish Domain.""" import collections from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.utils import containers from dm_control.utils import rewards import numpy as np _DEFAULT_TIME_LIMIT = 40 _CONTROL_TIMESTEP = .04 _JOINTS = ['tail1', 'tail_twist', 'tail2', 'finright_roll', 'finright_pitch', 'finleft_roll', 'finleft_pitch'] SUITE = containers.TaggedTasks() def get_model_and_assets(): """Returns a tuple containing the model XML string and a dict of assets.""" return common.read_model('fish.xml'), common.ASSETS @SUITE.add('benchmarking') def upright(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Fish Upright task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Upright(random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, control_timestep=_CONTROL_TIMESTEP, time_limit=time_limit, **environment_kwargs) @SUITE.add('benchmarking') def swim(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Fish Swim task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Swim(random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, control_timestep=_CONTROL_TIMESTEP, time_limit=time_limit, **environment_kwargs) class Physics(mujoco.Physics): """Physics simulation with additional features for the Fish domain.""" def upright(self): """Returns projection from z-axes of torso to the z-axes of worldbody.""" return self.named.data.xmat['torso', 'zz'] def torso_velocity(self): """Returns velocities and angular velocities of the torso.""" return self.data.sensordata def joint_velocities(self): """Returns the joint velocities.""" return self.named.data.qvel[_JOINTS] def joint_angles(self): """Returns the joint positions.""" return self.named.data.qpos[_JOINTS] def mouth_to_target(self): """Returns a vector, from mouth to target in local coordinate of mouth.""" data = self.named.data mouth_to_target_global = data.geom_xpos['target'] - data.geom_xpos['mouth'] return mouth_to_target_global.dot(data.geom_xmat['mouth'].reshape(3, 3)) class Upright(base.Task): """A Fish `Task` for getting the torso upright with smooth reward.""" def __init__(self, random=None): """Initializes an instance of `Upright`. Args: random: Either an existing `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically. """ super().__init__(random=random) def initialize_episode(self, physics): """Randomizes the tail and fin angles and the orientation of the Fish.""" quat = self.random.randn(4) physics.named.data.qpos['root'][3:7] = quat / np.linalg.norm(quat) for joint in _JOINTS: physics.named.data.qpos[joint] = self.random.uniform(-.2, .2) # Hide the target. It's irrelevant for this task. physics.named.model.geom_rgba['target', 3] = 0 super().initialize_episode(physics) def get_observation(self, physics): """Returns an observation of joint angles, velocities and uprightness.""" obs = collections.OrderedDict() obs['joint_angles'] = physics.joint_angles() obs['upright'] = physics.upright() obs['velocity'] = physics.velocity() return obs def get_reward(self, physics): """Returns a smooth reward.""" return rewards.tolerance(physics.upright(), bounds=(1, 1), margin=1) class Swim(base.Task): """A Fish `Task` for swimming with smooth reward.""" def __init__(self, random=None): """Initializes an instance of `Swim`. Args: random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). """ super().__init__(random=random) def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode.""" quat = self.random.randn(4) physics.named.data.qpos['root'][3:7] = quat / np.linalg.norm(quat) for joint in _JOINTS: physics.named.data.qpos[joint] = self.random.uniform(-.2, .2) # Randomize target position. physics.named.model.geom_pos['target', 'x'] = self.random.uniform(-.4, .4) physics.named.model.geom_pos['target', 'y'] = self.random.uniform(-.4, .4) physics.named.model.geom_pos['target', 'z'] = self.random.uniform(.1, .3) super().initialize_episode(physics) def get_observation(self, physics): """Returns an observation of joints, target direction and velocities.""" obs = collections.OrderedDict() obs['joint_angles'] = physics.joint_angles() obs['upright'] = physics.upright() obs['target'] = physics.mouth_to_target() obs['velocity'] = physics.velocity() return obs def get_reward(self, physics): """Returns a smooth reward.""" radii = physics.named.model.geom_size[['mouth', 'target'], 0].sum() in_target = rewards.tolerance(np.linalg.norm(physics.mouth_to_target()), bounds=(0, radii), margin=2*radii) is_upright = 0.5 * (physics.upright() + 1) return (7*in_target + is_upright) / 8
dm_control-main
dm_control/suite/fish.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. # ============================================================================ """Base class for tasks in the Control Suite.""" from dm_control import mujoco from dm_control.rl import control import numpy as np class Task(control.Task): """Base class for tasks in the Control Suite. Actions are mapped directly to the states of MuJoCo actuators: each element of the action array is used to set the control input for a single actuator. The ordering of the actuators is the same as in the corresponding MJCF XML file. Attributes: random: A `numpy.random.RandomState` instance. This should be used to generate all random variables associated with the task, such as random starting states, observation noise* etc. *If sensor noise is enabled in the MuJoCo model then this will be generated using MuJoCo's internal RNG, which has its own independent state. """ def __init__(self, random=None): """Initializes a new continuous control task. Args: random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). """ if not isinstance(random, np.random.RandomState): random = np.random.RandomState(random) self._random = random self._visualize_reward = False @property def random(self): """Task-specific `numpy.random.RandomState` instance.""" return self._random def action_spec(self, physics): """Returns a `BoundedArraySpec` matching the `physics` actuators.""" return mujoco.action_spec(physics) def initialize_episode(self, physics): """Resets geom colors to their defaults after starting a new episode. Subclasses of `base.Task` must delegate to this method after performing their own initialization. Args: physics: An instance of `mujoco.Physics`. """ self.after_step(physics) def before_step(self, action, physics): """Sets the control signal for the actuators to values in `action`.""" # Support legacy internal code. action = getattr(action, "continuous_actions", action) physics.set_control(action) def after_step(self, physics): """Modifies colors according to the reward.""" if self._visualize_reward: reward = np.clip(self.get_reward(physics), 0.0, 1.0) _set_reward_colors(physics, reward) @property def visualize_reward(self): return self._visualize_reward @visualize_reward.setter def visualize_reward(self, value): if not isinstance(value, bool): raise ValueError("Expected a boolean, got {}.".format(type(value))) self._visualize_reward = value _MATERIALS = ["self", "effector", "target"] _DEFAULT = [name + "_default" for name in _MATERIALS] _HIGHLIGHT = [name + "_highlight" for name in _MATERIALS] def _set_reward_colors(physics, reward): """Sets the highlight, effector and target colors according to the reward.""" assert 0.0 <= reward <= 1.0 colors = physics.named.model.mat_rgba default = colors[_DEFAULT] highlight = colors[_HIGHLIGHT] blend_coef = reward ** 4 # Better color distinction near high rewards. colors[_MATERIALS] = blend_coef * highlight + (1.0 - blend_coef) * default
dm_control-main
dm_control/suite/base.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. # ============================================================================ """Procedurally generated Swimmer domain.""" import collections from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.suite.utils import randomizers from dm_control.utils import containers from dm_control.utils import rewards from lxml import etree import numpy as np _DEFAULT_TIME_LIMIT = 30 _CONTROL_TIMESTEP = .03 # (Seconds) SUITE = containers.TaggedTasks() def get_model_and_assets(n_joints): """Returns a tuple containing the model XML string and a dict of assets. Args: n_joints: An integer specifying the number of joints in the swimmer. Returns: A tuple `(model_xml_string, assets)`, where `assets` is a dict consisting of `{filename: contents_string}` pairs. """ return _make_model(n_joints), common.ASSETS @SUITE.add('benchmarking') def swimmer6(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns a 6-link swimmer.""" return _make_swimmer(6, time_limit, random=random, environment_kwargs=environment_kwargs) @SUITE.add('benchmarking') def swimmer15(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns a 15-link swimmer.""" return _make_swimmer(15, time_limit, random=random, environment_kwargs=environment_kwargs) def swimmer(n_links=3, time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns a swimmer with n links.""" return _make_swimmer(n_links, time_limit, random=random, environment_kwargs=environment_kwargs) def _make_swimmer(n_joints, time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns a swimmer control environment.""" model_string, assets = get_model_and_assets(n_joints) physics = Physics.from_xml_string(model_string, assets=assets) task = Swimmer(random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) def _make_model(n_bodies): """Generates an xml string defining a swimmer with `n_bodies` bodies.""" if n_bodies < 3: raise ValueError('At least 3 bodies required. Received {}'.format(n_bodies)) mjcf = etree.fromstring(common.read_model('swimmer.xml')) head_body = mjcf.find('./worldbody/body') actuator = etree.SubElement(mjcf, 'actuator') sensor = etree.SubElement(mjcf, 'sensor') parent = head_body for body_index in range(n_bodies - 1): site_name = 'site_{}'.format(body_index) child = _make_body(body_index=body_index) child.append(etree.Element('site', name=site_name)) joint_name = 'joint_{}'.format(body_index) joint_limit = 360.0/n_bodies joint_range = '{} {}'.format(-joint_limit, joint_limit) child.append(etree.Element('joint', {'name': joint_name, 'range': joint_range})) motor_name = 'motor_{}'.format(body_index) actuator.append(etree.Element('motor', name=motor_name, joint=joint_name)) velocimeter_name = 'velocimeter_{}'.format(body_index) sensor.append(etree.Element('velocimeter', name=velocimeter_name, site=site_name)) gyro_name = 'gyro_{}'.format(body_index) sensor.append(etree.Element('gyro', name=gyro_name, site=site_name)) parent.append(child) parent = child # Move tracking cameras further away from the swimmer according to its length. cameras = mjcf.findall('./worldbody/body/camera') scale = n_bodies / 6.0 for cam in cameras: if cam.get('mode') == 'trackcom': old_pos = cam.get('pos').split(' ') new_pos = ' '.join([str(float(dim) * scale) for dim in old_pos]) cam.set('pos', new_pos) return etree.tostring(mjcf, pretty_print=True) def _make_body(body_index): """Generates an xml string defining a single physical body.""" body_name = 'segment_{}'.format(body_index) visual_name = 'visual_{}'.format(body_index) inertial_name = 'inertial_{}'.format(body_index) body = etree.Element('body', name=body_name) body.set('pos', '0 .1 0') etree.SubElement(body, 'geom', {'class': 'visual', 'name': visual_name}) etree.SubElement(body, 'geom', {'class': 'inertial', 'name': inertial_name}) return body class Physics(mujoco.Physics): """Physics simulation with additional features for the swimmer domain.""" def nose_to_target(self): """Returns a vector from nose to target in local coordinate of the head.""" nose_to_target = (self.named.data.geom_xpos['target'] - self.named.data.geom_xpos['nose']) head_orientation = self.named.data.xmat['head'].reshape(3, 3) return nose_to_target.dot(head_orientation)[:2] def nose_to_target_dist(self): """Returns the distance from the nose to the target.""" return np.linalg.norm(self.nose_to_target()) def body_velocities(self): """Returns local body velocities: x,y linear, z rotational.""" xvel_local = self.data.sensordata[12:].reshape((-1, 6)) vx_vy_wz = [0, 1, 5] # Indices for linear x,y vels and rotational z vel. return xvel_local[:, vx_vy_wz].ravel() def joints(self): """Returns all internal joint angles (excluding root joints).""" return self.data.qpos[3:].copy() class Swimmer(base.Task): """A swimmer `Task` to reach the target or just swim.""" def __init__(self, random=None): """Initializes an instance of `Swimmer`. Args: random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). """ super().__init__(random=random) def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode. Initializes the swimmer orientation to [-pi, pi) and the relative joint angle of each joint uniformly within its range. Args: physics: An instance of `Physics`. """ # Random joint angles: randomizers.randomize_limited_and_rotational_joints(physics, self.random) # Random target position. close_target = self.random.rand() < .2 # Probability of a close target. target_box = .3 if close_target else 2 xpos, ypos = self.random.uniform(-target_box, target_box, size=2) physics.named.model.geom_pos['target', 'x'] = xpos physics.named.model.geom_pos['target', 'y'] = ypos physics.named.model.light_pos['target_light', 'x'] = xpos physics.named.model.light_pos['target_light', 'y'] = ypos super().initialize_episode(physics) def get_observation(self, physics): """Returns an observation of joint angles, body velocities and target.""" obs = collections.OrderedDict() obs['joints'] = physics.joints() obs['to_target'] = physics.nose_to_target() obs['body_velocities'] = physics.body_velocities() return obs def get_reward(self, physics): """Returns a smooth reward.""" target_size = physics.named.model.geom_size['target', 0] return rewards.tolerance(physics.nose_to_target_dist(), bounds=(0, target_size), margin=5*target_size, sigmoid='long_tail')
dm_control-main
dm_control/suite/swimmer.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. # ============================================================================ """Finger Domain.""" import collections from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.suite.utils import randomizers from dm_control.utils import containers import numpy as np _DEFAULT_TIME_LIMIT = 20 # (seconds) _CONTROL_TIMESTEP = .02 # (seconds) # For TURN tasks, the 'tip' geom needs to enter a spherical target of sizes: _EASY_TARGET_SIZE = 0.07 _HARD_TARGET_SIZE = 0.03 # Initial spin velocity for the Stop task. _INITIAL_SPIN_VELOCITY = 100 # Spinning slower than this value (radian/second) is considered stopped. _STOP_VELOCITY = 1e-6 # Spinning faster than this value (radian/second) is considered spinning. _SPIN_VELOCITY = 15.0 SUITE = containers.TaggedTasks() def get_model_and_assets(): """Returns a tuple containing the model XML string and a dict of assets.""" return common.read_model('finger.xml'), common.ASSETS @SUITE.add('benchmarking') def spin(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Spin task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Spin(random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) @SUITE.add('benchmarking') def turn_easy(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the easy Turn task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Turn(target_radius=_EASY_TARGET_SIZE, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) @SUITE.add('benchmarking') def turn_hard(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the hard Turn task.""" physics = Physics.from_xml_string(*get_model_and_assets()) task = Turn(target_radius=_HARD_TARGET_SIZE, random=random) environment_kwargs = environment_kwargs or {} return control.Environment( physics, task, time_limit=time_limit, control_timestep=_CONTROL_TIMESTEP, **environment_kwargs) class Physics(mujoco.Physics): """Physics simulation with additional features for the Finger domain.""" def touch(self): """Returns logarithmically scaled signals from the two touch sensors.""" return np.log1p(self.named.data.sensordata[['touchtop', 'touchbottom']]) def hinge_velocity(self): """Returns the velocity of the hinge joint.""" return self.named.data.sensordata['hinge_velocity'] def tip_position(self): """Returns the (x,z) position of the tip relative to the hinge.""" return (self.named.data.sensordata['tip'][[0, 2]] - self.named.data.sensordata['spinner'][[0, 2]]) def bounded_position(self): """Returns the positions, with the hinge angle replaced by tip position.""" return np.hstack((self.named.data.sensordata[['proximal', 'distal']], self.tip_position())) def velocity(self): """Returns the velocities (extracted from sensordata).""" return self.named.data.sensordata[['proximal_velocity', 'distal_velocity', 'hinge_velocity']] def target_position(self): """Returns the (x,z) position of the target relative to the hinge.""" return (self.named.data.sensordata['target'][[0, 2]] - self.named.data.sensordata['spinner'][[0, 2]]) def to_target(self): """Returns the vector from the tip to the target.""" return self.target_position() - self.tip_position() def dist_to_target(self): """Returns the signed distance to the target surface, negative is inside.""" return (np.linalg.norm(self.to_target()) - self.named.model.site_size['target', 0]) class Spin(base.Task): """A Finger `Task` to spin the stopped body.""" def __init__(self, random=None): """Initializes a new `Spin` instance. Args: random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). """ super().__init__(random=random) def initialize_episode(self, physics): physics.named.model.site_rgba['target', 3] = 0 physics.named.model.site_rgba['tip', 3] = 0 physics.named.model.dof_damping['hinge'] = .03 _set_random_joint_angles(physics, self.random) super().initialize_episode(physics) def get_observation(self, physics): """Returns state and touch sensors, and target info.""" obs = collections.OrderedDict() obs['position'] = physics.bounded_position() obs['velocity'] = physics.velocity() obs['touch'] = physics.touch() return obs def get_reward(self, physics): """Returns a sparse reward.""" return float(physics.hinge_velocity() <= -_SPIN_VELOCITY) class Turn(base.Task): """A Finger `Task` to turn the body to a target angle.""" def __init__(self, target_radius, random=None): """Initializes a new `Turn` instance. Args: target_radius: Radius of the target site, which specifies the goal angle. random: Optional, either a `numpy.random.RandomState` instance, an integer seed for creating a new `RandomState`, or None to select a seed automatically (default). """ self._target_radius = target_radius super().__init__(random=random) def initialize_episode(self, physics): target_angle = self.random.uniform(-np.pi, np.pi) hinge_x, hinge_z = physics.named.data.xanchor['hinge', ['x', 'z']] radius = physics.named.model.geom_size['cap1'].sum() target_x = hinge_x + radius * np.sin(target_angle) target_z = hinge_z + radius * np.cos(target_angle) physics.named.model.site_pos['target', ['x', 'z']] = target_x, target_z physics.named.model.site_size['target', 0] = self._target_radius _set_random_joint_angles(physics, self.random) super().initialize_episode(physics) def get_observation(self, physics): """Returns state, touch sensors, and target info.""" obs = collections.OrderedDict() obs['position'] = physics.bounded_position() obs['velocity'] = physics.velocity() obs['touch'] = physics.touch() obs['target_position'] = physics.target_position() obs['dist_to_target'] = physics.dist_to_target() return obs def get_reward(self, physics): return float(physics.dist_to_target() <= 0) def _set_random_joint_angles(physics, random, max_attempts=1000): """Sets the joints to a random collision-free state.""" for _ in range(max_attempts): randomizers.randomize_limited_and_rotational_joints(physics, random) # Check for collisions. physics.after_reset() if physics.data.ncon == 0: break else: raise RuntimeError('Could not find a collision-free state ' 'after {} attempts'.format(max_attempts))
dm_control-main
dm_control/suite/finger.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 the action noise wrapper.""" from absl.testing import absltest from absl.testing import parameterized from dm_control.rl import control from dm_control.suite.wrappers import action_noise from dm_env import specs import mock import numpy as np class ActionNoiseTest(parameterized.TestCase): def make_action_spec(self, lower=(-1.,), upper=(1.,)): lower, upper = np.broadcast_arrays(lower, upper) return specs.BoundedArray( shape=lower.shape, dtype=float, minimum=lower, maximum=upper) def make_mock_env(self, action_spec=None): action_spec = action_spec or self.make_action_spec() env = mock.Mock(spec=control.Environment) env.action_spec.return_value = action_spec return env def assertStepCalledOnceWithCorrectAction(self, env, expected_action): # NB: `assert_called_once_with()` doesn't support numpy arrays. env.step.assert_called_once() actual_action = env.step.call_args_list[0][0][0] np.testing.assert_array_equal(expected_action, actual_action) @parameterized.parameters([ dict(lower=np.r_[-1., 0.], upper=np.r_[1., 2.], scale=0.05), dict(lower=np.r_[-1., 0.], upper=np.r_[1., 2.], scale=0.), dict(lower=np.r_[-1., 0.], upper=np.r_[-1., 0.], scale=0.05), ]) def test_step(self, lower, upper, scale): seed = 0 std = scale * (upper - lower) expected_noise = np.random.RandomState(seed).normal(scale=std) action = np.random.RandomState(seed).uniform(lower, upper) expected_noisy_action = np.clip(action + expected_noise, lower, upper) task = mock.Mock(spec=control.Task) task.random = np.random.RandomState(seed) action_spec = self.make_action_spec(lower=lower, upper=upper) env = self.make_mock_env(action_spec=action_spec) env.task = task wrapped_env = action_noise.Wrapper(env, scale=scale) time_step = wrapped_env.step(action) self.assertStepCalledOnceWithCorrectAction(env, expected_noisy_action) self.assertIs(time_step, env.step(expected_noisy_action)) @parameterized.named_parameters([ dict(testcase_name='within_bounds', action=np.r_[-1.], noise=np.r_[0.1]), dict(testcase_name='below_lower', action=np.r_[-1.], noise=np.r_[-0.1]), dict(testcase_name='above_upper', action=np.r_[1.], noise=np.r_[0.1]), ]) def test_action_clipping(self, action, noise): lower = -1. upper = 1. expected_noisy_action = np.clip(action + noise, lower, upper) task = mock.Mock(spec=control.Task) task.random = mock.Mock(spec=np.random.RandomState) task.random.normal.return_value = noise action_spec = self.make_action_spec(lower=lower, upper=upper) env = self.make_mock_env(action_spec=action_spec) env.task = task wrapped_env = action_noise.Wrapper(env) time_step = wrapped_env.step(action) self.assertStepCalledOnceWithCorrectAction(env, expected_noisy_action) self.assertIs(time_step, env.step(expected_noisy_action)) @parameterized.parameters([ dict(lower=np.r_[-1., 0.], upper=np.r_[1., np.inf]), dict(lower=np.r_[np.nan, 0.], upper=np.r_[1., 2.]), ]) def test_error_if_action_bounds_non_finite(self, lower, upper): action_spec = self.make_action_spec(lower=lower, upper=upper) env = self.make_mock_env(action_spec=action_spec) with self.assertRaisesWithLiteralMatch( ValueError, action_noise._BOUNDS_MUST_BE_FINITE.format(action_spec=action_spec)): _ = action_noise.Wrapper(env) def test_reset(self): env = self.make_mock_env() wrapped_env = action_noise.Wrapper(env) time_step = wrapped_env.reset() env.reset.assert_called_once_with() self.assertIs(time_step, env.reset()) def test_observation_spec(self): env = self.make_mock_env() wrapped_env = action_noise.Wrapper(env) observation_spec = wrapped_env.observation_spec() env.observation_spec.assert_called_once_with() self.assertIs(observation_spec, env.observation_spec()) def test_action_spec(self): env = self.make_mock_env() wrapped_env = action_noise.Wrapper(env) # `env.action_spec()` is called in `Wrapper.__init__()` env.action_spec.reset_mock() action_spec = wrapped_env.action_spec() env.action_spec.assert_called_once_with() self.assertIs(action_spec, env.action_spec()) @parameterized.parameters(['task', 'physics', 'control_timestep']) def test_getattr(self, attribute_name): env = self.make_mock_env() wrapped_env = action_noise.Wrapper(env) attr = getattr(wrapped_env, attribute_name) self.assertIs(attr, getattr(env, attribute_name)) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/suite/wrappers/action_noise_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. # ============================================================================ """Wrapper that adds pixel observations to a control environment.""" import collections import dm_env from dm_env import specs import numpy as np STATE_KEY = 'state' class Wrapper(dm_env.Environment): """Wraps a control environment and adds an observation with profile data. The profile data describes the time Mujoco spent in a "step", and the observation consists of two values: the cumulative time spent on steps (in seconds), and the number of times the profiling timer was called. """ def __init__(self, env, observation_key='step_timing'): """Initializes a new mujoco_profiling Wrapper. Args: env: The environment to wrap. observation_key: Optional custom string specifying the profile observation's key in the `OrderedDict` of observations. Defaults to 'step_timing'. Raises: ValueError: If `env`'s observation spec is not compatible with the wrapper. Supported formats are a single array, or a dict of arrays. ValueError: If `env`'s observation already contains the specified `observation_key`. """ wrapped_observation_spec = env.observation_spec() if isinstance(wrapped_observation_spec, specs.Array): self._observation_is_dict = False invalid_keys = set([STATE_KEY]) elif isinstance(wrapped_observation_spec, collections.abc.MutableMapping): self._observation_is_dict = True invalid_keys = set(wrapped_observation_spec.keys()) else: raise ValueError('Unsupported observation spec structure.') if observation_key in invalid_keys: raise ValueError( 'Duplicate or reserved observation key {!r}.'.format(observation_key)) if self._observation_is_dict: self._observation_spec = wrapped_observation_spec.copy() else: self._observation_spec = collections.OrderedDict() self._observation_spec[STATE_KEY] = wrapped_observation_spec env.physics.enable_profiling() # Extend observation spec. self._observation_spec[observation_key] = specs.Array( shape=(2,), dtype=np.double, name=observation_key) self._env = env self._observation_key = observation_key def reset(self): return self._add_profile_observation(self._env.reset()) def step(self, action): return self._add_profile_observation(self._env.step(action)) def observation_spec(self): return self._observation_spec def action_spec(self): return self._env.action_spec() def _add_profile_observation(self, time_step): if self._observation_is_dict: observation = type(time_step.observation)(time_step.observation) else: observation = collections.OrderedDict() observation[STATE_KEY] = time_step.observation # timer[0] is the step timer. There are lots of different timers (see # mujoco/include/mjdata.h) # but we only care about the step timer. timing = self._env.physics.data.timer[0] observation[self._observation_key] = np.array( [timing.duration, timing.number], dtype=np.double) return time_step._replace(observation=observation) def __getattr__(self, name): return getattr(self._env, name)
dm_control-main
dm_control/suite/wrappers/mujoco_profiling.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. # ============================================================================ """Wrapper that adds pixel observations to a control environment.""" import collections import dm_env from dm_env import specs STATE_KEY = 'state' class Wrapper(dm_env.Environment): """Wraps a control environment and adds a rendered pixel observation.""" def __init__(self, env, pixels_only=True, render_kwargs=None, observation_key='pixels'): """Initializes a new pixel Wrapper. Args: env: The environment to wrap. pixels_only: If True (default), the original set of 'state' observations returned by the wrapped environment will be discarded, and the `OrderedDict` of observations will only contain pixels. If False, the `OrderedDict` will contain the original observations as well as the pixel observations. render_kwargs: Optional `dict` containing keyword arguments passed to the `mujoco.Physics.render` method. observation_key: Optional custom string specifying the pixel observation's key in the `OrderedDict` of observations. Defaults to 'pixels'. Raises: ValueError: If `env`'s observation spec is not compatible with the wrapper. Supported formats are a single array, or a dict of arrays. ValueError: If `env`'s observation already contains the specified `observation_key`. """ if render_kwargs is None: render_kwargs = {} wrapped_observation_spec = env.observation_spec() if isinstance(wrapped_observation_spec, specs.Array): self._observation_is_dict = False invalid_keys = set([STATE_KEY]) elif isinstance(wrapped_observation_spec, collections.abc.MutableMapping): self._observation_is_dict = True invalid_keys = set(wrapped_observation_spec.keys()) else: raise ValueError('Unsupported observation spec structure.') if not pixels_only and observation_key in invalid_keys: raise ValueError('Duplicate or reserved observation key {!r}.' .format(observation_key)) if pixels_only: self._observation_spec = collections.OrderedDict() elif self._observation_is_dict: self._observation_spec = wrapped_observation_spec.copy() else: self._observation_spec = collections.OrderedDict() self._observation_spec[STATE_KEY] = wrapped_observation_spec # Extend observation spec. pixels = env.physics.render(**render_kwargs) pixels_spec = specs.Array( shape=pixels.shape, dtype=pixels.dtype, name=observation_key) self._observation_spec[observation_key] = pixels_spec self._env = env self._pixels_only = pixels_only self._render_kwargs = render_kwargs self._observation_key = observation_key def reset(self): time_step = self._env.reset() return self._add_pixel_observation(time_step) def step(self, action): time_step = self._env.step(action) return self._add_pixel_observation(time_step) def observation_spec(self): return self._observation_spec def action_spec(self): return self._env.action_spec() def _add_pixel_observation(self, time_step): if self._pixels_only: observation = collections.OrderedDict() elif self._observation_is_dict: observation = type(time_step.observation)(time_step.observation) else: observation = collections.OrderedDict() observation[STATE_KEY] = time_step.observation pixels = self._env.physics.render(**self._render_kwargs) observation[self._observation_key] = pixels return time_step._replace(observation=observation) def __getattr__(self, name): return getattr(self._env, name)
dm_control-main
dm_control/suite/wrappers/pixels.py
# Copyright 2019 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for the mujoco_profiling wrapper.""" import collections from absl.testing import absltest from dm_control.suite import cartpole from dm_control.suite.wrappers import mujoco_profiling import numpy as np class MujocoProfilingTest(absltest.TestCase): def test_dict_observation(self): obs_key = 'mjprofile' env = cartpole.swingup() # Make sure we are testing the right environment for the test. observation_spec = env.observation_spec() self.assertIsInstance(observation_spec, collections.OrderedDict) # The wrapper should only add one observation. wrapped = mujoco_profiling.Wrapper(env, observation_key=obs_key) wrapped_observation_spec = wrapped.observation_spec() self.assertIsInstance(wrapped_observation_spec, collections.OrderedDict) expected_length = len(observation_spec) + 1 self.assertLen(wrapped_observation_spec, expected_length) expected_keys = list(observation_spec.keys()) + [obs_key] self.assertEqual(expected_keys, list(wrapped_observation_spec.keys())) # Check that the added spec item is consistent with the added observation. time_step = wrapped.reset() profile_observation = time_step.observation[obs_key] wrapped_observation_spec[obs_key].validate(profile_observation) self.assertEqual(profile_observation.shape, (2,)) self.assertEqual(profile_observation.dtype, np.double) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/suite/wrappers/mujoco_profiling_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. # ============================================================================ """Environment wrappers used to extend or modify environment behaviour."""
dm_control-main
dm_control/suite/wrappers/__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 the action scale wrapper.""" from absl.testing import absltest from absl.testing import parameterized from dm_control.rl import control from dm_control.suite.wrappers import action_scale from dm_env import specs import mock import numpy as np def make_action_spec(lower=(-1.,), upper=(1.,)): lower, upper = np.broadcast_arrays(lower, upper) return specs.BoundedArray( shape=lower.shape, dtype=float, minimum=lower, maximum=upper) def make_mock_env(action_spec): env = mock.Mock(spec=control.Environment) env.action_spec.return_value = action_spec return env class ActionScaleTest(parameterized.TestCase): def assertStepCalledOnceWithCorrectAction(self, env, expected_action): # NB: `assert_called_once_with()` doesn't support numpy arrays. env.step.assert_called_once() actual_action = env.step.call_args_list[0][0][0] np.testing.assert_array_equal(expected_action, actual_action) @parameterized.parameters( { 'minimum': np.r_[-1., -1.], 'maximum': np.r_[1., 1.], 'scaled_minimum': np.r_[-2., -2.], 'scaled_maximum': np.r_[2., 2.], }, { 'minimum': np.r_[-2., -2.], 'maximum': np.r_[2., 2.], 'scaled_minimum': np.r_[-1., -1.], 'scaled_maximum': np.r_[1., 1.], }, { 'minimum': np.r_[-1., -1.], 'maximum': np.r_[1., 1.], 'scaled_minimum': np.r_[-2., -2.], 'scaled_maximum': np.r_[1., 1.], }, { 'minimum': np.r_[-1., -1.], 'maximum': np.r_[1., 1.], 'scaled_minimum': np.r_[-1., -1.], 'scaled_maximum': np.r_[2., 2.], }, ) def test_step(self, minimum, maximum, scaled_minimum, scaled_maximum): action_spec = make_action_spec(lower=minimum, upper=maximum) env = make_mock_env(action_spec=action_spec) wrapped_env = action_scale.Wrapper( env, minimum=scaled_minimum, maximum=scaled_maximum) time_step = wrapped_env.step(scaled_minimum) self.assertStepCalledOnceWithCorrectAction(env, minimum) self.assertIs(time_step, env.step(minimum)) env.reset_mock() time_step = wrapped_env.step(scaled_maximum) self.assertStepCalledOnceWithCorrectAction(env, maximum) self.assertIs(time_step, env.step(maximum)) @parameterized.parameters( { 'minimum': np.r_[-1., -1.], 'maximum': np.r_[1., 1.], }, { 'minimum': np.r_[0, 1], 'maximum': np.r_[2, 3], }, ) def test_correct_action_spec(self, minimum, maximum): original_action_spec = make_action_spec( lower=np.r_[-2., -2.], upper=np.r_[2., 2.]) env = make_mock_env(action_spec=original_action_spec) wrapped_env = action_scale.Wrapper(env, minimum=minimum, maximum=maximum) new_action_spec = wrapped_env.action_spec() np.testing.assert_array_equal(new_action_spec.minimum, minimum) np.testing.assert_array_equal(new_action_spec.maximum, maximum) @parameterized.parameters('reset', 'observation_spec', 'control_timestep') def test_method_delegated_to_underlying_env(self, method_name): env = make_mock_env(action_spec=make_action_spec()) wrapped_env = action_scale.Wrapper(env, minimum=0, maximum=1) env_method = getattr(env, method_name) wrapper_method = getattr(wrapped_env, method_name) out = wrapper_method() env_method.assert_called_once_with() self.assertIs(out, env_method()) def test_invalid_action_spec_type(self): action_spec = [make_action_spec()] * 2 env = make_mock_env(action_spec=action_spec) with self.assertRaisesWithLiteralMatch( ValueError, action_scale._ACTION_SPEC_MUST_BE_BOUNDED_ARRAY.format(action_spec)): action_scale.Wrapper(env, minimum=0, maximum=1) @parameterized.parameters( {'name': 'minimum', 'bounds': np.r_[np.nan]}, {'name': 'minimum', 'bounds': np.r_[-np.inf]}, {'name': 'maximum', 'bounds': np.r_[np.inf]}, ) def test_non_finite_bounds(self, name, bounds): kwargs = {'minimum': np.r_[-1.], 'maximum': np.r_[1.]} kwargs[name] = bounds env = make_mock_env(action_spec=make_action_spec()) with self.assertRaisesWithLiteralMatch( ValueError, action_scale._MUST_BE_FINITE.format(name=name, bounds=bounds)): action_scale.Wrapper(env, **kwargs) @parameterized.parameters( {'name': 'minimum', 'bounds': np.r_[1., 2., 3.]}, {'name': 'minimum', 'bounds': np.r_[[1.], [2.], [3.]]}, ) def test_invalid_bounds_shape(self, name, bounds): shape = (2,) kwargs = {'minimum': np.zeros(shape), 'maximum': np.ones(shape)} kwargs[name] = bounds action_spec = make_action_spec(lower=[-1, -1], upper=[2, 3]) env = make_mock_env(action_spec=action_spec) with self.assertRaisesWithLiteralMatch( ValueError, action_scale._MUST_BROADCAST.format( name=name, bounds=bounds, shape=shape)): action_scale.Wrapper(env, **kwargs) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/suite/wrappers/action_scale_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. # ============================================================================ """Wrapper control suite environments that adds Gaussian noise to actions.""" import dm_env import numpy as np _BOUNDS_MUST_BE_FINITE = ( 'All bounds in `env.action_spec()` must be finite, got: {action_spec}') class Wrapper(dm_env.Environment): """Wraps a control environment and adds Gaussian noise to actions.""" def __init__(self, env, scale=0.01): """Initializes a new action noise Wrapper. Args: env: The control suite environment to wrap. scale: The standard deviation of the noise, expressed as a fraction of the max-min range for each action dimension. Raises: ValueError: If any of the action dimensions of the wrapped environment are unbounded. """ action_spec = env.action_spec() if not (np.all(np.isfinite(action_spec.minimum)) and np.all(np.isfinite(action_spec.maximum))): raise ValueError(_BOUNDS_MUST_BE_FINITE.format(action_spec=action_spec)) self._minimum = action_spec.minimum self._maximum = action_spec.maximum self._noise_std = scale * (action_spec.maximum - action_spec.minimum) self._env = env def step(self, action): noisy_action = action + self._env.task.random.normal(scale=self._noise_std) # Clip the noisy actions in place so that they fall within the bounds # specified by the `action_spec`. Note that MuJoCo implicitly clips out-of- # bounds control inputs, but we also clip here in case the actions do not # correspond directly to MuJoCo actuators, or if there are other wrapper # layers that expect the actions to be within bounds. np.clip(noisy_action, self._minimum, self._maximum, out=noisy_action) return self._env.step(noisy_action) def reset(self): return self._env.reset() def observation_spec(self): return self._env.observation_spec() def action_spec(self): return self._env.action_spec() def __getattr__(self, name): return getattr(self._env, name)
dm_control-main
dm_control/suite/wrappers/action_noise.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for the pixel wrapper.""" import collections from absl.testing import absltest from absl.testing import parameterized from dm_control.suite import cartpole from dm_control.suite.wrappers import pixels import dm_env from dm_env import specs import numpy as np class FakePhysics: def render(self, *args, **kwargs): del args del kwargs return np.zeros((4, 5, 3), dtype=np.uint8) class FakeArrayObservationEnvironment(dm_env.Environment): def __init__(self): self.physics = FakePhysics() def reset(self): return dm_env.restart(np.zeros((2,))) def step(self, action): del action return dm_env.transition(0.0, np.zeros((2,))) def action_spec(self): pass def observation_spec(self): return specs.Array(shape=(2,), dtype=float) class PixelsTest(parameterized.TestCase): @parameterized.parameters(True, False) def test_dict_observation(self, pixels_only): pixel_key = 'rgb' env = cartpole.swingup() # Make sure we are testing the right environment for the test. observation_spec = env.observation_spec() self.assertIsInstance(observation_spec, collections.OrderedDict) width = 320 height = 240 # The wrapper should only add one observation. wrapped = pixels.Wrapper(env, observation_key=pixel_key, pixels_only=pixels_only, render_kwargs={'width': width, 'height': height}) wrapped_observation_spec = wrapped.observation_spec() self.assertIsInstance(wrapped_observation_spec, collections.OrderedDict) if pixels_only: self.assertLen(wrapped_observation_spec, 1) self.assertEqual([pixel_key], list(wrapped_observation_spec.keys())) else: expected_length = len(observation_spec) + 1 self.assertLen(wrapped_observation_spec, expected_length) expected_keys = list(observation_spec.keys()) + [pixel_key] self.assertEqual(expected_keys, list(wrapped_observation_spec.keys())) # Check that the added spec item is consistent with the added observation. time_step = wrapped.reset() rgb_observation = time_step.observation[pixel_key] wrapped_observation_spec[pixel_key].validate(rgb_observation) self.assertEqual(rgb_observation.shape, (height, width, 3)) self.assertEqual(rgb_observation.dtype, np.uint8) @parameterized.parameters(True, False) def test_single_array_observation(self, pixels_only): pixel_key = 'depth' env = FakeArrayObservationEnvironment() observation_spec = env.observation_spec() self.assertIsInstance(observation_spec, specs.Array) wrapped = pixels.Wrapper(env, observation_key=pixel_key, pixels_only=pixels_only) wrapped_observation_spec = wrapped.observation_spec() self.assertIsInstance(wrapped_observation_spec, collections.OrderedDict) if pixels_only: self.assertLen(wrapped_observation_spec, 1) self.assertEqual([pixel_key], list(wrapped_observation_spec.keys())) else: self.assertLen(wrapped_observation_spec, 2) self.assertEqual([pixels.STATE_KEY, pixel_key], list(wrapped_observation_spec.keys())) time_step = wrapped.reset() depth_observation = time_step.observation[pixel_key] wrapped_observation_spec[pixel_key].validate(depth_observation) self.assertEqual(depth_observation.shape, (4, 5, 3)) self.assertEqual(depth_observation.dtype, np.uint8) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/suite/wrappers/pixels_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. # ============================================================================ """Wrapper that scales actions to a specific range.""" import dm_env from dm_env import specs import numpy as np _ACTION_SPEC_MUST_BE_BOUNDED_ARRAY = ( "`env.action_spec()` must return a single `BoundedArray`, got: {}.") _MUST_BE_FINITE = "All values in `{name}` must be finite, got: {bounds}." _MUST_BROADCAST = ( "`{name}` must be broadcastable to shape {shape}, got: {bounds}.") class Wrapper(dm_env.Environment): """Wraps a control environment to rescale actions to a specific range.""" __slots__ = ("_action_spec", "_env", "_transform") def __init__(self, env, minimum, maximum): """Initializes a new action scale Wrapper. Args: env: Instance of `dm_env.Environment` to wrap. Its `action_spec` must consist of a single `BoundedArray` with all-finite bounds. minimum: Scalar or array-like specifying element-wise lower bounds (inclusive) for the `action_spec` of the wrapped environment. Must be finite and broadcastable to the shape of the `action_spec`. maximum: Scalar or array-like specifying element-wise upper bounds (inclusive) for the `action_spec` of the wrapped environment. Must be finite and broadcastable to the shape of the `action_spec`. Raises: ValueError: If `env.action_spec()` is not a single `BoundedArray`. ValueError: If `env.action_spec()` has non-finite bounds. ValueError: If `minimum` or `maximum` contain non-finite values. ValueError: If `minimum` or `maximum` are not broadcastable to `env.action_spec().shape`. """ action_spec = env.action_spec() if not isinstance(action_spec, specs.BoundedArray): raise ValueError(_ACTION_SPEC_MUST_BE_BOUNDED_ARRAY.format(action_spec)) minimum = np.array(minimum) maximum = np.array(maximum) shape = action_spec.shape orig_minimum = action_spec.minimum orig_maximum = action_spec.maximum orig_dtype = action_spec.dtype def validate(bounds, name): if not np.all(np.isfinite(bounds)): raise ValueError(_MUST_BE_FINITE.format(name=name, bounds=bounds)) try: np.broadcast_to(bounds, shape) except ValueError: raise ValueError(_MUST_BROADCAST.format( name=name, bounds=bounds, shape=shape)) validate(minimum, "minimum") validate(maximum, "maximum") validate(orig_minimum, "env.action_spec().minimum") validate(orig_maximum, "env.action_spec().maximum") scale = (orig_maximum - orig_minimum) / (maximum - minimum) def transform(action): new_action = orig_minimum + scale * (action - minimum) return new_action.astype(orig_dtype, copy=False) dtype = np.result_type(minimum, maximum, orig_dtype) self._action_spec = action_spec.replace( minimum=minimum, maximum=maximum, dtype=dtype) self._env = env self._transform = transform def step(self, action): return self._env.step(self._transform(action)) def reset(self): return self._env.reset() def observation_spec(self): return self._env.observation_spec() def action_spec(self): return self._action_spec def __getattr__(self, name): return getattr(self._env, name)
dm_control-main
dm_control/suite/wrappers/action_scale.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. # ============================================================================ """Parse and convert amc motion capture data.""" import collections from dm_control.mujoco import math as mjmath import numpy as np from scipy import interpolate MOCAP_DT = 1.0/120.0 CONVERSION_LENGTH = 0.056444 _CMU_MOCAP_JOINT_ORDER = ( 'root0', 'root1', 'root2', 'root3', 'root4', 'root5', 'lowerbackrx', 'lowerbackry', 'lowerbackrz', 'upperbackrx', 'upperbackry', 'upperbackrz', 'thoraxrx', 'thoraxry', 'thoraxrz', 'lowerneckrx', 'lowerneckry', 'lowerneckrz', 'upperneckrx', 'upperneckry', 'upperneckrz', 'headrx', 'headry', 'headrz', 'rclaviclery', 'rclaviclerz', 'rhumerusrx', 'rhumerusry', 'rhumerusrz', 'rradiusrx', 'rwristry', 'rhandrx', 'rhandrz', 'rfingersrx', 'rthumbrx', 'rthumbrz', 'lclaviclery', 'lclaviclerz', 'lhumerusrx', 'lhumerusry', 'lhumerusrz', 'lradiusrx', 'lwristry', 'lhandrx', 'lhandrz', 'lfingersrx', 'lthumbrx', 'lthumbrz', 'rfemurrx', 'rfemurry', 'rfemurrz', 'rtibiarx', 'rfootrx', 'rfootrz', 'rtoesrx', 'lfemurrx', 'lfemurry', 'lfemurrz', 'ltibiarx', 'lfootrx', 'lfootrz', 'ltoesrx' ) Converted = collections.namedtuple('Converted', ['qpos', 'qvel', 'time']) def convert(file_name, physics, timestep): """Converts the parsed .amc values into qpos and qvel values and resamples. Args: file_name: The .amc file to be parsed and converted. physics: The corresponding physics instance. timestep: Desired output interval between resampled frames. Returns: A namedtuple with fields: `qpos`, a numpy array containing converted positional variables. `qvel`, a numpy array containing converted velocity variables. `time`, a numpy array containing the corresponding times. """ frame_values = parse(file_name) joint2index = {} for name in physics.named.data.qpos.axes.row.names: joint2index[name] = physics.named.data.qpos.axes.row.convert_key_item(name) index2joint = {} for joint, index in joint2index.items(): if isinstance(index, slice): indices = range(index.start, index.stop) else: indices = [index] for ii in indices: index2joint[ii] = joint # Convert frame_values to qpos amcvals2qpos_transformer = Amcvals2qpos(index2joint, _CMU_MOCAP_JOINT_ORDER) qpos_values = [] for frame_value in frame_values: qpos_values.append(amcvals2qpos_transformer(frame_value)) qpos_values = np.stack(qpos_values) # Time by nq # Interpolate/resample. # Note: interpolate quaternions rather than euler angles (slerp). # see https://en.wikipedia.org/wiki/Slerp qpos_values_resampled = [] time_vals = np.arange(0, len(frame_values)*MOCAP_DT - 1e-8, MOCAP_DT) time_vals_new = np.arange(0, len(frame_values)*MOCAP_DT, timestep) while time_vals_new[-1] > time_vals[-1]: time_vals_new = time_vals_new[:-1] for i in range(qpos_values.shape[1]): f = interpolate.splrep(time_vals, qpos_values[:, i]) qpos_values_resampled.append(interpolate.splev(time_vals_new, f)) qpos_values_resampled = np.stack(qpos_values_resampled) # nq by ntime qvel_list = [] for t in range(qpos_values_resampled.shape[1]-1): p_tp1 = qpos_values_resampled[:, t + 1] p_t = qpos_values_resampled[:, t] qvel = [(p_tp1[:3]-p_t[:3])/ timestep, mjmath.mj_quat2vel( mjmath.mj_quatdiff(p_t[3:7], p_tp1[3:7]), timestep), (p_tp1[7:]-p_t[7:])/ timestep] qvel_list.append(np.concatenate(qvel)) qvel_values_resampled = np.vstack(qvel_list).T return Converted(qpos_values_resampled, qvel_values_resampled, time_vals_new) def parse(file_name): """Parses the amc file format.""" values = [] fid = open(file_name, 'r') line = fid.readline().strip() frame_ind = 1 first_frame = True while True: # Parse first frame. if first_frame and line[0] == str(frame_ind): first_frame = False frame_ind += 1 frame_vals = [] while True: line = fid.readline().strip() if not line or line == str(frame_ind): values.append(np.array(frame_vals, dtype=float)) break tokens = line.split() frame_vals.extend(tokens[1:]) # Parse other frames. elif line == str(frame_ind): frame_ind += 1 frame_vals = [] while True: line = fid.readline().strip() if not line or line == str(frame_ind): values.append(np.array(frame_vals, dtype=float)) break tokens = line.split() frame_vals.extend(tokens[1:]) else: line = fid.readline().strip() if not line: break return values class Amcvals2qpos: """Callable that converts .amc values for a frame and to MuJoCo qpos format. """ def __init__(self, index2joint, joint_order): """Initializes a new Amcvals2qpos instance. Args: index2joint: List of joint angles in .amc file. joint_order: List of joint names in MuJoco MJCF. """ # Root is x,y,z, then quat. # need to get indices of qpos that order for amc default order self.qpos_root_xyz_ind = [0, 1, 2] self.root_xyz_ransform = np.array( [[1, 0, 0], [0, 0, -1], [0, 1, 0]]) * CONVERSION_LENGTH self.qpos_root_quat_ind = [3, 4, 5, 6] amc2qpos_transform = np.zeros((len(index2joint), len(joint_order))) for i in range(len(index2joint)): for j in range(len(joint_order)): if index2joint[i] == joint_order[j]: if 'rx' in index2joint[i]: amc2qpos_transform[i][j] = 1 elif 'ry' in index2joint[i]: amc2qpos_transform[i][j] = 1 elif 'rz' in index2joint[i]: amc2qpos_transform[i][j] = 1 self.amc2qpos_transform = amc2qpos_transform def __call__(self, amc_val): """Converts a `.amc` frame to MuJoCo qpos format.""" amc_val_rad = np.deg2rad(amc_val) qpos = np.dot(self.amc2qpos_transform, amc_val_rad) # Root. qpos[:3] = np.dot(self.root_xyz_ransform, amc_val[:3]) qpos_quat = mjmath.euler2quat(amc_val[3], amc_val[4], amc_val[5]) qpos_quat = mjmath.mj_quatprod(mjmath.euler2quat(90, 0, 0), qpos_quat) for i, ind in enumerate(self.qpos_root_quat_ind): qpos[ind] = qpos_quat[i] return qpos
dm_control-main
dm_control/suite/utils/parse_amc.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for parse_amc utility.""" import os from absl.testing import absltest from dm_control.suite import humanoid_CMU from dm_control.suite.utils import parse_amc from dm_control.utils import io as resources _TEST_AMC_PATH = resources.GetResourceFilename( os.path.join(os.path.dirname(__file__), '../demos/zeros.amc')) class ParseAMCTest(absltest.TestCase): def test_sizes_of_parsed_data(self): # Instantiate the humanoid environment. env = humanoid_CMU.stand() # Parse and convert specified clip. converted = parse_amc.convert( _TEST_AMC_PATH, env.physics, env.control_timestep()) self.assertEqual(converted.qpos.shape[0], 63) self.assertEqual(converted.qvel.shape[0], 62) self.assertEqual(converted.time.shape[0], converted.qpos.shape[1]) self.assertEqual(converted.qpos.shape[1], converted.qvel.shape[1] + 1) # Parse and convert specified clip -- WITH SMALLER TIMESTEP converted2 = parse_amc.convert( _TEST_AMC_PATH, env.physics, 0.5 * env.control_timestep()) self.assertEqual(converted2.qpos.shape[0], 63) self.assertEqual(converted2.qvel.shape[0], 62) self.assertEqual(converted2.time.shape[0], converted2.qpos.shape[1]) self.assertEqual(converted.qpos.shape[1], converted.qvel.shape[1] + 1) # Compare sizes of parsed objects for different timesteps self.assertEqual(converted.qpos.shape[1] * 2, converted2.qpos.shape[1]) if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/suite/utils/parse_amc_test.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Randomization functions.""" from dm_control.mujoco.wrapper import mjbindings import numpy as np def random_limited_quaternion(random, limit): """Generates a random quaternion limited to the specified rotations.""" axis = random.randn(3) axis /= np.linalg.norm(axis) angle = random.rand() * limit quaternion = np.zeros(4) mjbindings.mjlib.mju_axisAngle2Quat(quaternion, axis, angle) return quaternion def randomize_limited_and_rotational_joints(physics, random=None): """Randomizes the positions of joints defined in the physics body. The following randomization rules apply: - Bounded joints (hinges or sliders) are sampled uniformly in the bounds. - Unbounded hinges are samples uniformly in [-pi, pi] - Quaternions for unlimited free joints and ball joints are sampled uniformly on the unit 3-sphere. - Quaternions for limited ball joints are sampled uniformly on a sector of the unit 3-sphere. - The linear degrees of freedom of free joints are not randomized. Args: physics: Instance of 'Physics' class that holds a loaded model. random: Optional instance of 'np.random.RandomState'. Defaults to the global NumPy random state. """ random = random or np.random hinge = mjbindings.enums.mjtJoint.mjJNT_HINGE slide = mjbindings.enums.mjtJoint.mjJNT_SLIDE ball = mjbindings.enums.mjtJoint.mjJNT_BALL free = mjbindings.enums.mjtJoint.mjJNT_FREE qpos = physics.named.data.qpos for joint_id in range(physics.model.njnt): joint_name = physics.model.id2name(joint_id, 'joint') joint_type = physics.model.jnt_type[joint_id] is_limited = physics.model.jnt_limited[joint_id] range_min, range_max = physics.model.jnt_range[joint_id] if is_limited: if joint_type == hinge or joint_type == slide: qpos[joint_name] = random.uniform(range_min, range_max) elif joint_type == ball: qpos[joint_name] = random_limited_quaternion(random, range_max) else: if joint_type == hinge: qpos[joint_name] = random.uniform(-np.pi, np.pi) elif joint_type == ball: quat = random.randn(4) quat /= np.linalg.norm(quat) qpos[joint_name] = quat elif joint_type == free: # this should be random.randn, but changing it now could significantly # affect benchmark results. quat = random.rand(4) quat /= np.linalg.norm(quat) qpos[joint_name][3:] = quat
dm_control-main
dm_control/suite/utils/randomizers.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. # ============================================================================ """Utility functions used in the control suite."""
dm_control-main
dm_control/suite/utils/__init__.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for randomizers.py.""" from absl.testing import absltest from absl.testing import parameterized from dm_control import mujoco from dm_control.mujoco.wrapper import mjbindings from dm_control.suite.utils import randomizers import numpy as np mjlib = mjbindings.mjlib class RandomizeUnlimitedJointsTest(parameterized.TestCase): def setUp(self): super().setUp() self.rand = np.random.RandomState(100) def test_single_joint_of_each_type(self): physics = mujoco.Physics.from_xml_string("""<mujoco> <default> <joint range="0 90" /> </default> <worldbody> <body> <geom type="box" size="1 1 1"/> <joint name="free" type="free"/> </body> <body> <geom type="box" size="1 1 1"/> <joint name="limited_hinge" type="hinge" limited="true"/> <joint name="slide" type="slide" limited="false"/> <joint name="limited_slide" type="slide" limited="true"/> <joint name="hinge" type="hinge" limited="false"/> </body> <body> <geom type="box" size="1 1 1"/> <joint name="ball" type="ball" limited="false"/> </body> <body> <geom type="box" size="1 1 1"/> <joint name="limited_ball" type="ball" limited="true"/> </body> </worldbody> </mujoco>""") randomizers.randomize_limited_and_rotational_joints(physics, self.rand) self.assertNotEqual(0., physics.named.data.qpos['hinge']) self.assertNotEqual(0., physics.named.data.qpos['limited_hinge']) self.assertNotEqual(0., physics.named.data.qpos['limited_slide']) self.assertNotEqual(0., np.sum(physics.named.data.qpos['ball'])) self.assertNotEqual(0., np.sum(physics.named.data.qpos['limited_ball'])) self.assertNotEqual(0., np.sum(physics.named.data.qpos['free'][3:])) # Unlimited slide and the positional part of the free joint remains # uninitialized. self.assertEqual(0., physics.named.data.qpos['slide']) self.assertEqual(0., np.sum(physics.named.data.qpos['free'][:3])) def test_multiple_joints_of_same_type(self): physics = mujoco.Physics.from_xml_string("""<mujoco> <worldbody> <body> <geom type="box" size="1 1 1"/> <joint name="hinge_1" type="hinge"/> <joint name="hinge_2" type="hinge"/> <joint name="hinge_3" type="hinge"/> </body> </worldbody> </mujoco>""") randomizers.randomize_limited_and_rotational_joints(physics, self.rand) self.assertNotEqual(0., physics.named.data.qpos['hinge_1']) self.assertNotEqual(0., physics.named.data.qpos['hinge_2']) self.assertNotEqual(0., physics.named.data.qpos['hinge_3']) self.assertNotEqual(physics.named.data.qpos['hinge_1'], physics.named.data.qpos['hinge_2']) self.assertNotEqual(physics.named.data.qpos['hinge_2'], physics.named.data.qpos['hinge_3']) self.assertNotEqual(physics.named.data.qpos['hinge_1'], physics.named.data.qpos['hinge_3']) def test_unlimited_hinge_randomization_range(self): physics = mujoco.Physics.from_xml_string("""<mujoco> <worldbody> <body> <geom type="box" size="1 1 1"/> <joint name="hinge" type="hinge"/> </body> </worldbody> </mujoco>""") for _ in range(10): randomizers.randomize_limited_and_rotational_joints(physics, self.rand) self.assertBetween(physics.named.data.qpos['hinge'], -np.pi, np.pi) def test_limited_1d_joint_limits_are_respected(self): physics = mujoco.Physics.from_xml_string("""<mujoco> <default> <joint limited="true"/> </default> <worldbody> <body> <geom type="box" size="1 1 1"/> <joint name="hinge" type="hinge" range="0 10"/> <joint name="slide" type="slide" range="30 50"/> </body> </worldbody> </mujoco>""") for _ in range(10): randomizers.randomize_limited_and_rotational_joints(physics, self.rand) self.assertBetween(physics.named.data.qpos['hinge'], np.deg2rad(0), np.deg2rad(10)) self.assertBetween(physics.named.data.qpos['slide'], 30, 50) def test_limited_ball_joint_are_respected(self): physics = mujoco.Physics.from_xml_string("""<mujoco> <worldbody> <body name="body" zaxis="1 0 0"> <geom type="box" size="1 1 1"/> <joint name="ball" type="ball" limited="true" range="0 60"/> </body> </worldbody> </mujoco>""") body_axis = np.array([1., 0., 0.]) joint_axis = np.zeros(3) for _ in range(10): randomizers.randomize_limited_and_rotational_joints(physics, self.rand) quat = physics.named.data.qpos['ball'] mjlib.mju_rotVecQuat(joint_axis, body_axis, quat) angle_cos = np.dot(body_axis, joint_axis) self.assertGreater(angle_cos, 0.5) # cos(60) = 0.5 if __name__ == '__main__': absltest.main()
dm_control-main
dm_control/suite/utils/randomizers_test.py
# Copyright 2017 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Functions to manage the common assets for domains.""" import os from dm_control.utils import io as resources _SUITE_DIR = os.path.dirname(os.path.dirname(__file__)) _FILENAMES = [ "./common/materials.xml", "./common/skybox.xml", "./common/visual.xml", ] ASSETS = {filename: resources.GetResource(os.path.join(_SUITE_DIR, filename)) for filename in _FILENAMES} def read_model(model_filename): """Reads a model XML file and returns its contents as a string.""" return resources.GetResource(os.path.join(_SUITE_DIR, model_filename))
dm_control-main
dm_control/suite/common/__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. # ============================================================================ """Demonstration of amc parsing for CMU mocap database. To run the demo, supply a path to a `.amc` file: python mocap_demo --filename='path/to/mocap.amc' CMU motion capture clips are available at mocap.cs.cmu.edu """ import time from absl import app from absl import flags from dm_control.suite import humanoid_CMU from dm_control.suite.utils import parse_amc import matplotlib.pyplot as plt import numpy as np FLAGS = flags.FLAGS flags.DEFINE_string('filename', None, 'amc file to be converted.') flags.DEFINE_integer('max_num_frames', 90, 'Maximum number of frames for plotting/playback') def main(unused_argv): env = humanoid_CMU.stand() # Parse and convert specified clip. converted = parse_amc.convert(FLAGS.filename, env.physics, env.control_timestep()) max_frame = min(FLAGS.max_num_frames, converted.qpos.shape[1] - 1) width = 480 height = 480 video = np.zeros((max_frame, height, 2 * width, 3), dtype=np.uint8) for i in range(max_frame): p_i = converted.qpos[:, i] with env.physics.reset_context(): env.physics.data.qpos[:] = p_i video[i] = np.hstack([env.physics.render(height, width, camera_id=0), env.physics.render(height, width, camera_id=1)]) tic = time.time() for i in range(max_frame): if i == 0: img = plt.imshow(video[i]) else: img.set_data(video[i]) toc = time.time() clock_dt = toc - tic tic = time.time() # Real-time playback not always possible as clock_dt > .03 plt.pause(max(0.01, 0.03 - clock_dt)) # Need min display time > 0.0. plt.draw() plt.waitforbuttonpress() if __name__ == '__main__': flags.mark_flag_as_required('filename') app.run(main)
dm_control-main
dm_control/suite/demos/mocap_demo.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. # ============================================================================ """A dm_env.Environment subclass for control-specific environments.""" import abc import collections import contextlib import dm_env from dm_env import specs import numpy as np FLAT_OBSERVATION_KEY = 'observations' class Environment(dm_env.Environment): """Class for physics-based reinforcement learning environments.""" def __init__(self, physics, task, time_limit=float('inf'), control_timestep=None, n_sub_steps=None, flat_observation=False, legacy_step: bool = True): """Initializes a new `Environment`. Args: physics: Instance of `Physics`. task: Instance of `Task`. time_limit: Optional `int`, maximum time for each episode in seconds. By default this is set to infinite. control_timestep: Optional control time-step, in seconds. n_sub_steps: Optional number of physical time-steps in one control time-step, aka "action repeats". Can only be supplied if `control_timestep` is not specified. flat_observation: If True, observations will be flattened and concatenated into a single numpy array. legacy_step: If True, steps the state with up-to-date position and velocity dependent fields. See Page 6 of https://arxiv.org/abs/2006.12983 for more information. Raises: ValueError: If both `n_sub_steps` and `control_timestep` are supplied. """ self._task = task self._physics = physics self._physics.legacy_step = legacy_step self._flat_observation = flat_observation if n_sub_steps is not None and control_timestep is not None: raise ValueError('Both n_sub_steps and control_timestep were supplied.') elif n_sub_steps is not None: self._n_sub_steps = n_sub_steps elif control_timestep is not None: self._n_sub_steps = compute_n_steps(control_timestep, self._physics.timestep()) else: self._n_sub_steps = 1 if time_limit == float('inf'): self._step_limit = float('inf') else: self._step_limit = time_limit / ( self._physics.timestep() * self._n_sub_steps) self._step_count = 0 self._reset_next_step = True def reset(self): """Starts a new episode and returns the first `TimeStep`.""" self._reset_next_step = False self._step_count = 0 with self._physics.reset_context(): self._task.initialize_episode(self._physics) observation = self._task.get_observation(self._physics) if self._flat_observation: observation = flatten_observation(observation) return dm_env.TimeStep( step_type=dm_env.StepType.FIRST, reward=None, discount=None, observation=observation) def step(self, action): """Updates the environment using the action and returns a `TimeStep`.""" if self._reset_next_step: return self.reset() self._task.before_step(action, self._physics) self._physics.step(self._n_sub_steps) self._task.after_step(self._physics) reward = self._task.get_reward(self._physics) observation = self._task.get_observation(self._physics) if self._flat_observation: observation = flatten_observation(observation) self._step_count += 1 if self._step_count >= self._step_limit: discount = 1.0 else: discount = self._task.get_termination(self._physics) episode_over = discount is not None if episode_over: self._reset_next_step = True return dm_env.TimeStep( dm_env.StepType.LAST, reward, discount, observation) else: return dm_env.TimeStep(dm_env.StepType.MID, reward, 1.0, observation) def action_spec(self): """Returns the action specification for this environment.""" return self._task.action_spec(self._physics) def step_spec(self): """May return a specification for the values returned by `step`.""" return self._task.step_spec(self._physics) def observation_spec(self): """Returns the observation specification for this environment. Infers the spec from the observation, unless the Task implements the `observation_spec` method. Returns: An dict mapping observation name to `ArraySpec` containing observation shape and dtype. """ try: return self._task.observation_spec(self._physics) except NotImplementedError: observation = self._task.get_observation(self._physics) if self._flat_observation: observation = flatten_observation(observation) return _spec_from_observation(observation) @property def physics(self): return self._physics @property def task(self): return self._task def control_timestep(self): """Returns the interval between agent actions in seconds.""" return self.physics.timestep() * self._n_sub_steps def compute_n_steps(control_timestep, physics_timestep, tolerance=1e-8): """Returns the number of physics timesteps in a single control timestep. Args: control_timestep: Control time-step, should be an integer multiple of the physics timestep. physics_timestep: The time-step of the physics simulation. tolerance: Optional tolerance value for checking if `physics_timestep` divides `control_timestep`. Returns: The number of physics timesteps in a single control timestep. Raises: ValueError: If `control_timestep` is smaller than `physics_timestep` or if `control_timestep` is not an integer multiple of `physics_timestep`. """ if control_timestep < physics_timestep: raise ValueError( 'Control timestep ({}) cannot be smaller than physics timestep ({}).'. format(control_timestep, physics_timestep)) if abs((control_timestep / physics_timestep - round( control_timestep / physics_timestep))) > tolerance: raise ValueError( 'Control timestep ({}) must be an integer multiple of physics timestep ' '({})'.format(control_timestep, physics_timestep)) return int(round(control_timestep / physics_timestep)) def _spec_from_observation(observation): result = collections.OrderedDict() for key, value in observation.items(): result[key] = specs.Array(value.shape, value.dtype, name=key) return result # Base class definitions for objects supplied to Environment. class Physics(metaclass=abc.ABCMeta): """Simulates a physical environment.""" legacy_step: bool = True @abc.abstractmethod def step(self, n_sub_steps=1): """Updates the simulation state. Args: n_sub_steps: Optional number of times to repeatedly update the simulation state. Defaults to 1. """ @abc.abstractmethod def time(self): """Returns the elapsed simulation time in seconds.""" @abc.abstractmethod def timestep(self): """Returns the simulation timestep.""" def set_control(self, control): """Sets the control signal for the actuators.""" raise NotImplementedError('set_control is not supported.') @contextlib.contextmanager def reset_context(self): """Context manager for resetting the simulation state. Sets the internal simulation to a default state when entering the block. ```python with physics.reset_context(): # Set joint and object positions. physics.step() ``` Yields: The `Physics` instance. """ try: self.reset() except PhysicsError: pass yield self self.after_reset() @abc.abstractmethod def reset(self): """Resets internal variables of the physics simulation.""" @abc.abstractmethod def after_reset(self): """Runs after resetting internal variables of the physics simulation.""" def check_divergence(self): """Raises a `PhysicsError` if the simulation state is divergent. The default implementation is a no-op. """ class PhysicsError(RuntimeError): """Raised if the state of the physics simulation becomes divergent.""" class Task(metaclass=abc.ABCMeta): """Defines a task in a `control.Environment`.""" @abc.abstractmethod def initialize_episode(self, physics): """Sets the state of the environment at the start of each episode. Called by `control.Environment` at the start of each episode *within* `physics.reset_context()` (see the documentation for `base.Physics`). Args: physics: Instance of `Physics`. """ @abc.abstractmethod def before_step(self, action, physics): """Updates the task from the provided action. Called by `control.Environment` before stepping the physics engine. Args: action: numpy array or array-like action values, or a nested structure of such arrays. Should conform to the specification returned by `self.action_spec(physics)`. physics: Instance of `Physics`. """ def after_step(self, physics): """Optional method to update the task after the physics engine has stepped. Called by `control.Environment` after stepping the physics engine and before `control.Environment` calls `get_observation, `get_reward` and `get_termination`. The default implementation is a no-op. Args: physics: Instance of `Physics`. """ @abc.abstractmethod def action_spec(self, physics): """Returns a specification describing the valid actions for this task. Args: physics: Instance of `Physics`. Returns: A `BoundedArraySpec`, or a nested structure containing `BoundedArraySpec`s that describe the shapes, dtypes and elementwise lower and upper bounds for the action array(s) passed to `self.step`. """ def step_spec(self, physics): """Returns a specification describing the time_step for this task. Args: physics: Instance of `Physics`. Returns: A `BoundedArraySpec`, or a nested structure containing `BoundedArraySpec`s that describe the shapes, dtypes and elementwise lower and upper bounds for the array(s) returned by `self.step`. """ raise NotImplementedError() @abc.abstractmethod def get_observation(self, physics): """Returns an observation from the environment. Args: physics: Instance of `Physics`. """ @abc.abstractmethod def get_reward(self, physics): """Returns a reward from the environment. Args: physics: Instance of `Physics`. """ def get_termination(self, physics): """If the episode should end, returns a final discount, otherwise None.""" def observation_spec(self, physics): """Optional method that returns the observation spec. If not implemented, the Environment infers the spec from the observation. Args: physics: Instance of `Physics`. Returns: A dict mapping observation name to `ArraySpec` containing observation shape and dtype. """ raise NotImplementedError() def flatten_observation(observation, output_key=FLAT_OBSERVATION_KEY): """Flattens multiple observation arrays into a single numpy array. Args: observation: A mutable mapping from observation names to numpy arrays. output_key: The key for the flattened observation array in the output. Returns: A mutable mapping of the same type as `observation`. This will contain a single key-value pair consisting of `output_key` and the flattened and concatenated observation array. Raises: ValueError: If `observation` is not a `collections.abc.MutableMapping`. """ if not isinstance(observation, collections.abc.MutableMapping): raise ValueError('Can only flatten dict-like observations.') if isinstance(observation, collections.OrderedDict): keys = observation.keys() else: # Keep a consistent ordering for other mappings. keys = sorted(observation.keys()) observation_arrays = [observation[key].ravel() for key in keys] return type(observation)([(output_key, np.concatenate(observation_arrays))])
dm_control-main
dm_control/rl/control.py