python_code
stringlengths
0
780k
repo_name
stringlengths
7
38
file_path
stringlengths
5
103
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """Module for defining a Cond Option for basic control flow.""" from typing import Optional, Text, Callable, Iterable, Set import dm_env from dm_robotics.agentflow import core from dm_robotics.agentflow.decorators import overrides from dm_robotics.agentflow.options import basic_options class Cond(basic_options.DelegateOption): """An option which branches on a condition to one of two delegates. The condition can be evaluated on option-selection or every timestep. """ def __init__(self, cond: Callable[[dm_env.TimeStep, Optional[core.OptionResult]], bool], true_branch: core.Option, false_branch: core.Option, eval_every_step: bool = False, name: Optional[Text] = None) -> None: """Initialize Cond. Args: cond: A callable accepting the current timestep, and the result of the last option - if one exists. true_branch: The option to run if `cond` is True. false_branch: The option to run if `cond` is False. eval_every_step: If True evaluate `cond` and re-select every step. If False (default) `cond` is evaluated once when the option is selected. name: A name for this option. """ super().__init__(delegate=true_branch, name=name) assert callable(cond) self._cond = cond self._true_branch = true_branch self._false_branch = false_branch self._eval_every_step = eval_every_step self._options_selected: Set[core.Option] = set() self._just_switched = False def _maybe_other_branch(self) -> Optional[core.Option]: """Returns the non-active branch only if it has been selected previously.""" cur, tb, fb = self.delegate, self._true_branch, self._false_branch other_option = fb if cur is tb else tb if other_option in self._options_selected: return other_option else: return None def _select_option( self, timestep: dm_env.TimeStep, prev_option_result: Optional[core.OptionResult] = None) -> None: """Evaluates condition and activates the appropriate option.""" prev_option = self.delegate if self._cond(timestep, prev_option_result): self.delegate = self._true_branch else: self.delegate = self._false_branch # Keep track of which options have been selected for later termination. self._options_selected.add(self.delegate) self._just_switched = prev_option is not self.delegate def _switch_step_options(self, on_option: core.Option, off_option: core.Option, timestep: dm_env.TimeStep) -> None: """Last-step off_option and first-step on_option.""" # End old option. last_timestep = timestep._replace(step_type=dm_env.StepType.LAST) off_option.step(last_timestep) result = off_option.result(timestep) # Start new option. on_option.on_selected(timestep, result) def child_policies(self) -> Iterable[core.Policy]: return [self._true_branch, self._false_branch] @property def true_branch(self): return self._true_branch @property def false_branch(self): return self._false_branch @property def options_selected(self) -> Set[core.Option]: return self._options_selected @overrides(core.Option) def on_selected( self, timestep: dm_env.TimeStep, prev_option_result: Optional[core.OptionResult] = None) -> None: self._select_option(timestep, prev_option_result) return super().on_selected(timestep, prev_option_result) def step(self, timestep: dm_env.TimeStep): """Evaluates the condition if requested, and runs the selected option.""" if ( ((timestep.first() and not self._options_selected) or self._eval_every_step or not self._options_selected) and not timestep.last() # <-- Never switch options on a LAST step. ): # TODO(b/186731743): Test selecting an option for 1st time on a LAST step. self._select_option(timestep, None) if timestep.last(): # Clean up other branch if appropriate. other_branch = self._maybe_other_branch() if other_branch is not None: other_branch.step(timestep) # Re-initialized the set of option selected. self._options_selected: Set[core.Option] = set() if timestep.mid() and self._eval_every_step and self._just_switched: # Step through option lifecycle appropriately. other_branch = self._maybe_other_branch() if other_branch is not None: self._switch_step_options(self.delegate, other_branch, timestep) # Convert timestep to FIRST for stepping the newly-selected option. timestep = timestep._replace(step_type=dm_env.StepType.FIRST) # Step the active option. return super().step(timestep) @overrides(core.Option) def result(self, timestep: dm_env.TimeStep) -> core.OptionResult: return super().result(timestep)
dm_robotics-main
py/agentflow/meta_options/control_flow/cond.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """Module for defining a While Option for basic control flow.""" from typing import Callable, Optional, Text import dm_env from dm_robotics.agentflow import core from dm_robotics.agentflow import util from dm_robotics.agentflow.decorators import overrides from dm_robotics.agentflow.options import basic_options import numpy as np class While(basic_options.DelegateOption): """An option which runs until a condition is False.""" def __init__(self, cond: Callable[[dm_env.TimeStep], bool], delegate: core.Option, eval_every_step: bool = True, name: Optional[Text] = None) -> None: """Construct While Option. Per step `cond` will be called: * 0 times: if passed a LAST timestep (since the option is exiting anyway). * 0 times: if eval_every_step is False and the delegate doesn't terminate. * 1 time: if eval_every_step is False and the delegate terminates. * 1 time: if eval_every_step is True and the delegate doesn't terminate. * 2 times: if eval_every_step is True and the delegate terminates. Args: cond: A callable accepting the current timestep. delegate: The option to run while `cond` is True. eval_every_step: If True re-evaluate `cond` every step. If False `cond` is evaluated only upon each termination. See breakdown above. Note that the cond is not evaluated by pterm(), as this result is cached during step(). name: A name for this option. """ super().__init__(delegate=delegate, name=name) assert callable(cond) self._cond = cond self._eval_every_step = eval_every_step self._delegate_episode_ctr = 0 self._continue = None @property def delegate_episode_ctr(self): return self._delegate_episode_ctr @overrides(core.Option) def pterm(self, timestep: dm_env.TimeStep): """Terminates if `cond` is False.""" if self._continue is None: raise ValueError('pterm called before step') return 0.0 if self._continue else 1.0 @overrides(core.Option) def step(self, timestep: dm_env.TimeStep): """Evaluates the condition if requested, and runs the selected option.""" self._continue = True # Flag used in pterm (T, F, None (error state)) terminate_delegate = super().delegate.pterm(timestep) > np.random.rand() if terminate_delegate or self._eval_every_step: # Evaluate condition if delegate is terminal or asked to by user. self._continue = self._cond(timestep) terminate_loop = timestep.last() or not self._continue if terminate_delegate and not terminate_loop: # Terminate & restart delegate. last_timestep = timestep._replace(step_type=dm_env.StepType.LAST) last_action = self._delegate.step(last_timestep) self._delegate_episode_ctr += 1 self._continue = self._cond(timestep) if self._continue: # Only restart if cond is still True. This calls cond twice in a given # step, but is required in order to allow stateful conditions (e.g. # Repeat) to see the state after the delegate terminates. result = self._delegate.result(last_timestep) timestep = timestep._replace(step_type=dm_env.StepType.FIRST) self._delegate.on_selected(timestep, result) else: return last_action elif terminate_loop and not timestep.last(): timestep = timestep._replace(step_type=dm_env.StepType.LAST) util.log_termination_reason(self, self.result(timestep)) return super().step(timestep) class Repeat(While): """An option which runs for a given number of iterations.""" def __init__(self, num_iter: int, delegate: core.Option, name: Optional[Text] = None) -> None: """Construct Repeat Option. Args: num_iter: Number of times to repeat the option. delegate: The option to run for `num_iter` iterations. name: A name for this option. """ self._num_iter = num_iter cond = lambda _: self.delegate_episode_ctr < num_iter super().__init__( cond=cond, delegate=delegate, eval_every_step=False, name=name) @property def num_iters(self) -> int: return self._num_iter
dm_robotics-main
py/agentflow/meta_options/control_flow/loop_ops.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """Tests for dm_robotics.agentflow.meta_options.control_flow.cond.""" from typing import Any, List, Text from unittest import mock from absl.testing import absltest import dm_env from dm_robotics.agentflow import core from dm_robotics.agentflow import testing_functions from dm_robotics.agentflow.meta_options.control_flow import cond import numpy as np class CondOptionTest(absltest.TestCase): def _timestep(self, first=False, last=False, observation=None): step_type = dm_env.StepType.MID if first: step_type = dm_env.StepType.FIRST if last: step_type = dm_env.StepType.LAST if first and last: raise ValueError('FIRST and LAST not allowed') reward = 0 discount = np.random.random() observation = observation or {} return dm_env.TimeStep(step_type, reward, discount, observation) def _test_called_correct_delegate_method(self, cond_option, on_delegate, off_delegate, method_name, *args, **kwargs): initial_call_count = getattr(off_delegate, method_name).call_count getattr(cond_option, method_name)(*args, **kwargs) getattr(on_delegate, method_name).assert_called_with(*args, **kwargs) self.assertEqual( getattr(off_delegate, method_name).call_count, initial_call_count) def _test_delegation(self, option: cond.Cond, on_delegate: core.Option, off_delegate: core.Option, methods_to_test: List[Text], method_args: List[Any]): """Helper for testing that option calls the appropriate delegate. Args: option: The cond-option. on_delegate: The option that should be called. off_delegate: The option that shouldn't be called. methods_to_test: A list of strings naming methods to test. method_args: A list of args to pass, one list per entry in `methods_to_test` """ for i, method_name in enumerate(methods_to_test): self._test_called_correct_delegate_method(option, on_delegate, off_delegate, method_name, *method_args[i]) # Result is called on the delegate option to ensure proper forwarding to # the delegate. on_delegate_result = core.OptionResult( termination_reason=core.TerminationType.SUCCESS, data='random data') on_delegate.result.return_value = on_delegate_result timestep = mock.MagicMock() self.assertEqual(option.result(timestep), on_delegate_result) on_delegate.result.assert_called_with(timestep) self.assertEqual(off_delegate.result.call_count, 0) def test_cond_static(self): # Test whether Cond selects and properly delegates to proper branches for # one-time cond option1 = mock.MagicMock(spec=core.Option) option2 = mock.MagicMock(spec=core.Option) timestep = mock.MagicMock() previous_result = mock.MagicMock() methods_to_test = ['on_selected', 'pterm', 'step'] method_args = [[timestep, previous_result], [timestep], [timestep]] true_cond_option = cond.Cond(lambda timestep, _: True, option1, option2) self._test_delegation(true_cond_option, option1, option2, methods_to_test, method_args) option1.reset_mock() option2.reset_mock() false_cond_option = cond.Cond(lambda timestep, _: False, option1, option2) self._test_delegation(false_cond_option, option2, option1, methods_to_test, method_args) def test_cond_dynamic(self): # Test whether Cond selects and properly delegates to proper branches for # a dynamic cond which is evaluated every step, and cleans up properly. def assert_mock_step_type(mock_step, step_type): self.assertEqual(mock_step.call_args[0][0].step_type, step_type) class FlipFlopCond(object): """Simple callable that returns true once every `freq` calls.""" def __init__(self, freq: int): self._call_ctr = 0 self._freq = freq def __call__(self, timestep, result): res = self._call_ctr % self._freq == 0 if timestep.mid(): # don't increment during on_selected. self._call_ctr += 1 return res random_action_spec = testing_functions.random_array_spec(shape=(4,)) random_observation_spec = { 'doubles': testing_functions.random_array_spec(shape=(10,)) } # create options fixed_action1 = testing_functions.valid_value(random_action_spec) fixed_action2 = testing_functions.valid_value(random_action_spec) option1 = mock.MagicMock(spec=core.Option) option2 = mock.MagicMock(spec=core.Option) option1.step.return_value = fixed_action1 option2.step.return_value = fixed_action2 flip_flop_cond = FlipFlopCond(freq=3) cond_option = cond.Cond( flip_flop_cond, option1, option2, eval_every_step=True) first_timestep = self._timestep( first=True, observation=testing_functions.valid_value(random_observation_spec)) mid_timestep = self._timestep( observation=testing_functions.valid_value(random_observation_spec)) last_timestep = self._timestep( last=True, observation=testing_functions.valid_value(random_observation_spec)) # Select option1 (call_ctr 0->0). cond_option.on_selected(first_timestep) self.assertEqual(option1.on_selected.call_count, 1) self.assertEqual(option2.on_selected.call_count, 0) self.assertSetEqual(set([option1]), cond_option.options_selected) # Step 1; No switch (call_ctr 0->0). # Should first-step option1. cond_option.step(first_timestep) self.assertEqual(flip_flop_cond._call_ctr, 0) self.assertEqual(option1.on_selected.call_count, 1) self.assertEqual(option2.on_selected.call_count, 0) self.assertEqual(option1.step.call_count, 1) self.assertEqual(option2.step.call_count, 0) assert_mock_step_type(option1.step, dm_env.StepType.FIRST) self.assertSetEqual(set([option1]), cond_option.options_selected) # Step 2; No switch (call_ctr 0->1). # Should step option1 cond_option.step(mid_timestep) self.assertEqual(flip_flop_cond._call_ctr, 1) self.assertEqual(option1.on_selected.call_count, 1) self.assertEqual(option2.on_selected.call_count, 0) self.assertEqual(option1.step.call_count, 2) self.assertEqual(option2.step.call_count, 0) assert_mock_step_type(option1.step, dm_env.StepType.MID) self.assertSetEqual(set([option1]), cond_option.options_selected) # Step 3; Switch 1->2; (call_ctr 1->2) # Should term-step option1 and select + first-step option2. cond_option.step(mid_timestep) self.assertEqual(flip_flop_cond._call_ctr, 2) self.assertEqual(option1.on_selected.call_count, 1) self.assertEqual(option2.on_selected.call_count, 1) self.assertEqual(option1.step.call_count, 3) self.assertEqual(option2.step.call_count, 1) assert_mock_step_type(option1.step, dm_env.StepType.LAST) assert_mock_step_type(option2.step, dm_env.StepType.FIRST) self.assertSetEqual(set([option1, option2]), cond_option.options_selected) # Step 4; No switch; (call_ctr 2->3) # Should step option2. cond_option.step(mid_timestep) self.assertEqual(flip_flop_cond._call_ctr, 3) self.assertEqual(option1.on_selected.call_count, 1) self.assertEqual(option2.on_selected.call_count, 1) self.assertEqual(option1.step.call_count, 3) self.assertEqual(option2.step.call_count, 2) assert_mock_step_type(option2.step, dm_env.StepType.MID) self.assertSetEqual(set([option1, option2]), cond_option.options_selected) # Step 5; Switch 2->1; (call_ctr 3->4) # Should term-step option2 and select + first-step option1. cond_option.step(mid_timestep) self.assertEqual(flip_flop_cond._call_ctr, 4) self.assertEqual(option1.on_selected.call_count, 2) self.assertEqual(option2.on_selected.call_count, 1) self.assertEqual(option1.step.call_count, 4) self.assertEqual(option2.step.call_count, 3) assert_mock_step_type(option1.step, dm_env.StepType.FIRST) assert_mock_step_type(option2.step, dm_env.StepType.LAST) self.assertSetEqual(set([option1, option2]), cond_option.options_selected) # Step 6; Switch 1->2; (call_ctr 4->5) # Should term-step option1 and select + first-step option2. cond_option.step(mid_timestep) self.assertEqual(flip_flop_cond._call_ctr, 5) self.assertEqual(option1.on_selected.call_count, 2) self.assertEqual(option2.on_selected.call_count, 2) self.assertEqual(option1.step.call_count, 5) self.assertEqual(option2.step.call_count, 4) assert_mock_step_type(option1.step, dm_env.StepType.LAST) assert_mock_step_type(option2.step, dm_env.StepType.FIRST) self.assertSetEqual(set([option1, option2]), cond_option.options_selected) # Step 7; No switch; (call_ctr 5->5) # Send terminal step and verify both options see it. # Should term-step option1 and option2 # The set of selected options should be reinitialized. cond_option.step(last_timestep) self.assertEqual(flip_flop_cond._call_ctr, 5) self.assertEqual(option1.step.call_count, 6) self.assertEqual(option2.step.call_count, 5) cond_option._true_branch.step.assert_called_with(last_timestep) cond_option._false_branch.step.assert_called_with(last_timestep) self.assertSetEqual(set(), cond_option.options_selected) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/agentflow/meta_options/control_flow/cond_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """Common boilerplate for examples.""" from typing import Mapping, Optional, Text, Tuple import dm_env from dm_env import specs from dm_robotics.agentflow import core from dm_robotics.agentflow import subtask import numpy as np class DummyEnv(dm_env.Environment): """A dummy environment with some spec.""" def observation_spec(self) -> Mapping[Text, specs.Array]: return { 'dummy_obs': specs.BoundedArray( shape=(3,), dtype=np.float32, minimum=0., maximum=1., name='dummy_obs') } def action_spec(self) -> specs.Array: return specs.BoundedArray( shape=(4,), dtype=np.float32, minimum=0., maximum=1., name='dummy_act') def step(self, action) -> dm_env.TimeStep: return dm_env.TimeStep( reward=0., discount=1., observation={'dummy_obs': np.random.rand(3)}, step_type=dm_env.StepType.MID) def reset(self) -> dm_env.TimeStep: return dm_env.TimeStep( reward=0., discount=1., observation={'dummy_obs': np.random.rand(3)}, step_type=dm_env.StepType.FIRST) class DummySubTask(subtask.SubTask): """A dummy subtask.""" def __init__(self, base_obs_spec: Mapping[Text, specs.Array], name: Optional[Text] = None): super().__init__(name) self._base_obs_spec = base_obs_spec def observation_spec(self) -> Mapping[Text, specs.Array]: return self._base_obs_spec def arg_spec(self) -> Optional[specs.Array]: return def action_spec(self) -> specs.Array: # pytype: disable=signature-mismatch # overriding-return-type-checks return specs.BoundedArray( shape=(2,), dtype=np.float32, minimum=0., maximum=1., name='dummy_act') def agent_to_parent_action(self, agent_action: np.ndarray) -> np.ndarray: return np.hstack((agent_action, np.zeros(2))) # Return full action. def parent_to_agent_timestep(self, parent_timestep: dm_env.TimeStep, # pytype: disable=signature-mismatch # overriding-return-type-checks arg_key: Text) -> Tuple[dm_env.TimeStep, float]: return (parent_timestep, 1.0) def pterm(self, parent_timestep: dm_env.TimeStep, own_arg_key: Text) -> float: return 0. class DummyPolicy(core.Policy): """A dummy policy.""" def __init__(self, action_spec: specs.Array, unused_observation_spec: Mapping[Text, specs.Array], name: Optional[Text] = None): super().__init__(name) self._action_spec = action_spec def step(self, timestep: dm_env.TimeStep) -> np.ndarray: return np.random.rand(self._action_spec.shape[0]) class DummyOption(core.Option): """A dummy option.""" def __init__(self, action_spec: specs.Array, unused_observation_spec: Mapping[Text, specs.Array], name: Optional[Text] = None): super().__init__(name) self._action_spec = action_spec def step(self, timestep: dm_env.TimeStep) -> np.ndarray: option_action = np.random.rand(self._action_spec.shape[0]) return np.hstack((option_action, np.zeros(2)))
dm_robotics-main
py/agentflow/meta_options/control_flow/examples/common.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """An Control-Flow example which builds up a simple insertion experiment.""" from typing import Optional from absl import app import dm_env from dm_robotics.agentflow import core from dm_robotics.agentflow import subtask from dm_robotics.agentflow.meta_options.control_flow import cond from dm_robotics.agentflow.meta_options.control_flow import loop_ops from dm_robotics.agentflow.meta_options.control_flow import sequence from dm_robotics.agentflow.meta_options.control_flow.examples import common from dm_robotics.agentflow.rendering import graphviz_renderer def near_socket(unused_timestep: dm_env.TimeStep, unused_result: Optional[core.OptionResult]) -> bool: return False def last_option_successful(unused_timestep: dm_env.TimeStep, result: core.OptionResult): return result.termination_reason == core.TerminationType.SUCCESS def build(): """Builds example graph.""" env = common.DummyEnv() # Define a subtask that exposes the desired RL-environment view on `base_task` my_subtask = common.DummySubTask(env.observation_spec(), 'Insertion SubTask') # Define a regular RL agent against this task-spec. my_policy = common.DummyPolicy(my_subtask.action_spec(), my_subtask.observation_spec(), 'My Policy') # Compose the policy and subtask to form an Option module. learned_insert_option = subtask.SubTaskOption( my_subtask, my_policy, name='Learned Insertion') reach_option = common.DummyOption(env.action_spec(), env.observation_spec(), 'Reach for Socket') scripted_reset = common.DummyOption(env.action_spec(), env.observation_spec(), 'Scripted Reset') extract_option = common.DummyOption(env.action_spec(), env.observation_spec(), 'Extract') recovery_option = common.DummyOption(env.action_spec(), env.observation_spec(), 'Recover') # Use some AgentFlow operators to embed the agent in a bigger agent. # First use Cond to op run learned-agent if sufficiently close. reach_or_insert_op = cond.Cond( cond=near_socket, true_branch=learned_insert_option, false_branch=reach_option, name='Reach or Insert') # Loop the insert-or-reach option 5 times. reach_and_insert_5x = loop_ops.Repeat( 5, reach_or_insert_op, name='Retry Loop') loop_body = sequence.Sequence([ scripted_reset, reach_and_insert_5x, cond.Cond( cond=last_option_successful, true_branch=extract_option, false_branch=recovery_option, name='post-insert') ]) main_loop = loop_ops.While(lambda _: True, loop_body) graphviz_renderer.open_viewer(main_loop) return main_loop def main(unused_argv): build() if __name__ == '__main__': app.run(main)
dm_robotics-main
py/agentflow/meta_options/control_flow/examples/simple_insertion.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """A subtask with customizable timestep preprocessors and termination functions.""" from typing import Any, Callable, Optional, Text import dm_env from dm_env import specs from dm_robotics import agentflow as af from dm_robotics.agentflow import core from dm_robotics.agentflow import spec_utils from dm_robotics.agentflow.decorators import overrides from dm_robotics.agentflow.preprocessors import timestep_preprocessor as processing import numpy as np class ParameterizedSubTask(af.SubTask): """A subtask with injectable components for actions, obs, and termination.""" def __init__( self, parent_spec: spec_utils.TimeStepSpec, action_space: af.ActionSpace[specs.BoundedArray], timestep_preprocessor: Optional[processing.TimestepPreprocessor] = None, default_termination_type: af.TerminationType = af.TerminationType.FAILURE, render_frame_cb: Optional[Callable[[Any], None]] = None, name: Optional[Text] = None): """Constructor. Args: parent_spec: The spec that is exposed by the environment. action_space: The action space that projects the action received by the agent to one that the environment expects. timestep_preprocessor: The preprocessor that transforms the observation of the environment to the one received by the agent. default_termination_type: Termination type used by default if the `timestep_preprocessor does not return one. render_frame_cb: Callable that is used to render a frame on a canvas. name: Name of the subtask. """ super().__init__(name=name) self._action_space = action_space self._parent_spec = parent_spec self._timestep_preprocessor = timestep_preprocessor if timestep_preprocessor is None: self._spec = parent_spec else: self._spec = timestep_preprocessor.setup_io_spec(self._parent_spec) self._default_termination_type = default_termination_type self._pterm = 0. self._render_frame_cb = render_frame_cb @overrides(af.SubTask) def observation_spec(self): return self._spec.observation_spec @overrides(af.SubTask) def arg_spec(self) -> None: return # ParameterizedSubTask cannot take runtime arguments. @overrides(af.SubTask) def reward_spec(self): return self._spec.reward_spec @overrides(af.SubTask) def discount_spec(self): return self._spec.discount_spec @overrides(af.SubTask) def action_spec(self) -> specs.BoundedArray: return self._action_space.spec() @overrides(af.SubTask) def agent_to_parent_action(self, agent_action: np.ndarray) -> np.ndarray: return self._action_space.project(agent_action) @overrides(af.SubTask) def parent_to_agent_timestep( self, parent_timestep: dm_env.TimeStep, own_arg_key: Optional[Text] = None) -> dm_env.TimeStep: """Applies timestep preprocessors to generate the agent-side timestep.""" del own_arg_key # ParameterizedSubTask doesn't handle signals from parent. preprocessor_timestep = ( processing.PreprocessorTimestep.from_environment_timestep( parent_timestep, pterm=0., result=None)) if self._timestep_preprocessor is not None: preprocessor_timestep = self._timestep_preprocessor.process( preprocessor_timestep) # Cache preprocessed timestep pterm and result since these fields are lost # when converting back to dm_env.TimeStep. self._pterm = preprocessor_timestep.pterm self._result = preprocessor_timestep.result return preprocessor_timestep.to_environment_timestep() @overrides(af.SubTask) def pterm(self, parent_timestep: dm_env.TimeStep, own_arg_key: Text) -> float: del parent_timestep del own_arg_key return self._pterm @overrides(af.SubTask) def subtask_result(self, parent_timestep: dm_env.TimeStep, own_arg_key: Text) -> af.OptionResult: result = self._result or af.OptionResult( self._default_termination_type, data=None) return result @overrides(af.SubTask) def render_frame(self, canvas) -> None: if self._render_frame_cb is not None: self._render_frame_cb(canvas) # Forward render call to timestep_preprocessor(s). if (self._timestep_preprocessor is not None and isinstance(self._timestep_preprocessor, core.Renderable)): self._timestep_preprocessor.render_frame(canvas) def set_timestep_preprocessor( self, preprocessor: processing.TimestepPreprocessor): self._spec = preprocessor.setup_io_spec(self._parent_spec) self._timestep_preprocessor = preprocessor
dm_robotics-main
py/agentflow/subtasks/parameterized_subtask.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """Tests for dm_robotics.agentflow.subtasks.parameterized_subtask.""" from unittest import mock from absl.testing import absltest from absl.testing import parameterized from dm_env import specs from dm_robotics.agentflow import core from dm_robotics.agentflow import spec_utils from dm_robotics.agentflow import testing_functions from dm_robotics.agentflow.preprocessors import timestep_preprocessor as tsp from dm_robotics.agentflow.subtasks import parameterized_subtask class ParameterizedSubtaskTest(parameterized.TestCase): def test_pterm_and_result_caching(self): mock_preprocessor = mock.MagicMock(tsp.TimestepPreprocessor) default_termination_type = core.TerminationType.FAILURE test_subtask = parameterized_subtask.ParameterizedSubTask( parent_spec=mock.MagicMock(spec=spec_utils.TimeStepSpec), action_space=mock.MagicMock(spec=core.ActionSpace[specs.BoundedArray]), timestep_preprocessor=mock_preprocessor, default_termination_type=default_termination_type, name='TestParameterizedSubTask') parent_timestep = testing_functions.random_timestep() # Verify the preprocessor's result is captured. test_result = core.OptionResult(core.TerminationType.SUCCESS, data='test_data') preprocessor_timestep = tsp.PreprocessorTimestep.from_environment_timestep( parent_timestep, pterm=0.123, result=test_result) mock_preprocessor.process.return_value = preprocessor_timestep test_subtask.parent_to_agent_timestep(parent_timestep) self.assertEqual(test_subtask.pterm(parent_timestep, 'fake_key'), 0.123) self.assertEqual(test_subtask.subtask_result(parent_timestep, 'fake_key'), test_result) # If preprocessor doesn't set the result we should recover the default. preprocessor_timestep = tsp.PreprocessorTimestep.from_environment_timestep( parent_timestep, pterm=0.456, result=None) mock_preprocessor.process.return_value = preprocessor_timestep test_subtask.parent_to_agent_timestep(parent_timestep) self.assertEqual(test_subtask.pterm(parent_timestep, 'fake_key'), 0.456) self.assertEqual(test_subtask.subtask_result(parent_timestep, 'fake_key'), core.OptionResult(default_termination_type, data=None)) def test_agent_action_projection(self): mock_preprocessor = mock.MagicMock(tsp.TimestepPreprocessor) default_termination_type = core.TerminationType.FAILURE mock_action_space = mock.create_autospec(spec=core.ActionSpace) test_subtask = parameterized_subtask.ParameterizedSubTask( parent_spec=mock.MagicMock(spec=spec_utils.TimeStepSpec), action_space=mock_action_space, timestep_preprocessor=mock_preprocessor, default_termination_type=default_termination_type, name='TestParameterizedSubTask') agent_action = testing_functions.random_action() test_subtask.agent_to_parent_action(agent_action) mock_action_space.project.assert_called_once_with(agent_action) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/agentflow/subtasks/parameterized_subtask_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """Tests for dm_robotics.agentflow.subtasks.parameterized_subtask.""" from absl.testing import absltest from absl.testing import parameterized import dm_env from dm_env import specs from dm_robotics.agentflow import core from dm_robotics.agentflow import testing_functions from dm_robotics.agentflow.preprocessors import timestep_preprocessor from dm_robotics.agentflow.subtasks import subtask_termination from dm_robotics.geometry import geometry import numpy as np _NUM_RUNS = 10 to_preprocessor_timestep = ( timestep_preprocessor.PreprocessorTimestep.from_environment_timestep) class SubtaskTerminationTest(parameterized.TestCase): def test_max_steps_termination(self): max_steps = 3 terminal_discount = 0. for _ in range(_NUM_RUNS): random_timestep_spec = testing_functions.random_timestep_spec() random_first_timestep = testing_functions.random_timestep( random_timestep_spec, step_type=dm_env.StepType.FIRST) tsp = subtask_termination.MaxStepsTermination( max_steps, terminal_discount) tsp.setup_io_spec(random_timestep_spec) # First-step, increments counter but no change to timestep. preprocessor_timestep = to_preprocessor_timestep( random_first_timestep, pterm=0., result=None) result = tsp.process(preprocessor_timestep) self.assertEqual(result.pterm, 0.) self.assertEqual(result.discount, random_first_timestep.discount) self.assertIsNone(result.result) # Second-step, increments counter but no change to timestep. random_mid_timestep = testing_functions.random_timestep( random_timestep_spec, step_type=dm_env.StepType.MID) preprocessor_timestep = to_preprocessor_timestep( random_mid_timestep, pterm=0., result=None) result = tsp.process(preprocessor_timestep) self.assertEqual(result.pterm, 0.) self.assertEqual(result.discount, random_mid_timestep.discount) self.assertIsNone(result.result) # Third-step, signal termination. result = tsp.process(preprocessor_timestep) self.assertEqual(result.pterm, 1.) self.assertEqual(result.discount, terminal_discount) self.assertEqual(result.result, core.OptionResult.failure_result()) @parameterized.parameters([False, True]) def test_reward_threshold_termination(self, sparse_mode: bool): reward_threshold = 0.5 terminal_discount = 0.2 for _ in range(_NUM_RUNS): reward_spec = specs.BoundedArray( shape=(), dtype=np.float64, minimum=0., maximum=1., name='reward') discount_spec = specs.BoundedArray( shape=(), dtype=np.float64, minimum=0., maximum=1., name='discount') random_timestep_spec = testing_functions.random_timestep_spec( reward_spec=reward_spec, discount_spec=discount_spec) random_mid_timestep = testing_functions.random_timestep( random_timestep_spec, step_type=dm_env.StepType.MID) tsp = subtask_termination.RewardThresholdTermination( reward_threshold, terminal_discount, sparse_mode) tsp.setup_io_spec(random_timestep_spec) # If reward is sub-threshold timestep should be unchanged. sub_thresh_reward = 0.3 random_mid_timestep = random_mid_timestep._replace( reward=sub_thresh_reward) preprocessor_timestep = to_preprocessor_timestep( random_mid_timestep, pterm=0., result=None) result = tsp.process(preprocessor_timestep) self.assertEqual(result.pterm, 0.) self.assertEqual(result.discount, random_mid_timestep.discount) self.assertEqual(result.reward, sub_thresh_reward) self.assertIsNone(result.result) # If reward is super-threshold timestep should be terminal. super_thresh_reward = 0.7 random_mid_timestep = random_mid_timestep._replace( reward=super_thresh_reward) preprocessor_timestep = to_preprocessor_timestep( random_mid_timestep, pterm=0., result=None) result = tsp.process(preprocessor_timestep) if not sparse_mode: self.assertEqual(result.pterm, 1.) self.assertEqual(result.discount, terminal_discount) self.assertEqual(result.reward, super_thresh_reward) self.assertEqual(result.result, core.OptionResult.success_result()) else: # First step signals termination, but sets cached reward and doesn't set # terminal discount self.assertEqual(result.pterm, 1.) self.assertEqual(result.discount, random_mid_timestep.discount) self.assertEqual(result.reward, sub_thresh_reward) self.assertEqual(result.result, core.OptionResult.success_result()) # Stepping again with a MID timestep still does NOT terminate. result = tsp.process(preprocessor_timestep) self.assertEqual(result.pterm, 1.) self.assertEqual(result.discount, random_mid_timestep.discount) self.assertEqual(result.reward, sub_thresh_reward) self.assertEqual(result.result, core.OptionResult.success_result()) # Finally providing a LAST timestep yields proper termination. preprocessor_timestep = preprocessor_timestep._replace( step_type=dm_env.StepType.LAST) result = tsp.process(preprocessor_timestep) self.assertEqual(result.pterm, 1.) self.assertEqual(result.discount, terminal_discount) self.assertEqual(result.reward, super_thresh_reward) self.assertEqual(result.result, core.OptionResult.success_result()) @parameterized.parameters([False, True]) def test_reward_array_threshold_termination(self, use_threshold_array): reward_threshold = 0.5 * np.ones(2) if use_threshold_array else 0.5 terminal_discount = 0.2 reward_spec = specs.BoundedArray( shape=(2,), dtype=np.float64, minimum=0., maximum=1., name='reward') discount_spec = specs.BoundedArray( shape=(), dtype=np.float64, minimum=0., maximum=1., name='discount') random_timestep_spec = testing_functions.random_timestep_spec( reward_spec=reward_spec, discount_spec=discount_spec) random_mid_timestep = testing_functions.random_timestep( random_timestep_spec, step_type=dm_env.StepType.MID) tsp = subtask_termination.RewardThresholdTermination( reward_threshold, terminal_discount) tsp.setup_io_spec(random_timestep_spec) # If reward is sub-threshold timestep should be unchanged. sub_thresh_reward = 0.3 * np.ones(reward_spec.shape, reward_spec.dtype) random_mid_timestep = random_mid_timestep._replace( reward=sub_thresh_reward) preprocessor_timestep = to_preprocessor_timestep( random_mid_timestep, pterm=0., result=None) result = tsp.process(preprocessor_timestep) self.assertEqual(result.pterm, 0.) self.assertEqual(result.discount, random_mid_timestep.discount) self.assertIsNone(result.result) # If reward is super-threshold timestep should be terminal. super_thresh_reward = 0.7 * np.ones(reward_spec.shape, reward_spec.dtype) random_mid_timestep = random_mid_timestep._replace( reward=super_thresh_reward) preprocessor_timestep = to_preprocessor_timestep( random_mid_timestep, pterm=0., result=None) result = tsp.process(preprocessor_timestep) self.assertEqual(result.pterm, 1.) self.assertEqual(result.discount, terminal_discount) self.assertEqual(result.result, core.OptionResult.success_result()) def test_leaving_workspace_termination(self): tcp_pos_obs = 'tcp_pos_obs' workspace_center = np.array([0.1, 0.2, 0.3]) workspace_radius = 0.5 terminal_discount = 0.1 observation_spec = { tcp_pos_obs: specs.BoundedArray( shape=(3,), name=tcp_pos_obs, minimum=np.ones(3) * -10, maximum=np.ones(3) * 10, dtype=np.float64) } discount_spec = specs.BoundedArray( shape=(), dtype=np.float64, minimum=0., maximum=1., name='discount') for _ in range(_NUM_RUNS): random_timestep_spec = testing_functions.random_timestep_spec( observation_spec=observation_spec, discount_spec=discount_spec) tsp = subtask_termination.LeavingWorkspaceTermination( tcp_pos_obs, workspace_center, workspace_radius, terminal_discount) tsp.setup_io_spec(random_timestep_spec) random_unit_offset = np.random.rand(3) random_unit_offset /= np.linalg.norm(random_unit_offset) within_bounds_obs = workspace_center + random_unit_offset * 0.4 out_of_bounds_obs = workspace_center + random_unit_offset * 0.6 # If observation is within bounds the timestep should be unchanged. random_in_bounds_timestep = testing_functions.random_timestep( random_timestep_spec, observation={tcp_pos_obs: within_bounds_obs}) preprocessor_timestep = to_preprocessor_timestep( random_in_bounds_timestep, pterm=0., result=None) result = tsp.process(preprocessor_timestep) self.assertEqual(result.pterm, 0.) self.assertEqual(result.discount, random_in_bounds_timestep.discount) self.assertIsNone(result.result) # If observation is out of bounds the timestep should be terminal. random_out_of_bounds_timestep = testing_functions.random_timestep( random_timestep_spec, observation={tcp_pos_obs: out_of_bounds_obs}) preprocessor_timestep = to_preprocessor_timestep( random_out_of_bounds_timestep, pterm=0., result=None) result = tsp.process(preprocessor_timestep) self.assertEqual(result.pterm, 1.) self.assertEqual(result.discount, terminal_discount) self.assertEqual(result.result, core.OptionResult.failure_result()) def test_leaving_workspace_box_termination(self): tcp_pos_obs = 'tcp_pos_obs' tcp_quat_obs = 'tcp_quat_obs' workspace_center_poseuler = np.array([0.1, 0.2, 0.3, -0.1, 0.2, -0.3]) workspace_center = geometry.PoseStamped( geometry.Pose.from_poseuler(workspace_center_poseuler), None) workspace_limits = np.array([0.3, 0.2, 0.1, 0.5, 0.5, 0.5]) terminal_discount = 0.1 observation_spec = { tcp_pos_obs: specs.BoundedArray( shape=(3,), name=tcp_pos_obs, minimum=np.ones(3) * -10, maximum=np.ones(3) * 10, dtype=np.float64), tcp_quat_obs: specs.BoundedArray( shape=(4,), name=tcp_quat_obs, minimum=np.ones(4) * -1.0, maximum=np.ones(4) * 1.0, dtype=np.float64) } discount_spec = specs.BoundedArray( shape=(), dtype=np.float64, minimum=0., maximum=1., name='discount') for _ in range(_NUM_RUNS): random_timestep_spec = testing_functions.random_timestep_spec( observation_spec=observation_spec, discount_spec=discount_spec) tsp = subtask_termination.LeavingWorkspaceBoxTermination( tcp_pos_obs=tcp_pos_obs, tcp_quat_obs=tcp_quat_obs, workspace_centre=workspace_center, workspace_limits=workspace_limits, terminal_discount=terminal_discount) tsp.setup_io_spec(random_timestep_spec) random_unit_offset = np.random.rand(6) random_unit_offset /= np.linalg.norm(random_unit_offset) # pos-euler offsets. within_bounds_offset = random_unit_offset * 0.99 * workspace_limits out_of_bounds_offset = (random_unit_offset + 1.01) * workspace_limits within_bounds_pose = geometry.PoseStamped( geometry.Pose.from_poseuler(within_bounds_offset), frame=workspace_center) within_bounds_pos = within_bounds_pose.get_world_pose().position within_bounds_quat = within_bounds_pose.get_world_pose().quaternion out_of_bounds_pose = geometry.PoseStamped( geometry.Pose.from_poseuler(out_of_bounds_offset), frame=workspace_center) out_of_bounds_pos = out_of_bounds_pose.get_world_pose().position out_of_bounds_quat = out_of_bounds_pose.get_world_pose().quaternion # If observation is within bounds the timestep should be unchanged. random_in_bounds_timestep = testing_functions.random_timestep( random_timestep_spec, observation={ tcp_pos_obs: within_bounds_pos, tcp_quat_obs: within_bounds_quat }) preprocessor_timestep = to_preprocessor_timestep( random_in_bounds_timestep, pterm=0., result=None) result = tsp.process(preprocessor_timestep) self.assertEqual(result.pterm, 0.) self.assertEqual(result.discount, random_in_bounds_timestep.discount) self.assertIsNone(result.result) # If observation is out of bounds the timestep should be terminal. random_out_of_bounds_timestep = testing_functions.random_timestep( random_timestep_spec, observation={ tcp_pos_obs: out_of_bounds_pos, tcp_quat_obs: out_of_bounds_quat }) preprocessor_timestep = to_preprocessor_timestep( random_out_of_bounds_timestep, pterm=0., result=None) result = tsp.process(preprocessor_timestep) self.assertEqual(result.pterm, 1.) self.assertEqual(result.discount, terminal_discount) self.assertEqual(result.result, core.OptionResult.failure_result()) def test_observation_threshold_termination(self): obs = 'joint_configuration' desired_obs = np.array([0.1, 0.2, 0.3, 0.4]) error_norm = 0.5 terminal_discount = 0.1 observation_spec = { obs: specs.BoundedArray( shape=(4,), name=obs, minimum=np.ones(4) * -10, maximum=np.ones(4) * 10, dtype=np.float64) } discount_spec = specs.BoundedArray( shape=(), dtype=np.float64, minimum=0., maximum=1., name='discount') for _ in range(_NUM_RUNS): random_timestep_spec = testing_functions.random_timestep_spec( observation_spec=observation_spec, discount_spec=discount_spec) tsp = subtask_termination.ObservationThresholdTermination( obs, desired_obs, error_norm, terminal_discount) tsp.setup_io_spec(random_timestep_spec) random_unit_offset = np.random.rand(4) random_unit_offset /= np.linalg.norm(random_unit_offset) within_threshold_obs = desired_obs + random_unit_offset * 0.4 outside_threshold_obs = desired_obs + random_unit_offset * 0.6 # If observation is within the threshold, the timestep should be terminal. random_within_threshold_timestep = testing_functions.random_timestep( random_timestep_spec, observation={obs: within_threshold_obs}) preprocessor_timestep = to_preprocessor_timestep( random_within_threshold_timestep, pterm=0., result=None) result = tsp.process(preprocessor_timestep) self.assertEqual(result.pterm, 1.) self.assertEqual(result.discount, terminal_discount) self.assertEqual(result.result, core.OptionResult.failure_result()) # If observation is outside the threshold, the timestep should be # unchanged. random_outside_threshold_timestep = testing_functions.random_timestep( random_timestep_spec, observation={obs: outside_threshold_obs}) preprocessor_timestep = to_preprocessor_timestep( random_outside_threshold_timestep, pterm=0., result=None) result = tsp.process(preprocessor_timestep) self.assertEqual(result.pterm, 0.) self.assertEqual(result.discount, random_outside_threshold_timestep.discount) self.assertIsNone(result.result) def test_joint_limits_termination(self): joint_pos_obs = 'joint_pos' joint_min_limits = [-0.1, -0.2, -0.3, -0.4] joint_max_limits = [0.1, 0.2, 0.3, 0.4] terminal_discount = 0.1 observation_spec = { joint_pos_obs: specs.Array( shape=(4,), name=joint_pos_obs, dtype=np.float64) } discount_spec = specs.BoundedArray( shape=(), dtype=np.float64, minimum=0., maximum=1., name='discount') for _ in range(_NUM_RUNS): random_timestep_spec = testing_functions.random_timestep_spec( observation_spec=observation_spec, discount_spec=discount_spec) tsp = subtask_termination.JointLimitsTermination( joint_pos_obs, joint_min_limits, joint_max_limits, terminal_discount) tsp.setup_io_spec(random_timestep_spec) within_bounds_obs = np.random.uniform( low=joint_min_limits, high=joint_max_limits) below_bounds_obs = np.random.uniform(low=-1., high=-0.5, size=(4,)) above_bounds_obs = np.random.uniform(low=0.5, high=1., size=(4,)) # If observation is within bounds the timestep should be unchanged. random_in_bounds_timestep = testing_functions.random_timestep( random_timestep_spec, observation={joint_pos_obs: within_bounds_obs}) preprocessor_timestep = to_preprocessor_timestep( random_in_bounds_timestep, pterm=0., result=None) result = tsp.process(preprocessor_timestep) self.assertEqual(result.pterm, 0.) self.assertEqual(result.discount, random_in_bounds_timestep.discount) self.assertIsNone(result.result) # If observation is out of bounds the timestep should be terminal. for out_of_bounds_obs in [below_bounds_obs, above_bounds_obs]: random_out_of_bounds_timestep = testing_functions.random_timestep( random_timestep_spec, observation={joint_pos_obs: out_of_bounds_obs}) preprocessor_timestep = to_preprocessor_timestep( random_out_of_bounds_timestep, pterm=0., result=None) result = tsp.process(preprocessor_timestep) self.assertEqual(result.pterm, 1.) self.assertEqual(result.discount, terminal_discount) self.assertEqual(result.result, core.OptionResult.failure_result()) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/agentflow/subtasks/subtask_termination_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """Integration test for parameterized_subtask and termination components.""" from unittest import mock from absl.testing import absltest from absl.testing import parameterized import dm_env from dm_env import specs from dm_robotics.agentflow import core from dm_robotics.agentflow import subtask from dm_robotics.agentflow import testing_functions from dm_robotics.agentflow.preprocessors import rewards from dm_robotics.agentflow.preprocessors import timestep_preprocessor from dm_robotics.agentflow.subtasks import parameterized_subtask from dm_robotics.agentflow.subtasks import subtask_termination import numpy as np class IntegrationTest(parameterized.TestCase): def setUp(self): super().setUp() # Parameters for MaxStepsTermination. self._max_steps = 10 self._max_steps_terminal_discount = 0.123 # Parameters for RewardThresholdTermination. self._reward_threshold = 0.5 self._reward_threshold_terminal_discount = 0. # Parameters for LeavingWorkspaceTermination. self._tcp_pos_obs = 'tcp_pos' self._workspace_center = np.array([0.2, -0.4, 0.6]) self._workspace_radius = 1. self._leaving_workspace_terminal_discount = 0.456 self._tcp_observation_spec = { self._tcp_pos_obs: specs.BoundedArray( shape=(3,), name=self._tcp_pos_obs, minimum=np.ones(3) * -10, maximum=np.ones(3) * 10, dtype=np.float64) } # Parameters for ThresholdedL2Reward. self._reward_l2_threshold = 0.1 self._success_reward_value = 1. self._world_center_obs = 'world_center' self._world_center_observation_spec = { self._world_center_obs: specs.BoundedArray( shape=(3,), name=self._world_center_obs, minimum=self._workspace_center, maximum=self._workspace_center, dtype=np.float64) } def _build(self, sparse_mode: bool): # Configure all timestep preprocessors. max_steps_tsp = subtask_termination.MaxStepsTermination( self._max_steps, self._max_steps_terminal_discount) leaving_workspace_tsp = subtask_termination.LeavingWorkspaceTermination( self._tcp_pos_obs, self._workspace_center, self._workspace_radius, self._leaving_workspace_terminal_discount) reward_setting_tsp = rewards.ThresholdedL2Reward( obs0=self._tcp_pos_obs, obs1=self._world_center_obs, threshold=self._reward_l2_threshold, reward=self._success_reward_value) reward_threshold_tsp = subtask_termination.RewardThresholdTermination( self._reward_threshold, self._reward_threshold_terminal_discount, sparse_mode=sparse_mode) # Compose to a single CompositeTimestepPreprocessor that runs in order. self._preprocesors = [ max_steps_tsp, leaving_workspace_tsp, reward_setting_tsp, reward_threshold_tsp ] ts_preprocessor = timestep_preprocessor.CompositeTimestepPreprocessor( *self._preprocesors) # Create task spec and instantiate subtask. self._action_spec = testing_functions.random_array_spec(shape=(4,)) random_action_space = core.IdentityActionSpace(self._action_spec) random_observation_spec = testing_functions.random_observation_spec( dtype=np.float64) random_observation_spec.update(self._tcp_observation_spec) random_observation_spec.update(self._world_center_observation_spec) self._parent_spec = testing_functions.random_timestep_spec( observation_spec=random_observation_spec) self._subtask = parameterized_subtask.ParameterizedSubTask( parent_spec=self._parent_spec, action_space=random_action_space, timestep_preprocessor=ts_preprocessor, name='TestParameterizedSubTask') # Update types on all reward and discount members for tests. discount_type = self._parent_spec.discount_spec.dtype.type reward_type = self._parent_spec.reward_spec.dtype.type self._default_discount = discount_type(1.) self._default_reward = reward_type(0.) self._success_reward_value = reward_type(self._success_reward_value) self._reward_threshold_terminal_discount = discount_type( self._reward_threshold_terminal_discount) self._max_steps_terminal_discount = discount_type( self._max_steps_terminal_discount) self._leaving_workspace_terminal_discount = discount_type( self._leaving_workspace_terminal_discount) def _run(self, default_tcp_obs, event_tcp_obs, event_step_idx, expected_rewards, expected_discounts): # Steps through an episode, setting `event_tcp_obs` on step `event_step_idx` # and checks that the policy saw the correct rewards and discounts. mock_policy = mock.MagicMock(spec=core.Policy) valid_action = testing_functions.valid_value(self._action_spec) mock_policy.step.return_value = valid_action agent = subtask.SubTaskOption(sub_task=self._subtask, agent=mock_policy, name='Subtask Option') random_first_timestep = testing_functions.random_timestep( self._parent_spec, step_type=dm_env.StepType.FIRST, discount=self._default_discount) random_first_timestep.observation[self._tcp_pos_obs] = default_tcp_obs _ = agent.step(random_first_timestep) for i in range(1, self._max_steps * 2): random_mid_timestep = testing_functions.random_timestep( self._parent_spec, step_type=dm_env.StepType.MID, discount=self._default_discount) if i == event_step_idx: random_mid_timestep.observation[self._tcp_pos_obs] = event_tcp_obs else: random_mid_timestep.observation[self._tcp_pos_obs] = default_tcp_obs _ = agent.step(random_mid_timestep) if agent.pterm(random_mid_timestep) > np.random.rand(): random_last_timestep = testing_functions.random_timestep( self._parent_spec, step_type=dm_env.StepType.LAST, discount=self._default_discount) # TCP doesn't have to be in-bounds for subtask to provide terminal # reward, so just to verify we set back to out-of-bounds. random_last_timestep.observation[self._tcp_pos_obs] = event_tcp_obs _ = agent.step(random_last_timestep) break actual_rewards = [ call[0][0].reward for call in mock_policy.step.call_args_list ] actual_discounts = [ call[0][0].discount for call in mock_policy.step.call_args_list ] self.assertEqual(expected_rewards, actual_rewards) self.assertEqual(expected_discounts, actual_discounts) @parameterized.parameters([False, True]) def test_terminating_with_sparse_reward(self, sparse_mode: bool): # Tests that agent sees proper reward and discount when solving the task. self._build(sparse_mode) # Make sure tcp is not within radius of target. random_unit_offset = np.random.rand(3) random_unit_offset /= np.linalg.norm(random_unit_offset) within_bounds_obs = ( self._workspace_center + random_unit_offset * (self._workspace_radius / 2.)) success_obs = ( self._workspace_center + random_unit_offset * (self._reward_l2_threshold / 2.)) event_step_idx = 5 event_tcp_obs = success_obs default_tcp_obs = within_bounds_obs expected_event_reward = self._success_reward_value expected_event_discount = self._reward_threshold_terminal_discount # Expected results: if sparse_mode: # If `sparse_mode` then agent should see reward=0 and discount=1 for first # step and following `event_step_idx - 1` steps, and then reward=1 and # discount=0 for step `event_step_idx + 1`. The episode should terminate # on that step. expected_rewards = ([self._default_reward] + # first step. [self._default_reward] * event_step_idx + # steps 1:n [expected_event_reward]) # last step. expected_discounts = ([self._default_discount] + [self._default_discount] * event_step_idx + [expected_event_discount]) else: # In default mode agent should see `event_step_idx` regular steps with # reward=0 and discount=1, and TWO "success" steps with reward=1 and # discount=0. expected_rewards = ([self._default_reward] * event_step_idx + # 0:(n-1). [expected_event_reward] + # first success step. [expected_event_reward]) # last step. expected_discounts = ([self._default_discount] * event_step_idx + [expected_event_discount] + # first success step. [expected_event_discount]) # last step. self._run(default_tcp_obs, event_tcp_obs, event_step_idx, expected_rewards, expected_discounts) def test_terminating_out_of_bounds(self): # Tests that agent sees proper reward and discount when violating workspace # limits. self._build(False) # Make sure tcp is not within radius of target. random_unit_offset = np.random.rand(3) random_unit_offset /= np.linalg.norm(random_unit_offset) out_of_bounds_obs = ( self._workspace_center + random_unit_offset * (self._workspace_radius * 2.)) within_bounds_obs = ( self._workspace_center + random_unit_offset * (self._workspace_radius / 2.)) event_step_idx = 5 event_tcp_obs = out_of_bounds_obs default_tcp_obs = within_bounds_obs expected_event_reward = self._default_reward expected_event_discount = self._leaving_workspace_terminal_discount # Expected results: # Agent should see `event_step_idx` regular steps with reward=0 and # discount=1, and TWO "failure" steps with reward=0 and discount=0. expected_rewards = ([self._default_reward] * event_step_idx + # 0:(n-1). [expected_event_reward] + # first success step. [expected_event_reward]) # last step. expected_discounts = ([self._default_discount] * event_step_idx + [expected_event_discount] + # first success step. [expected_event_discount]) # last step. self._run(default_tcp_obs, event_tcp_obs, event_step_idx, expected_rewards, expected_discounts) def test_terminating_max_steps(self): # Tests that agent sees proper reward and discount when running out of time. self._build(False) # Make sure tcp is not within radius of target. random_unit_offset = np.random.rand(3) random_unit_offset /= np.linalg.norm(random_unit_offset) within_bounds_obs = ( self._workspace_center + random_unit_offset * (self._workspace_radius / 2.)) event_step_idx = self._max_steps - 1 event_tcp_obs = within_bounds_obs default_tcp_obs = within_bounds_obs expected_event_reward = self._default_reward expected_event_discount = self._max_steps_terminal_discount # Expected results: # Agent should see `event_step_idx` regular steps with reward=0 and # discount=1, and TWO "failure" steps with reward=0 and discount=0. expected_rewards = ([self._default_reward] * event_step_idx + # 0:(n-1). [expected_event_reward] + # first success step. [expected_event_reward]) # last step. expected_discounts = ([self._default_discount] * event_step_idx + [expected_event_discount] + # first success step. [expected_event_discount]) # last step. self._run(default_tcp_obs, event_tcp_obs, event_step_idx, expected_rewards, expected_discounts) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/agentflow/subtasks/integration_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """A subtask with customizable timestep preprocessors and termination functions.""" from typing import Optional, Sequence, Union from absl import logging from dm_robotics.agentflow import core from dm_robotics.agentflow import spec_utils from dm_robotics.agentflow import util as af_util from dm_robotics.agentflow.decorators import overrides from dm_robotics.agentflow.preprocessors import timestep_preprocessor as preprocessors from dm_robotics.geometry import geometry import numpy as np import tree class MaxStepsTermination(preprocessors.TimestepPreprocessor): """Terminate when the maximum number of steps is reached.""" def __init__( self, max_steps: int, terminal_discount: float = 1., validation_frequency: preprocessors.ValidationFrequency = ( preprocessors.ValidationFrequency.ONCE_PER_EPISODE)): """Initialize MaxStepsTermination. Args: max_steps: The maximum number of steps in the episode. terminal_discount: A scalar discount to set when the step threshold is exceeded. validation_frequency: The validation frequency of the preprocessor. """ super().__init__(validation_frequency=validation_frequency) self._max_steps = max_steps self._terminal_discount = terminal_discount self._steps = 0 self._episode_reward_sum = None @overrides(preprocessors.TimestepPreprocessor) def _process_impl( self, timestep: preprocessors.PreprocessorTimestep ) -> preprocessors.PreprocessorTimestep: if timestep.first(): self._steps = 0 self._episode_reward_sum = None self._steps += 1 if timestep.reward is not None: if self._episode_reward_sum is None: # Initialize (possibly nested) reward sum. self._episode_reward_sum = tree.map_structure( lambda _: 0.0, timestep.reward) # Update (possibly nested) reward sum. self._episode_reward_sum = tree.map_structure( lambda x, y: x + y, self._episode_reward_sum, timestep.reward) if self._steps >= self._max_steps: ts = timestep._replace(pterm=1.0, discount=self._terminal_discount, result=core.OptionResult.failure_result()) af_util.log_info('Episode timeout', 'red') logging.info( 'Terminating with discount %s because maximum steps reached ' '(%s)', ts.discount, self._max_steps) logging.info( 'Reward Sum: %r, Last Reward: %r', self._episode_reward_sum, ts.reward) return ts return timestep @overrides(preprocessors.TimestepPreprocessor) def _output_spec( self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec: self._terminal_discount = input_spec.discount_spec.dtype.type( self._terminal_discount) return input_spec class RewardThresholdTermination(preprocessors.TimestepPreprocessor): """Terminate when the agent receives more than threshold reward on a step.""" def __init__( self, reward_threshold: Union[float, np.ndarray], terminal_discount: float = 0., sparse_mode: bool = False, validation_frequency: preprocessors.ValidationFrequency = ( preprocessors.ValidationFrequency.ONCE_PER_EPISODE)): """Initialize RewardThresholdTermination. Args: reward_threshold: Scalar or array threshold on reward current found in timestep. If reward exceeds threshold(s), triggers termination according to `sparse_mode`. terminal_discount: The discount to set when the threshold is exceeded. sparse_mode: If False (default), simply adds the discount and a `SUCCESS` result for any timesteps with reward exceeding threshold. Note this typically results in the post-threshold reward being seen twice, because agentflow always LAST steps an option after pterm. If `sparse_mode` is True, the first post-threshold step only sets `pterm=1` and a SUCCESS result, but uses the last (cached) sub-threshold reward until a LAST timestep is received. validation_frequency: The validation frequency of the preprocessor. """ super().__init__(validation_frequency=validation_frequency) self._reward_threshold = reward_threshold self._terminal_discount = terminal_discount self._sparse_mode = sparse_mode self._reset() def _reset(self) -> None: self._terminate_next_step = False self._last_subthresh_reward = None def _log_success(self, timestep: preprocessors.PreprocessorTimestep): af_util.log_info('Episode successful!', 'yellow') logging.info( 'Terminating with discount (%s) because reward (%s) crossed ' 'threshold (%s)', timestep.discount, timestep.reward, self._reward_threshold) @overrides(preprocessors.TimestepPreprocessor) def _process_impl( self, timestep: preprocessors.PreprocessorTimestep ) -> preprocessors.PreprocessorTimestep: if timestep.first(): self._reset() if np.all(timestep.reward >= self._reward_threshold): if self._sparse_mode: # Only provide super-threshold reward on LAST timestep. if self._terminate_next_step and timestep.last(): # Reward still > threshold and received LAST timestep; terminate. timestep = timestep._replace( pterm=1.0, discount=self._terminal_discount, result=core.OptionResult.success_result()) self._log_success(timestep) self._reset() return timestep else: # Signal termination and cache reward, but set reward back to last # sub-threshold value until we receive a LAST step. timestep = timestep._replace( pterm=1.0, reward=self._last_subthresh_reward, result=core.OptionResult.success_result()) self._terminate_next_step = True else: # Default mode: simply request termination and set terminal discount. timestep = timestep._replace( pterm=1.0, discount=self._terminal_discount, result=core.OptionResult.success_result()) self._log_success(timestep) return timestep else: self._last_subthresh_reward = timestep.reward logging.log_every_n( logging.INFO, 'Not terminating; reward (%s) less ' 'than threshold (%s)', 100, timestep.reward, self._reward_threshold) return timestep @overrides(preprocessors.TimestepPreprocessor) def _output_spec( self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec: self._terminal_discount = input_spec.discount_spec.dtype.type( self._terminal_discount) return input_spec class LeavingWorkspaceTermination(preprocessors.TimestepPreprocessor): """Terminate if the object(s) leave the workspace.""" def __init__(self, pose_obs_keys: Union[str, Sequence[str]], workspace_center: Sequence[float], workspace_radius: float, terminal_discount: float = 0., validation_frequency: preprocessors.ValidationFrequency = ( preprocessors.ValidationFrequency.ONCE_PER_EPISODE)): """Initialize LeavingWorkspaceTermination. Args: pose_obs_keys: A (or Sequence of) string key(s) into the observation from the timestep in which to find a 3-dim array representing position(s) in world-coords of the prop(s) to track (this can also be the tool center-point of the robot). workspace_center: A 3-dim array representing the position of the center of the workspace in world coords. workspace_radius: A float representing the radius of the workspace sphere. terminal_discount: A scalar discount to set when the workspace is violated validation_frequency: The validation frequency of the preprocessor. """ super().__init__(validation_frequency=validation_frequency) # Convert the input to a list if it isn't already. self._pose_obs_keys = [pose_obs_keys] if isinstance(pose_obs_keys, str) else pose_obs_keys self._workspace_centre = np.array(workspace_center, dtype=np.float32) self._workspace_radius = workspace_radius self._terminal_discount = terminal_discount def _process_impl( self, timestep: preprocessors.PreprocessorTimestep ) -> preprocessors.PreprocessorTimestep: # Check poses one by one and terminate when find one that is outside the # workspace. for pose_key in self._pose_obs_keys: try: pose = timestep.observation[pose_key] except KeyError as key_error: raise KeyError( ('{} not a valid observation name. Valid names are ' '{}').format(pose_key, list(timestep.observation.keys()))) from key_error dist = np.linalg.norm(pose[:3] - self._workspace_centre) if dist > self._workspace_radius: ts = timestep._replace(pterm=1.0, discount=self._terminal_discount, result=core.OptionResult.failure_result()) logging.info( 'Terminating with discount %s because out of bounds. \n' 'obs_key: %s\n' 'pose (xyz): %s\n' 'workspace_centre: %s\n' 'dist: %s,' 'workspace_radius: %s\n', ts.discount, pose_key, pose, self._workspace_centre, dist, self._workspace_radius) return ts return timestep @overrides(preprocessors.TimestepPreprocessor) def _output_spec( self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec: self._terminal_discount = input_spec.discount_spec.dtype.type( self._terminal_discount) return input_spec class LeavingWorkspaceBoxTermination(preprocessors.TimestepPreprocessor): """Terminate if the robot's tool center point leaves the 6D workspace box.""" def __init__(self, tcp_pos_obs: str, tcp_quat_obs: str, workspace_centre: geometry.PoseStamped, workspace_limits: np.ndarray, tcp_offset: Optional[geometry.Pose] = None, terminal_discount: float = 0., validation_frequency: preprocessors.ValidationFrequency = ( preprocessors.ValidationFrequency.ONCE_PER_EPISODE)): """Initialize LeavingWorkspaceBoxTermination. Args: tcp_pos_obs: A string key into the observation from the timestep in which to find a 3-dim array representing the tool center-point position in world-coords. tcp_quat_obs: A tring key into the observation from the timestep in which to find a 4-dim array representing the tool center-point orientation quaternion in world-coords. workspace_centre: A PoseStamped object representing the pose of the center of the workspace in world coords. workspace_limits: A 6D pos-euler array (XYZ ordering) that defines the maximal limits of the workspace relative to the workspace centre. It is important to note that these limits are defined in the coordinate space of the workspace centre, NOT in world coordinates. tcp_offset: An optional offset from the TCP pose of the point on the arm that is checked against the workspace bounds. terminal_discount: A scalar discount to set when the workspace is violated validation_frequency: The validation frequency of the preprocessor. """ super().__init__(validation_frequency=validation_frequency) self._tcp_pos_obs = tcp_pos_obs self._tcp_quat_obs = tcp_quat_obs self._workspace_centre = workspace_centre self._workspace_limits = workspace_limits self._tcp_offset = tcp_offset self._terminal_discount = terminal_discount if len(workspace_limits) != 6: raise ValueError('Workspace Limits should be 6-dim pos-euler vector') @overrides(preprocessors.TimestepPreprocessor) def _process_impl( self, timestep: preprocessors.PreprocessorTimestep ) -> preprocessors.PreprocessorTimestep: tcp_pos = timestep.observation[self._tcp_pos_obs] tcp_quat = timestep.observation[self._tcp_quat_obs] tcp_pose = geometry.Pose(tcp_pos, tcp_quat) if self._tcp_offset is not None: offset_tcp_pose = tcp_pose.mul(self._tcp_offset) else: offset_tcp_pose = tcp_pose offset_tcp_pose = geometry.PoseStamped(offset_tcp_pose, None) rel_pose = offset_tcp_pose.get_relative_pose(self._workspace_centre) dist = np.abs(rel_pose.to_poseuler()) if np.all(dist < self._workspace_limits): return timestep else: ts = timestep._replace(pterm=1.0, discount=self._terminal_discount, result=core.OptionResult.failure_result()) logging.info( 'Terminating with discount %s because out of bounds. \n' 'tcp_site_pos (xyz): %s\n' 'tcp_site_quat (wxyz): %s\n' 'workspace_centre: %s\n' 'workspace_limits: %s\n' 'dist: %s\n', ts.discount, tcp_pos, tcp_quat, self._workspace_centre, self._workspace_limits, dist) return ts @overrides(preprocessors.TimestepPreprocessor) def _output_spec( self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec: self._check_inputs(input_spec) self._terminal_discount = input_spec.discount_spec.dtype.type( self._terminal_discount) return input_spec def _check_inputs(self, input_spec: spec_utils.TimeStepSpec) -> None: """Check that we have the correct keys in the observations.""" for key in [self._tcp_pos_obs, self._tcp_quat_obs]: if key not in input_spec.observation_spec: raise KeyError(('{} not a valid observation name. Valid names are ' '{}').format(self._tcp_pos_obs, list(input_spec.observation_spec.keys()))) class ObservationThresholdTermination(preprocessors.TimestepPreprocessor): """Terminate if the observation is in the vicinity of a specified value.""" def __init__( self, observation: str, desired_obs_values: Sequence[float], norm_threshold: float, terminal_discount: float = 0., validation_frequency: preprocessors.ValidationFrequency = ( preprocessors.ValidationFrequency.ONCE_PER_EPISODE) ): """Initialize ObservationThresholdTermination. Args: observation: A string key into the observation from the timestep in which to find a N-dim array representing the observation for which to set a threshold. desired_obs_values: A N-dim array representing the desired observation values. norm_threshold: A float representing the error norm below which it should terminate. terminal_discount: A scalar discount to set when terminating. validation_frequency: The validation frequency of the preprocessor. Raises: KeyError: if `observation` is not a valid observation name. """ super().__init__(validation_frequency=validation_frequency) self._obs = observation self._desired_obs_values = np.array(desired_obs_values, dtype=np.float32) self._norm_threshold = norm_threshold self._terminal_discount = terminal_discount def _process_impl( self, timestep: preprocessors.PreprocessorTimestep ) -> preprocessors.PreprocessorTimestep: try: obs_values = timestep.observation[self._obs] except KeyError as key_error: raise KeyError( ('{} not a valid observation name. Valid names are ' '{}').format(self._obs, list(timestep.observation.keys()))) from key_error error_norm = np.linalg.norm(obs_values[:] - self._desired_obs_values) if error_norm <= self._norm_threshold: ts = timestep._replace( pterm=1.0, discount=self._terminal_discount, result=core.OptionResult.failure_result()) logging.info( 'Terminating with discount %s because %s is within the threshold.\n' 'observation values: %s\n' 'desired observation values: %s\n' 'error norm: %s,' 'threshold: %s\n', self._terminal_discount, self._obs, obs_values, self._desired_obs_values, error_norm, self._norm_threshold) return ts else: return timestep @overrides(preprocessors.TimestepPreprocessor) def _output_spec( self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec: self._terminal_discount = input_spec.discount_spec.dtype.type( self._terminal_discount) return input_spec class JointLimitsTermination(preprocessors.TimestepPreprocessor): """Terminate if an arm goes beyond the specified limits. Note that this mainly works with arms that have rotational joints which allow less than one full rotation. Arms with joints that can rotate more than 2pi radians, like the UR series, may not not work with this, depending on how the arm is initialized at the start of an episode. """ def __init__(self, joint_pos_obs_key: str, joint_pos_min_limits: Sequence[float], joint_pos_max_limits: Sequence[float], terminal_discount: float = 0., validation_frequency: preprocessors.ValidationFrequency = ( preprocessors.ValidationFrequency.ONCE_PER_EPISODE)): """Initialize JointLimitsTermination. Args: joint_pos_obs_key: A string key into the observation from the timestep which returns the joint positions of the robot arm. joint_pos_min_limits: Sequence of the lower limits of the joint positions. If the arm drops below any of these limits, the episode will terminate. joint_pos_max_limits: Sequence of the upper limits of the joint positions. If the arm goes above any of these limits, the episode will terminate. terminal_discount: A scalar discount to set when the limits are violated. validation_frequency: The validation frequency of the preprocessor. """ super().__init__(validation_frequency=validation_frequency) self._joint_pos_obs_key = joint_pos_obs_key self._joint_pos_min_limits = list(joint_pos_min_limits) self._joint_pos_max_limits = list(joint_pos_max_limits) self._terminal_discount = terminal_discount def _process_impl( self, timestep: preprocessors.PreprocessorTimestep ) -> preprocessors.PreprocessorTimestep: joint_pos = timestep.observation[self._joint_pos_obs_key] if (np.any(joint_pos < self._joint_pos_min_limits) or np.any(joint_pos > self._joint_pos_max_limits)): ts = timestep._replace(pterm=1.0, discount=self._terminal_discount, result=core.OptionResult.failure_result()) logging.info( 'Terminating with discount %s because out of bounds. \n' 'obs_key: %s\n' 'joint pos: %s\n' 'min limits: %s\n' 'max limits: %s\n', ts.discount, self._joint_pos_obs_key, joint_pos, self._joint_pos_min_limits, self._joint_pos_max_limits) return ts return timestep @overrides(preprocessors.TimestepPreprocessor) def _output_spec( self, input_spec: spec_utils.TimeStepSpec) -> spec_utils.TimeStepSpec: self._terminal_discount = input_spec.discount_spec.dtype.type( self._terminal_discount) return input_spec
dm_robotics-main
py/agentflow/subtasks/subtask_termination.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """Module to convert AgentFlow policies into a Graph. The job of this module is to translate (represent) each component of AgentFlow (E.g. a Conditional option, a Sequence) as an *abstract* graph. This means the rendering doesn't have to know about AgentFlow. """ from typing import Any, Callable, Type from dm_robotics import agentflow as af from dm_robotics.agentflow.rendering import subgraph # Special nodes. ENTRY_NODE = subgraph.Node('_entry_', 'entry') EXIT_NODE = subgraph.Node('_exit_', 'exit') # Edge types SUCCESS_STR = af.TerminationType.SUCCESS.name FAILURE_STR = af.TerminationType.FAILURE.name PREEMPTED_STR = af.TerminationType.PREEMPTED.name def render(agent: af.Policy) -> subgraph.Node: """Render a policy as a subgraph.Node.""" # Look for most-specific match for agent type, falling back to generic node. for cls in agent.__class__.mro(): try: return _RENDER_FUNCS[cls](agent) except KeyError as ex: if ex.args[0] == cls: continue raise ex return subgraph.Node(agent.name, type='option') def add_renderer(node_type: Type[af.Policy], render_func: Callable[[Any], subgraph.Graph]): """Adds a custom renderer for the provided AgentFlow node type. This callable should generate the intermediate `subgraph.Graph` representation, not a final output e.g. pydot, png, networkx, etc. Args: node_type: The type of node to associate with `render_func`. render_func: A callable taking an instance of type `node_type` and returning an intermediate `subgraph.Graph` representation to be passed to the final renderer front-end. """ _RENDER_FUNCS.update({node_type: render_func}) def _repeat_to_graph(agent: af.Repeat) -> subgraph.Graph: node = render(_get_only_child(agent)) return subgraph.Graph( label=agent.name, nodes=frozenset([ENTRY_NODE, node, EXIT_NODE]), edges=frozenset([ subgraph.Edge(ENTRY_NODE, node), subgraph.Edge(node, node, label='{} times'.format(agent.num_iters)), subgraph.Edge(node, EXIT_NODE) ])) def _get_only_child(agent: af.Policy) -> af.Policy: children = list(agent.child_policies()) if len(children) != 1: raise ValueError('{} should have one child, actual: {}'.format( agent.name, [child.name for child in children])) return children[0] def _while_to_graph(agent: af.While) -> subgraph.Graph: condition_node = subgraph.Node(label='Condition', type='condition') node = render(_get_only_child(agent)) return subgraph.Graph( label=agent.name, nodes=frozenset([ENTRY_NODE, condition_node, node, EXIT_NODE]), edges=frozenset([ subgraph.Edge(ENTRY_NODE, condition_node), subgraph.Edge(condition_node, node, label='True'), subgraph.Edge(condition_node, EXIT_NODE, label='False'), subgraph.Edge(node, condition_node, label='While') ])) def _sequence_to_graph(agent: af.Sequence) -> subgraph.Graph: """Convert a `Sequence` to a `Graph`.""" early_exit = agent.terminate_on_option_failure child_nodes = [render(option) for option in agent.child_policies()] edges = { subgraph.Edge(ENTRY_NODE, child_nodes[0]), subgraph.Edge(child_nodes[-1], EXIT_NODE), } for from_node, to_node in zip(child_nodes[:-1], child_nodes[1:]): if early_exit: edges.add(subgraph.Edge(from_node, to_node, SUCCESS_STR)) edges.add(subgraph.Edge(from_node, EXIT_NODE, FAILURE_STR)) edges.add(subgraph.Edge(from_node, EXIT_NODE, PREEMPTED_STR)) else: edges.add(subgraph.Edge(from_node, to_node)) nodes = {ENTRY_NODE, EXIT_NODE} nodes.update(child_nodes) return subgraph.Graph( agent.name, nodes=frozenset(nodes), edges=frozenset(edges)) def _concurrent_to_graph(agent: af.ConcurrentOption) -> subgraph.Graph: """Convert a `ConcurrentOption` to a `Graph`.""" child_nodes = [render(option) for option in agent.child_policies()] edges = set() for child_node in child_nodes: edges.add(subgraph.Edge(ENTRY_NODE, child_node)) edges.add(subgraph.Edge(child_node, EXIT_NODE)) nodes = {ENTRY_NODE, EXIT_NODE} nodes.update(child_nodes) return subgraph.Graph( agent.name, nodes=frozenset(nodes), edges=frozenset(edges)) def _sto_to_graph(agent: af.SubTaskOption) -> subgraph.Node: """Convert a `SubTaskOption` to a `Graph`.""" node_label = '{},{},{}'.format(agent.name or 'SubTask Option', agent.subtask.name or 'SubTask', agent.agent.name or 'Policy') return subgraph.Node(label=node_label, type='sub_task_option') def _cond_to_graph(agent: af.Cond) -> subgraph.Graph: condition_node = subgraph.Node(label='Condition', type='condition') true_node = render(agent.true_branch) false_node = render(agent.false_branch) return subgraph.Graph( agent.name, nodes=frozenset( [ENTRY_NODE, condition_node, true_node, false_node, EXIT_NODE]), edges=frozenset([ subgraph.Edge(ENTRY_NODE, condition_node), subgraph.Edge(condition_node, true_node, label='True'), subgraph.Edge(condition_node, false_node, label='False'), subgraph.Edge(true_node, EXIT_NODE), subgraph.Edge(false_node, EXIT_NODE) ])) def _delegate_to_graph(agent: af.DelegateOption) -> subgraph.Graph: delegate_node = render(agent.delegate) return subgraph.Graph( label=agent.name, nodes=frozenset({ENTRY_NODE, delegate_node, EXIT_NODE}), edges=frozenset({ subgraph.Edge(ENTRY_NODE, delegate_node), subgraph.Edge(delegate_node, EXIT_NODE) })) # Rendering methods for transforming agentflow nodes to graph-intermediates. _RENDER_FUNCS = { af.Repeat: _repeat_to_graph, af.While: _while_to_graph, af.Sequence: _sequence_to_graph, af.ConcurrentOption: _concurrent_to_graph, af.SubTaskOption: _sto_to_graph, af.Cond: _cond_to_graph, af.DelegateOption: _delegate_to_graph, }
dm_robotics-main
py/agentflow/rendering/intermediate.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """Module to convert subgraph Graphs into graphviz graphs for rendering.""" import itertools import os import tempfile from typing import Any, Callable, Dict, Iterable, Text, Type, Union from absl import logging from dm_robotics import agentflow as af from dm_robotics.agentflow.rendering import intermediate from dm_robotics.agentflow.rendering import subgraph import lxml from lxml.html import builder as E import pydot # Color names for HTML nodes. _BACKGROUND_COLOR = '#00000015' _SUBTASK_COLOR = '#00999925' _POLICY_COLOR = '#ffff0025' _SUBTASK_OPTION_COLOR = '#0000d015' def add_itermediate_renderer( node_type: Type[af.Policy], render_func: Callable[[Any], subgraph.Graph]) -> None: """Adds a custom renderer for the provided AgentFlow node type.""" intermediate.add_renderer(node_type, render_func) def render(graph: subgraph.Graph) -> Union[pydot.Graph]: """Render the subgraph as a graphviz graph.""" try: _validate_state_machine_graph(graph) except ValueError: logging.error('Invalid Graph: %s', graph) raise renderer = _RenderedGraph(graph, depth=0, namespace='') return renderer.graph def to_png(graph: Union[pydot.Dot, pydot.Subgraph]) -> Union[Text, bytes]: """Render a graphviz to a PNG.""" return graph.create_png(prog='dot') # pytype: disable=attribute-error def open_viewer(option: af.Policy) -> None: """Render a graphviz to a PNG and xdg-open it (Linux assumed). This is a simple entry point if you just want to get a graph on the screen. Args: option: The option (typed as policy) to render. """ graph = intermediate.render(option) if not isinstance(graph, subgraph.Graph): raise ValueError('policy is not composite.') graphviz_graph = render(graph) temp_dir = tempfile.mkdtemp() raw_filename = os.path.join(temp_dir, 'graph.dot') png_filename = os.path.join(temp_dir, 'graph.png') graphviz_graph.write_raw(raw_filename, prog='dot') # pytype: disable=attribute-error graphviz_graph.write_png(png_filename, prog='dot') # pytype: disable=attribute-error print('Rendered option {} to {} and {}'.format(option.name, raw_filename, png_filename)) os.system('xdg-open {}'.format(png_filename)) def _validate_state_machine_graph(graph: subgraph.Graph): """Validates assumptions about how subgraph.Graph is used.""" # Assumes the graph is acyclic. Otherwise this will overflow the stack. for node in graph.nodes: if isinstance(node, subgraph.Graph): _validate_state_machine_graph(node) # Every edge in the graph must start and end on a node in the graph. for edge in graph.edges: if edge.begin not in graph.nodes or edge.end not in graph.nodes: raise ValueError('Nodes of edge {} not in graph, nodes are: {}'.format( edge, [n.label for n in graph.nodes])) # There must be an entry node. if not any(edge.begin == intermediate.ENTRY_NODE for edge in graph.edges): raise ValueError('No edge from ENTRY_NODE') class _RenderedGraph(object): """Renderer for subgraph.Graph objects. This creates the graph and subgraphs recursively. Each node in the graph that is itself a subgraph.Graph is rendered with a _RenderedGraph and stored in self._subgraphs. """ def __init__(self, graph: subgraph.Graph, depth: int, namespace: Text): """Render the graph to a graphviz graph. Args: graph: A graph to convert. depth: The depth in the hierarchy, with 0 being top. namespace: A namespace to ensure name uniqueness between graphs. """ self._depth = depth self._namespace = namespace self._data_graph = graph self._graphviz_graph = self._create_graphviz_container( graph.label, depth, namespace) self._graphviz_nodes = {} # type: Dict[Text, pydot.Node] self._subgraphs = {} # type: Dict[Text, '_RenderedGraph'] # Add each node to the graphviz graph. for node in self._sorted_nodes(): if isinstance(node, subgraph.Graph): child = _RenderedGraph( node, depth=depth+1, namespace=self._namespaced(node.label)) self._subgraphs[node.label] = child self._graphviz_graph.add_subgraph(child.graph) else: if node == intermediate.ENTRY_NODE: graphviz_node = self._create_entry_viz_node() elif node == intermediate.EXIT_NODE: graphviz_node = self._create_exit_viz_node() elif node.type == 'sub_task_option': graphviz_node = self._create_sto_viz_node(node) else: graphviz_node = self._create_graphviz_node(node) self._graphviz_nodes[node.label] = graphviz_node self._graphviz_graph.add_node(graphviz_node) # Add edges between nodes, this is tricker because of subgraphs. for edge in self._data_graph.edges: self._graphviz_graph.add_edge(self._create_graphviz_edge(edge)) @property def graph(self) -> Union[pydot.Graph]: return self._graphviz_graph @property def entry_node(self) -> pydot.Node: return self._graphviz_nodes[intermediate.ENTRY_NODE.label] @property def exit_node(self) -> pydot.Node: return self._graphviz_nodes[intermediate.EXIT_NODE.label] def _sorted_nodes(self) -> Iterable[subgraph.Node]: """Returns all graph nodes, in a topologically sorted order.""" # Notes: # 1. The primary ordering is of nodes according to success transitions, # I.e. we will emit the nodes reachable from a success before those # reachable by failure. # 2. All nodes will be emitted, and it's possible for a node to be # detached from all other nodes. success = list( subgraph.topologically_sorted_nodes([ edge for edge in self._data_graph.edges if edge.type != intermediate.FAILURE_STR ])) failure = list( subgraph.topologically_sorted_nodes([ edge for edge in self._data_graph.edges if edge.type == intermediate.FAILURE_STR ])) failure = [node for node in failure if node not in success] floating = [ node for node in self._data_graph.nodes if node not in success and node not in failure ] return itertools.chain(success, failure, floating) def _create_graphviz_container( self, label: Text, depth: int, namespace: Text) -> Union[pydot.Dot, pydot.Subgraph]: """A 'container' is a top-level Dot object or a subgraph.""" # nodesep size is in inches if depth == 0: return pydot.Dot(compound=True, labeljust='l', nodesep=0.2, newrank=True) else: return pydot.Subgraph( 'cluster_{}'.format(namespace), bgcolor=_BACKGROUND_COLOR, color='black', label=label, shape='box', style='rounded') def _create_graphviz_node(self, node: subgraph.Node) -> pydot.Node: if node == intermediate.ENTRY_NODE: assert False, 'use _create_entry_viz_node' elif node == intermediate.EXIT_NODE: assert False, 'use _create_exit_viz_node' else: return pydot.Node( name=self._namespaced(node.label), label=node.label, shape='box', style='rounded' if node.type == 'option' else '') def _create_graphviz_edge(self, edge: subgraph.Edge) -> pydot.Edge: """Create an graphviz edge from a graph edge.""" begin_node, end_node = edge.begin, edge.end attrs = {'xlabel': edge.label, 'color': self._edge_color(edge)} # Edges to or from a subgraph are really edges to nodes in different # subgraphs. However, we want them to render as though they come from the # subgraph itself, not a node in that subgraph. # This is achieved by clipping to the cluster with lhead and ltail. # # Edges to and from the subgraph go via the ENTRY node rather # than to the ENTRY and from the EXIT. This allows graphs to be laid-out # more compactly. from_graph = isinstance(begin_node, subgraph.Graph) to_graph = isinstance(end_node, subgraph.Graph) if from_graph: child = self._subgraphs[begin_node.label] out_viz_node = child.exit_node # attrs['ltail'] = child.graph.get_name() # To hide edge under subgraph. else: out_viz_node = self._graphviz_nodes[begin_node.label] if to_graph: child = self._subgraphs[end_node.label] in_viz_node = child.entry_node # attrs['lhead'] = child.graph.get_name() # To hide edge under subgraph. else: in_viz_node = self._graphviz_nodes[end_node.label] # If an edge goes from one subgraph to another, then don't use that # edge to imply ranking. This results in more compact graphs. if from_graph and to_graph: attrs['constraint'] = False attrs['minlen'] = 2.0 # If this is a failure, don't use the edge to imply ranking. if edge.type == intermediate.FAILURE_STR: attrs['constraint'] = False return pydot.Edge(out_viz_node, in_viz_node, **attrs) def _create_entry_viz_node(self) -> pydot.Node: attrs = { 'label': '', 'shape': 'circle', 'style': 'filled', 'fillcolor': 'black', 'fixedsize': True, 'width': 0.2 } return pydot.Node(name=self._namespaced('ENTRY'), **attrs) def _create_exit_viz_node(self) -> pydot.Node: attrs = { 'label': '', 'shape': 'doublecircle', 'style': 'filled', 'fillcolor': 'black', 'fixedsize': True, 'width': 0.2 } return pydot.Node(name=self._namespaced('EXIT'), **attrs) def _create_sto_viz_node(self, node: subgraph.Node) -> pydot.Node: """Makes an HTML-style node for a SubTaskOption.""" agent_name, subtask_name, policy_name = node.label.split(',') # HTML styles below interpreted by graphviz-special, not vanilla HTML, see: # https://graphviz.org/doc/info/shapes.html#html table_element = E.TABLE( E.TR(E.TD(agent_name, BORDER='0', COLSPAN='2')), E.TR( E.TD( subtask_name, BORDER='1', STYLE='RADIAL', BGCOLOR=_SUBTASK_COLOR), E.TD( policy_name, BORDER='1', STYLE='RADIAL', BGCOLOR=_POLICY_COLOR), ), BORDER='1', STYLE='ROUNDED', BGCOLOR=_SUBTASK_OPTION_COLOR, CELLBORDER='1', CELLPADDING='3', CELLSPACING='5') table_str = lxml.etree.tostring(table_element) if isinstance(table_str, bytes): table_str = table_str.decode('utf-8') # lxml generates bytes in python3. html_str = '<{}>'.format(table_str) # Wrap with '<>' to designate HTML tag. attrs = { 'label': html_str, 'fontcolor': 'black', 'shape': 'plaintext', } return pydot.Node(name=self._namespaced(node.label), **attrs) def _namespaced(self, name: Text) -> Text: return '{}_{}'.format(self._namespace, name) def _edge_color(self, edge: subgraph.Edge): """Returns edge color string according to edge type.""" if not edge.type: return 'black' elif edge.type == intermediate.SUCCESS_STR: return 'green' elif edge.type == intermediate.FAILURE_STR: return 'red' elif edge.type == intermediate.PREEMPTED_STR: return 'yellow' else: logging.warning('Unknown edge type: %s', edge.type) return 'purple'
dm_robotics-main
py/agentflow/rendering/graphviz_renderer.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """Test for Subgraph.""" import random from absl import logging from absl.testing import absltest from dm_robotics.agentflow import testing_functions from dm_robotics.agentflow.rendering import subgraph class SubgraphTest(absltest.TestCase): def test_construction(self): node1 = subgraph.Node(testing_functions.random_string()) node2 = subgraph.Node(testing_functions.random_string()) nodes = {node1, node2} edges = { subgraph.Edge(node1, node2), subgraph.Edge(node2, node1), } graph = subgraph.Graph( testing_functions.random_string(), nodes=nodes, edges=edges) # That's the test, this constructor should work self.assertIsNotNone(graph) self.assertLen(graph.nodes, 2) self.assertLen(graph.edges, 2) def test_hashable(self): # This is important, we don't want hashing to break. def create_graph(graph_name, node1_name, node2_name): node1 = subgraph.Node(node1_name) node2 = subgraph.Node(node2_name) nodes = {node1, node2} edges = { subgraph.Edge(node1, node2), subgraph.Edge(node2, node1), } return subgraph.Graph( graph_name, nodes=frozenset(nodes), edges=frozenset(edges)) graph_name = testing_functions.random_string() name1 = testing_functions.random_string() name2 = testing_functions.random_string() graph1 = create_graph(graph_name, name1, name2) graph2 = create_graph(graph_name, name1, name2) self.assertIsNot(graph1, graph2) self.assertEqual(graph1, graph2) self.assertEqual(hash(graph1), hash(graph2)) def test_topological_sort_no_loop(self): node1 = subgraph.Node(testing_functions.random_string()) node2 = subgraph.Node(testing_functions.random_string()) node3 = subgraph.Node(testing_functions.random_string()) # Edges, unsorted, graph is: ENTRY -> node1 -> node2 -> node3 -> EXIT edges = [ subgraph.Edge(node1, node2), subgraph.Edge(node2, node3), ] sorted_nodes = list(subgraph.topologically_sorted_nodes(edges)) self.assertEqual(sorted_nodes, [node1, node2, node3]) def test_topological_sort_with_loop(self): node1 = subgraph.Node(testing_functions.random_string()) node2 = subgraph.Node(testing_functions.random_string()) node3 = subgraph.Node(testing_functions.random_string()) # ENTRY node1 -> node2 <--> node3 -> EXIT I.e. Loop between node 2 and 3 edges = [ subgraph.Edge(node1, node2), subgraph.Edge(node2, node3), subgraph.Edge(node3, node2), ] random.shuffle(edges) sorted_nodes = list(subgraph.topologically_sorted_nodes(edges)) order1 = [node1, node2, node3] order2 = [node1, node3, node2] if sorted_nodes != order1 and sorted_nodes != order2: logging.info('order1: %s', order1) logging.info('order2: %s', order2) logging.info('sorted_nodes: %s', sorted_nodes) self.fail('bad sort order, see log.') if __name__ == '__main__': absltest.main()
dm_robotics-main
py/agentflow/rendering/subgraph_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """Test for Intermediate.""" from typing import Mapping, Optional, Text, Tuple from absl.testing import absltest import dm_env from dm_env import specs from dm_robotics import agentflow as af from dm_robotics.agentflow import testing_functions from dm_robotics.agentflow.rendering import intermediate from dm_robotics.agentflow.rendering import subgraph import numpy as np ENTRY = intermediate.ENTRY_NODE EXIT = intermediate.EXIT_NODE class TestSubTask(af.SubTask): """A test subtask.""" def __init__(self, base_obs_spec: Mapping[Text, specs.Array], name: Optional[Text] = None): super().__init__(name) self._base_obs_spec = base_obs_spec def observation_spec(self) -> Mapping[Text, specs.Array]: return self._base_obs_spec def arg_spec(self) -> Optional[specs.Array]: return def action_spec(self) -> specs.Array: return specs.BoundedArray( shape=(2,), dtype=np.float32, minimum=0., maximum=1., name='dummy_act') def agent_to_parent_action(self, agent_action: np.ndarray) -> np.ndarray: return np.hstack((agent_action, np.zeros(2))) # Return full action. def parent_to_agent_timestep(self, parent_timestep: dm_env.TimeStep, arg_key: Text) -> Tuple[dm_env.TimeStep, float]: return (parent_timestep, 1.0) def pterm(self, parent_timestep: dm_env.TimeStep, own_arg_key: Text) -> float: del parent_timestep, own_arg_key return 0.0 class TestPolicy(af.Policy): """A test policy.""" def __init__(self, action_spec: specs.Array, unused_observation_spec: Mapping[Text, specs.Array], name: Optional[Text] = None): super().__init__(name) self._action_spec = action_spec def step(self, timestep: dm_env.TimeStep) -> np.ndarray: return np.random.rand(self._action_spec.shape[0]) def test_subtask(name: Text): return TestSubTask( base_obs_spec={'foo': specs.Array(dtype=np.float32, shape=(2,))}, name=name) def test_policy(name: Text): return TestPolicy( specs.Array(dtype=np.float32, shape=(2,)), {'foo': specs.Array(dtype=np.float32, shape=(2,))}, name=name) class TestDelegateOption(af.DelegateOption): def step(self, timestep): return np.arange(2) class IntermediateTest(absltest.TestCase): def test_atomic(self): """Simple atomic options should become nodes.""" option = testing_functions.atomic_option_with_name('The Label') graph = intermediate.render(option) self.assertIsInstance(graph, subgraph.Node) self.assertNotIsInstance(graph, subgraph.Graph) self.assertEqual(graph, subgraph.Node(label='The Label', type='option')) def test_while(self): """A while loop should become a subgraph with a condition 'option'.""" inner_option = testing_functions.atomic_option_with_name('Inner') loop = af.While(lambda x: True, inner_option, name='Loop') graph = intermediate.render(loop) self.assertIsInstance(graph, subgraph.Graph) cond_node = subgraph.Node(label='Condition', type='condition') inner_node = subgraph.Node(label='Inner', type='option') self.assertEqual( graph, subgraph.Graph( label='Loop', nodes=frozenset({ENTRY, cond_node, inner_node, EXIT}), edges=frozenset({ subgraph.Edge(ENTRY, cond_node), subgraph.Edge(cond_node, inner_node, label='True'), subgraph.Edge(cond_node, EXIT, label='False'), subgraph.Edge(inner_node, cond_node, label='While'), }))) def test_repeat(self): """Repeat is a special while loop.""" # The condition is the number of iterations, so we can avoid two nodes in # the subgraph by labelling the return arc. num_iter = 3 inner_option = testing_functions.atomic_option_with_name('Inner') loop = af.Repeat(num_iter, inner_option, name='Loop') graph = intermediate.render(loop) inner_node = subgraph.Node(label='Inner', type='option') expected_graph = subgraph.Graph( label='Loop', nodes=frozenset({ENTRY, inner_node, EXIT}), edges=frozenset({ subgraph.Edge(ENTRY, inner_node, label=''), subgraph.Edge(inner_node, inner_node, label='3 times'), subgraph.Edge(inner_node, EXIT, label=''), })) self.assertEqual(graph, expected_graph) def test_sequence(self): o1 = testing_functions.atomic_option_with_name('o1') o2 = testing_functions.atomic_option_with_name('o2') o3 = testing_functions.atomic_option_with_name('o3') seq = af.Sequence([o1, o2, o3], terminate_on_option_failure=False, name='Sequence Name') node1 = subgraph.Node(label='o1', type='option') node2 = subgraph.Node(label='o2', type='option') node3 = subgraph.Node(label='o3', type='option') edges = { subgraph.Edge(ENTRY, node1), subgraph.Edge(node1, node2), subgraph.Edge(node2, node3), subgraph.Edge(node3, EXIT) } nodes = {ENTRY, node1, node2, node3, EXIT} expected_graph = subgraph.Graph( 'Sequence Name', nodes=frozenset(nodes), edges=frozenset(edges)) actual_graph = intermediate.render(seq) self.assertEqual(actual_graph, expected_graph) def test_sequence_early_exit(self): # When a sequence has an early exit (terminate_on_option_failure=True), # then a failure of any option in the sequence results in failure (exit) # of the whole sequence, therefore there are failure edges from every # option to the exit option (except for the last option which results in # the option ending whether or not it fails). # o1 = testing_functions.atomic_option_with_name('o1') o2 = testing_functions.atomic_option_with_name('o2') o3 = testing_functions.atomic_option_with_name('o3') seq = af.Sequence([o1, o2, o3], terminate_on_option_failure=True, name='Sequence Name') node1 = subgraph.Node(label='o1', type='option') node2 = subgraph.Node(label='o2', type='option') node3 = subgraph.Node(label='o3', type='option') edges = { subgraph.Edge(ENTRY, node1), subgraph.Edge(node1, node2, intermediate.SUCCESS_STR), subgraph.Edge(node1, EXIT, intermediate.FAILURE_STR), subgraph.Edge(node1, EXIT, intermediate.PREEMPTED_STR), subgraph.Edge(node2, node3, intermediate.SUCCESS_STR), subgraph.Edge(node2, EXIT, intermediate.FAILURE_STR), subgraph.Edge(node2, EXIT, intermediate.PREEMPTED_STR), subgraph.Edge(node3, EXIT) } nodes = {ENTRY, node1, node2, node3, EXIT} expected_graph = subgraph.Graph( 'Sequence Name', nodes=frozenset(nodes), edges=frozenset(edges)) actual_graph = intermediate.render(seq) self.assertEqual(actual_graph, expected_graph) def test_concurrent(self): action_size = 2 o1 = testing_functions.atomic_option_with_name('o1', action_size) o2 = testing_functions.atomic_option_with_name('o2', action_size) o3 = testing_functions.atomic_option_with_name('o3', action_size) seq = af.ConcurrentOption([o1, o2, o3], action_spec=specs.Array( shape=(action_size,), dtype=np.float64), name='Concurrent Name') node1 = subgraph.Node(label='o1', type='option') node2 = subgraph.Node(label='o2', type='option') node3 = subgraph.Node(label='o3', type='option') edges = { subgraph.Edge(ENTRY, node1), subgraph.Edge(ENTRY, node2), subgraph.Edge(ENTRY, node3), subgraph.Edge(node1, EXIT), subgraph.Edge(node2, EXIT), subgraph.Edge(node3, EXIT) } nodes = {ENTRY, node1, node2, node3, EXIT} expected_graph = subgraph.Graph( 'Concurrent Name', nodes=frozenset(nodes), edges=frozenset(edges)) actual_graph = intermediate.render(seq) print(expected_graph) print(actual_graph) self.assertEqual(actual_graph, expected_graph) def test_subtask_option(self): # Nodes of type 'sub_task_option' should have a label that is a comma- # separated list of `agent_name`, `subtask_name`, and `policy_name`. subtask_name = 'test_subtask' policy_name = 'test_policy' agent_name = 'Test SubTask Option' subtask = test_subtask(subtask_name) policy = test_policy(policy_name) op = af.SubTaskOption(subtask, policy, name=agent_name) actual_graph = intermediate.render(op) expected_graph = subgraph.Node( label=','.join([agent_name, subtask_name, policy_name]), type='sub_task_option') print(expected_graph) print(actual_graph) self.assertEqual(actual_graph, expected_graph) def test_cond(self): # Conditions have a true and false branch. # The subgraph is represented as: # entry --> condition # +----- TRUE ----> [ true option ] -----+ # | | # +----- FALSE ---> [ false option ] ----+ # | # exit # I.e. 5 nodes and 5 edges: cond = lambda ts, res: True true_option = testing_functions.atomic_option_with_name('TrueOption') false_option = testing_functions.atomic_option_with_name('FalseOption') option = af.Cond(cond, true_option, false_option, name='Conditional') cond_node = subgraph.Node(label='Condition', type='condition') true_node = subgraph.Node(label='TrueOption', type='option') false_node = subgraph.Node(label='FalseOption', type='option') expected_graph = subgraph.Graph( label='Conditional', nodes=frozenset([ENTRY, cond_node, true_node, false_node, EXIT]), edges=frozenset([ subgraph.Edge(ENTRY, cond_node), subgraph.Edge(cond_node, true_node, label='True'), subgraph.Edge(cond_node, false_node, label='False'), subgraph.Edge(true_node, EXIT), subgraph.Edge(false_node, EXIT), ])) actual_graph = intermediate.render(option) self.assertEqual(actual_graph, expected_graph) def test_delegate(self): """Test DelegateOption subclasses.""" # We have a number of DelegateOptions, this test uses a test-only subclass # to ensure that even if the common subclasses are handled specially, that # all DelegateOption instances render. delegate_option = testing_functions.atomic_option_with_name('Bottom') option = TestDelegateOption(delegate_option, name='Delegator') actual_graph = intermediate.render(option) self.assertIsInstance(actual_graph, subgraph.Graph) bottom_node = subgraph.Node(label='Bottom', type='option') expected_graph = subgraph.Graph( label='Delegator', nodes=frozenset({ENTRY, bottom_node, EXIT}), edges=frozenset({ subgraph.Edge(ENTRY, bottom_node), subgraph.Edge(bottom_node, EXIT) })) self.assertEqual(actual_graph, expected_graph) def test_subgraph_in_graph(self): """Test that rendering is recursive for options.""" o1 = testing_functions.atomic_option_with_name('seq_o1') o2 = testing_functions.atomic_option_with_name('seq_o2') seq = af.Sequence([o1, o2], terminate_on_option_failure=False, name='Sequence') option = TestDelegateOption(delegate=seq, name='Delegator') # option delegates to a sequence. # option is rendered as a graph, and so is sequence. # This means we should have a graph in a graph. # Construct the expected graph (inner graph first). inner_node1 = subgraph.Node(label='seq_o1', type='option') inner_node2 = subgraph.Node(label='seq_o2', type='option') inner_graph = subgraph.Graph( 'Sequence', nodes=frozenset({ENTRY, inner_node1, inner_node2, EXIT}), edges=frozenset({ subgraph.Edge(ENTRY, inner_node1), subgraph.Edge(inner_node1, inner_node2), subgraph.Edge(inner_node2, EXIT), })) expected_graph = subgraph.Graph( 'Delegator', nodes=frozenset({ENTRY, inner_graph, EXIT}), edges=frozenset({ subgraph.Edge(ENTRY, inner_graph), subgraph.Edge(inner_graph, EXIT) })) actual_graph = intermediate.render(option) self.assertEqual(actual_graph, expected_graph) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/agentflow/rendering/intermediate_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """Module for rendering AgentFlow agents.""" import collections import sys from typing import FrozenSet, Iterable, Optional, Text import attr @attr.s(frozen=True) class Node(object): label = attr.ib(type=Text) type = attr.ib(type=Text, default='') @attr.s(frozen=True) class Edge(object): begin = attr.ib(type=Node) end = attr.ib(type=Node) label = attr.ib(type=Text, default='') type = attr.ib(type=Text, default='') @attr.s(frozen=True) class Graph(Node): """An graph (vertices and edges) which may be a vertex in another graph.""" nodes = attr.ib(type=FrozenSet[Node], default=attr.Factory(frozenset)) edges = attr.ib(type=FrozenSet[Edge], default=attr.Factory(frozenset)) def topologically_sorted_nodes(edges: Iterable[Edge]) -> Iterable[Node]: """Yields the nodes in topologically sorted order. The edges may contain cycles, the order of nodes in a cycle is chosen arbitrarily. Args: edges: Edges between nodes to sort. """ # Map of Node -> incoming (non-negative) edge count incoming_count = collections.defaultdict(int) # Dict[Node, int] for edge in edges: incoming_count[edge.begin] += 0 # ensure all nodes are included. incoming_count[edge.end] += 1 while incoming_count: low_count = sys.maxsize lowest = None # type: Optional[Node] # Find next node with lowest incoming node count (can be > 0 if there are # loops) for node, in_count in incoming_count.items(): if in_count < low_count: lowest = node low_count = in_count elif in_count == low_count: # in the case of loops or multiple entry points, tie-break by label. assert lowest if node.label < lowest.label: lowest = node assert lowest yield lowest # Remove this node from the incoming count dict del incoming_count[lowest] # Reduce in-count of remaining nodes that the `lowest` node points to. for edge in edges: if edge.begin == lowest and edge.end in incoming_count: incoming_count[edge.end] -= 1
dm_robotics-main
py/agentflow/rendering/subgraph.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """Test for GraphvizRenderer.""" import random import re from typing import Iterable, Sequence, Text from absl import logging from absl.testing import absltest from dm_robotics.agentflow import testing_functions from dm_robotics.agentflow.rendering import graphviz_renderer from dm_robotics.agentflow.rendering import intermediate from dm_robotics.agentflow.rendering import subgraph import pydot _TEST_EDGE_HIDING = False ENTRY = intermediate.ENTRY_NODE EXIT = intermediate.EXIT_NODE class GraphvizRendererTest(absltest.TestCase): def test_render_flat_graph(self): # render a very simple graph, check for all nodes and edges. node1 = subgraph.Node(label='node1', type='option') graph = subgraph.Graph( label='graph1', nodes=frozenset({ENTRY, node1, EXIT}), edges=frozenset({ subgraph.Edge(ENTRY, node1), subgraph.Edge(node1, EXIT), })) graphviz_graph = graphviz_renderer.render(graph) logging.info('graphviz source: %s', graphviz_graph.to_string()) nodes = graphviz_graph.get_node_list() self.assertNames(nodes, ['_ENTRY', '_node1', '_EXIT']) edges = graphviz_graph.get_edge_list() self.assertLen(edges, 2) self.assertEdge(edges, '_ENTRY', '_node1') self.assertEdge(edges, '_node1', '_EXIT') def test_render_subtask_option(self): # render a subtask option, check shape and HTML-label. agent_name = 'agent' subtask_name = 'subtask' policy_name = 'policy' node1 = subgraph.Node( label=','.join([agent_name, subtask_name, policy_name]), type='sub_task_option') graph = subgraph.Graph( label='graph1', nodes=frozenset({ENTRY, node1, EXIT}), edges=frozenset({ subgraph.Edge(ENTRY, node1), subgraph.Edge(node1, EXIT), })) graphviz_graph = graphviz_renderer.render(graph) logging.info('graphviz source: %s', graphviz_graph.to_string()) nodes = graphviz_graph.get_node_list() expected_name = ('_' + # for namespace. ','.join([agent_name, subtask_name, policy_name])) self.assertNames(nodes, ['_ENTRY', expected_name, '_EXIT']) self.assertNode( nodes, expected_name, shape='plaintext', label=re.compile('<.*.>') # tests for an HTML-style label. ) def test_top_graph_attributes(self): graph = subgraph.Graph( label='graph1', nodes=frozenset({ENTRY, EXIT}), edges=frozenset({ subgraph.Edge(ENTRY, EXIT), })) graphviz_graph = graphviz_renderer.render(graph) self.assertTrue(graphviz_graph.get('compound')) self.assertTrue(graphviz_graph.get('newrank')) def test_entry_and_exit_nodes(self): graph = subgraph.Graph( label='graph1', nodes=frozenset({ENTRY, EXIT}), edges=frozenset({ subgraph.Edge(ENTRY, EXIT), })) graphviz_graph = graphviz_renderer.render(graph) entry_node = self._get_node(graphviz_graph, ENTRY) self.assertEqual(entry_node.get('shape'), 'circle') self.assertEqual(entry_node.get('style'), 'filled') self.assertEqual(entry_node.get('fillcolor'), 'black') exit_node = self._get_node(graphviz_graph, EXIT) self.assertEqual(exit_node.get('shape'), 'doublecircle') self.assertEqual(exit_node.get('style'), 'filled') self.assertEqual(exit_node.get('fillcolor'), 'black') def test_failure_edges(self): node1 = subgraph.Node(label=testing_functions.random_string(5)) graph = subgraph.Graph( label='graph1', nodes=frozenset({ENTRY, node1, EXIT}), edges=frozenset({ subgraph.Edge(ENTRY, node1, type=intermediate.FAILURE_STR), subgraph.Edge(node1, EXIT), })) graphviz_graph = graphviz_renderer.render(graph) entry_node1_edge = self._get_edge(graphviz_graph, ENTRY, node1) self.assertIn('constraint', entry_node1_edge.get_attributes()) self.assertFalse(entry_node1_edge.get('constraint')) def test_topologically_sorted_nodes(self): # Dot attempts to put nodes in the order they appear in the source file, # emitting them in a topologically sorted order means that the rendering # is better and more consistent. # This is tested by generating some sequences with randomly named nodes # and checking that the order in the file is not random but is ordered. for _ in range(10): node1 = subgraph.Node(label=testing_functions.random_string(5)) node2 = subgraph.Node(label=testing_functions.random_string(5)) node3 = subgraph.Node(label=testing_functions.random_string(5)) nodes = [ENTRY, node1, node2, node3, EXIT] edges = [ subgraph.Edge(nodes[0], nodes[1]), subgraph.Edge(nodes[1], nodes[2]), subgraph.Edge(nodes[2], nodes[3]), subgraph.Edge(nodes[3], nodes[4]) ] random.shuffle(nodes) random.shuffle(edges) graph = subgraph.Graph( label='graph', nodes=frozenset(nodes), edges=frozenset(edges)) graphviz_graph = graphviz_renderer.render(graph) logging.info('graphviz_graph\n%s\n', graphviz_graph.to_string()) entry_num = self._get_node(graphviz_graph, ENTRY).get_sequence() node1_num = self._get_node(graphviz_graph, node1).get_sequence() node2_num = self._get_node(graphviz_graph, node2).get_sequence() node3_num = self._get_node(graphviz_graph, node3).get_sequence() exit_num = self._get_node(graphviz_graph, EXIT).get_sequence() self.assertGreater(node1_num, entry_num) self.assertGreater(node2_num, node1_num) self.assertGreater(node3_num, node2_num) self.assertGreater(exit_num, node3_num) def test_graph_with_no_exit(self): # Dot attempts to put nodes in the order they appear in the source file, # emitting them in a topologically sorted order means that the rendering # is better and more consistent. # This is tested by generating some sequences with randomly named nodes # and checking that the order in the file is not random but is ordered. node1 = subgraph.Node(label='node1') node2 = subgraph.Node(label='node2') nodes = [ENTRY, node1, node2] edges = [ subgraph.Edge(nodes[0], nodes[1]), subgraph.Edge(nodes[1], nodes[2]) ] graph = subgraph.Graph( label='graph', nodes=frozenset(nodes), edges=frozenset(edges)) graphviz_graph = graphviz_renderer.render(graph) nodes = graphviz_graph.get_node_list() self.assertNames(nodes, ['_ENTRY', '_node1', '_node2']) edges = graphviz_graph.get_edge_list() self.assertLen(edges, 2) self.assertEdge(edges, '_ENTRY', '_node1') self.assertEdge(edges, '_node1', '_node2') def test_subgraph(self): inner_graph = subgraph.Graph( label='inner_graph', nodes=frozenset({ENTRY, EXIT}), edges=frozenset({ subgraph.Edge(ENTRY, EXIT), })) top_graph = subgraph.Graph( label='top_graph', nodes=frozenset({ENTRY, inner_graph, EXIT}), edges=frozenset({ subgraph.Edge(ENTRY, inner_graph), subgraph.Edge(inner_graph, EXIT), })) graphviz_graph = graphviz_renderer.render(top_graph) # compound must be set for subgraphs to work. self.assertTrue(graphviz_graph.get('compound')) nodes = graphviz_graph.get_nodes() subgraphs = graphviz_graph.get_subgraph_list() self.assertNames(nodes, ['_ENTRY', '_EXIT']) # The name is significant, it must start with cluster_ self.assertNames(subgraphs, ['cluster__inner_graph']) # Edges to/from a subgraph should have have lhead/ltail set respectively. # This makes the edge end/start on the subgraph rather than node in it. # Moreover, the node in the subgraph that's used for these edges is # always the entry node. I.e. edges to and from the entry node. if _TEST_EDGE_HIDING: edges = graphviz_graph.get_edge_list() self.assertEdge( edges, '_ENTRY', '_inner_graph_ENTRY', lhead='cluster__inner_graph') self.assertEdge( edges, '_inner_graph_ENTRY', '_EXIT', ltail='cluster__inner_graph') def assertEdge(self, edges: Iterable[pydot.Edge], source: Text, destination: Text, **attributes): found = False matched = False for edge in edges: if edge.get_source() == source and edge.get_destination() == destination: found = True # check attributes. for key, value in attributes.items(): if edge.get(key) != value: self.fail( 'Edge from {} to {} has attributes: {}, but expected {} = {}' .format(source, destination, attributes, key, value)) matched = True if not found: self.fail('No edge from {} to {} found. All edges: {}'.format( source, destination, [(e.get_source, e.get_destination()) for e in edges])) if not matched: self.fail( 'Edge from {} to {} found, but attributes did not match: {}'.format( source, destination, attributes)) def assertNode(self, nodes: Iterable[pydot.Node], name: Text, **attributes): found = False matched = False for node in nodes: if node.get_name() == name: found = True # check attributes. for key, value in attributes.items(): try: is_regex = isinstance(value, re._pattern_type) except AttributeError: is_regex = isinstance(value, re.Pattern) if is_regex: matched = re.search(value, node.get(key)) is not None else: matched = node.get(key) == value if not matched: self.fail('Node {} has attributes: {}, but expected {} = {}'.format( name, attributes, key, value)) matched = True if not found: self.fail('No node {} found. All nodes: {}'.format( name, [(n.get_name()) for n in nodes])) if not matched: self.fail('Node {} found, but attributes did not match: {}'.format( name, attributes)) def assertNames(self, nodes: Iterable[pydot.Common], expected: Sequence[Text]): actual = set((node.get_name() for node in nodes)) expected = set(expected) self.assertEqual(actual, expected) def _get_node(self, graphviz_graph: pydot.Graph, data_node: subgraph.Node) -> pydot.Node: node_name = self._graphviz_node_name(data_node) matches = graphviz_graph.get_node(node_name) if not matches: raise AssertionError('No node named: {}. Names: {}'.format( node_name, [node.get_name() for node in graphviz_graph.get_node_list()])) if len(matches) > 1: raise AssertionError('Multiple nodes named: {}. Names: {}'.format( node_name, [node.get_name() for node in graphviz_graph.get_node_list()])) return matches[0] def _graphviz_node_name(self, data_node: subgraph.Node): if data_node == ENTRY: return '_ENTRY' elif data_node == EXIT: return '_EXIT' else: return '_{}'.format(data_node.label) def _get_edge(self, graphviz_graph: pydot.Graph, begin: subgraph.Node, end: subgraph.Node) -> pydot.Edge: begin_name = self._graphviz_node_name(begin) end_name = self._graphviz_node_name(end) edges = graphviz_graph.get_edge(begin_name, end_name) if len(edges) == 1: return edges[0] else: raise AssertionError( 'Expected to find one edge from {} to {}, but got: {}'.format( begin_name, end_name, len(edges))) class GraphvizValidationTest(absltest.TestCase): def test_invalid_edge_nodes(self): node1 = subgraph.Node(testing_functions.random_string()) node2 = subgraph.Node(testing_functions.random_string()) node3 = subgraph.Node(testing_functions.random_string()) edges = { subgraph.Edge(node1, node2), subgraph.Edge(node2, node3), # node3 not in graph. subgraph.Edge(ENTRY, node1), subgraph.Edge(node2, EXIT) } # Because edge2 is node2 -> node3 and node3 is not in the graph, this # graph is invalid and should not be instantiable. try: graph = subgraph.Graph( testing_functions.random_string(), nodes={ENTRY, node1, node2, node3, EXIT}, edges=edges) graphviz_renderer.render(graph) except ValueError as expected: del expected def test_invalid_no_edge_from_entry(self): node1 = subgraph.Node(testing_functions.random_string()) node2 = subgraph.Node(testing_functions.random_string()) node3 = subgraph.Node(testing_functions.random_string()) edges = {subgraph.Edge(node1, node2), subgraph.Edge(node2, EXIT)} try: graph = subgraph.Graph( testing_functions.random_string(), nodes={ENTRY, node1, node2, node3, EXIT}, edges=edges) graphviz_renderer.render(graph) except ValueError as expected: del expected def test_valid_no_edge_to_exit(self): node1 = subgraph.Node(testing_functions.random_string()) node2 = subgraph.Node(testing_functions.random_string()) node3 = subgraph.Node(testing_functions.random_string()) edges = { subgraph.Edge(ENTRY, node1), subgraph.Edge(node1, node2), } # An option that never terminates is valid. graph = subgraph.Graph( testing_functions.random_string(), nodes={ENTRY, node1, node2, node3, EXIT}, edges=edges) graphviz_renderer.render(graph) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/agentflow/rendering/graphviz_renderer_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module for scene composers for the insertion task.""" import dataclasses from typing import Callable, Iterable, Tuple from dm_control import composer from dm_control import mjcf from dm_control.composer.initializers import prop_initializer from dm_robotics.geometry import geometry from dm_robotics.geometry import mujoco_physics from dm_robotics.moma import initializer as base_initializer import numpy as np PropPlacer = prop_initializer.PropPlacer @dataclasses.dataclass class TaskEntitiesInitializer(base_initializer.Initializer): """An initializer composed of other initializers.""" initializers: Iterable[composer.Initializer] def __call__(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> bool: """Runs initializers sequentially, until all done or one fails.""" for initializer in self.initializers: # pylint: disable=singleton-comparison,g-explicit-bool-comparison # Explicitly check for false because an initializer returning `None` # should be counted as success. if initializer(physics, random_state) == False: return False # pylint: enable=singleton-comparison,g-explicit-bool-comparison return True NO_INIT = TaskEntitiesInitializer(initializers=tuple()) @dataclasses.dataclass class PoseInitializer(base_initializer.Initializer): """Initialize entity pose. This can be used to initialize things like entities that are attached to a scene with a free joint. Attributes: initializer_fn: A function that will initialize the pose of an entity, the array arguments passed are pos and quat. pose_sampler: A function that will provide a new pos and quat on each invocation, to pass to the `initializer_fn`. """ initializer_fn: Callable[[mjcf.Physics, np.ndarray, np.ndarray], None] pose_sampler: Callable[[np.random.RandomState, geometry.Physics], Tuple[np.ndarray, np.ndarray]] def __call__(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> bool: pos, quat = self.pose_sampler(random_state, mujoco_physics.wrap(physics)) self.initializer_fn(physics, pos, quat) return True @dataclasses.dataclass class JointsInitializer(base_initializer.Initializer): """Initialize joint angles. This can be used to initialize things like robot arm joint angles. Attributes: initializer_fn: A function that will set joint angles. pose_sampler: A function that will provide new joint angles on each invocation, to pass to the `initializer_fn`. """ initializer_fn: Callable[[mjcf.Physics, np.ndarray], None] joints_sampler: Callable[[np.random.RandomState, geometry.Physics], np.ndarray] def __call__(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> bool: joint_angles = self.joints_sampler(random_state, mujoco_physics.wrap(physics)) self.initializer_fn(physics, joint_angles) return True @dataclasses.dataclass class CallableInitializer(base_initializer.Initializer): """An initializer composed of a single callable.""" initializer: Callable[[mjcf.Physics, np.random.RandomState], None] def __call__(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> bool: """Invokes the initializer.""" self.initializer(physics, random_state) return True
dm_robotics-main
py/moma/entity_initializer.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Abstract sensor interface definition .""" import abc import enum from typing import Dict, TypeVar, Generic from dm_control import mjcf from dm_control.composer.observation import observable import numpy as np EnumBound = TypeVar('EnumBound', bound=enum.Enum) class Sensor(abc.ABC, Generic[EnumBound]): """Abstract sensor interface, sensors generate observations. `Sensor`s. have `observables`, it is these objects that supply sensed values. At its simplest, an Observable is a callable that takes a physics and returns a sensed value (which could be a `np.ndarray`). The instances returned by observables are stored and used by the composer environment to create the environment's observations (state). """ def initialize_for_task(self, control_timestep_seconds: float, physics_timestep_seconds: float, physics_steps_per_control_step: int): """Setup the sensor for this task. Called before the base environment is setup. A sensor may need to know the control or physics frequencies to function correctly. This method is a place to determine these things. Args: control_timestep_seconds: How many seconds there are between control timesteps, where the actuators can change control signals. physics_timestep_seconds: How many seconds there are between simulation step. physics_steps_per_control_step: Number of physics steps for every control timestep. (`control_timestep_seconds` / `physics_timestep_seconds`) """ def close(self): """Clean up after we are done using the sensor. Called to clean up when we are done using the sensor. This is mainly used for real sensors that might need to close all the connections to the robot. """ def after_compile(self, mjcf_model: mjcf.RootElement, physics: mjcf.Physics) -> None: """Method called after the MJCF model has been compiled and finalized. Args: mjcf_model: The root element of the scene MJCF model. physics: Compiled physics. """ @abc.abstractmethod def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: """Called on a new episode, after the environment has been reset. This is called before the agent has got a timestep in the episode that is about to start. Sensors can reset any state they may have. Args: physics: The MuJoCo physics the environment uses. random_state: A PRNG seed. """ @property @abc.abstractmethod def observables(self) -> Dict[str, observable.Observable]: """Get the observables for this Sensor. This will be called after `initialize_for_task`. It's expected that the keys in this dict are values from `self.get_obs_key(SOME_ENUM_VALUE)`, the values are Observables. See the class docstring for more information about Observable. subclassing `dm_control.composer.observation.observable.Generic` is a simple way to create an `Observable`. Observables have many properties that are used by composer to alter how the values it produces are processed. See the code `dm_control.composer.observation` for more information. """ @property @abc.abstractmethod def name(self) -> str: pass @abc.abstractmethod def get_obs_key(self, obs: EnumBound) -> str: """Returns the key to an observable provided by this sensor."""
dm_robotics-main
py/moma/sensor.py
# Copyright 2022 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 manual test runner that runs each test file in a separate process. This is needed because there is global state in spec_utils used to switch off validation after some time (for performance on real robots). This automatic switch-off causes the validation test to fail because validation is switched off when it comes to run, unless each test starts in a new process. """ import os import subprocess import sys _MODULE = "dm_robotics.moma" _EXCLUDED_PATHS = ["build", "./build", ".tox", "./.tox", "venv", "./venv"] def test_file_paths(top_dir): """Yields the path to the test files in the given directory.""" def excluded_path(name): return any(name.startswith(path) for path in _EXCLUDED_PATHS) for dirpath, dirnames, filenames in os.walk(top_dir): # do not search tox or other hidden directories: remove_indexes = [ i for i, name in enumerate(dirnames) if excluded_path(name) ] for index in reversed(remove_indexes): del dirnames[index] for filename in filenames: if filename.endswith("test.py"): yield os.path.join(dirpath, filename) def module_name_from_file_path(pathname): # dirname will be like: "./file.py", "./dir/file.py" or "./dir1/dir2/file.py" # convert this to a module.name: submodule_name = pathname.replace("./", "").replace("/", ".")[0:-3] return _MODULE + "." + submodule_name def run_test(test_module_name): return subprocess.call([sys.executable, "-m", test_module_name]) == 0 if __name__ == "__main__": dir_to_search = sys.argv[1] success = True for test_path in test_file_paths(dir_to_search): module_name = module_name_from_file_path(test_path) success &= run_test(module_name) sys.exit(0 if success else 1)
dm_robotics-main
py/moma/run_tests.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 classes for props.""" from dm_control import composer from dm_control import mjcf from dm_robotics.transformations import transformations as tr import numpy as np class Prop(composer.Entity): """Base class for MOMA props.""" def _build(self, name: str, mjcf_root: mjcf.RootElement, prop_root: str = 'prop_root'): """Base constructor for props. This constructor sets up the common observables and element access properties. Args: name: The unique name of this prop. mjcf_root: (mjcf.Element) The root element of the MJCF model. prop_root: (string) Name of the prop root body MJCF element. Raises: ValueError: If the model does not contain the necessary elements. """ self._name = name self._mjcf_root = mjcf_root self._prop_root = mjcf_root.find('body', prop_root) # type: mjcf.Element if self._prop_root is None: raise ValueError(f'model does not contain prop root {prop_root}.') self._freejoint = None # type: mjcf.Element @property def name(self) -> str: return self._name @property def mjcf_model(self) -> mjcf.RootElement: """Returns the `mjcf.RootElement` object corresponding to this prop.""" return self._mjcf_root def set_pose(self, physics: mjcf.Physics, position: np.ndarray, quaternion: np.ndarray) -> None: """Sets the pose of the prop wrt to where it was defined. This function overrides `Entity.set_pose`, which has the annoying property that it doesn't consider where the prop was originally attached. EG if you do `pinch_site.attach(prop)`, the prop will be a sibling of pinch_site with the pinch_site's pose parameters, and calling `set_pose([0, 0, 0], [1, 0, 0, 0])` will clobber these params and move the prop to the parent-body origin. Oleg's fix uses an extra `prop_root` body that's a child of the sibling body, and sets the pose of this guy instead. Args: physics: An instance of `mjcf.Physics`. position: A NumPy array of size 3. quaternion: A NumPy array of size [w, i, j, k]. Raises: RuntimeError: If the entity is not attached. Exception: If oleg isn't happy """ if self._prop_root is None: raise Exception('prop {} missing root element'.format( self.mjcf_model.model)) if self._freejoint is None: physics.bind(self._prop_root).pos = position # pytype: disable=not-writable physics.bind(self._prop_root).quat = quaternion # pytype: disable=not-writable else: # If we're attached via a freejoint then bind().pos or quat does nothing, # as the pose is controlled by qpos directly. physics.bind(self._freejoint).qpos = np.hstack([position, quaternion]) # pytype: disable=not-writable def set_freejoint(self, joint: mjcf.Element): """Associates a freejoint with this prop if attached to arena.""" joint_type = joint.tag # pytype: disable=attribute-error if joint_type != 'freejoint': raise ValueError(f'Expected a freejoint but received {joint_type}') self._freejoint = joint def disable_collisions(self) -> None: for geom in self.mjcf_model.find_all('geom'): geom.contype = 0 geom.conaffinity = 0 class WrapperProp(Prop): def _build(self, wrapped_entity: composer.Entity, name: str): root = mjcf.element.RootElement(model=name) body_elem = root.worldbody.add('body', name='prop_root') site_elem = body_elem.add('site', name='prop_root_site') site_elem.attach(wrapped_entity.mjcf_model) super()._build(name=name, mjcf_root=root, prop_root='prop_root') class Camera(Prop): """Base class for Moma camera props.""" def _build( # pylint:disable=arguments-renamed self, name: str, mjcf_root: mjcf.RootElement, camera_element: str, prop_root: str = 'prop_root', width: int = 480, height: int = 640, fovy: float = 90.0): """Camera constructor. Args: name: The unique name of this prop. mjcf_root: The root element of the MJCF model. camera_element: Name of the camera MJCF element. prop_root: Name of the prop root body MJCF element. width: Width of the camera image. height: Height of the camera image. fovy: Field of view, in degrees. """ super()._build(name, mjcf_root, prop_root) self._camera_element = camera_element self._width = width self._height = height self._fovy = fovy # Sub-classes should extend `_build` to construct the appropriate mjcf, and # over-ride the `rgb_camera` and `depth_camera` properties. @property def camera(self) -> mjcf.Element: """Returns an mjcf.Element representing the camera.""" return self._mjcf_root.find('camera', self._camera_element) def get_camera_pos(self, physics: mjcf.Physics) -> np.ndarray: return physics.bind(self.camera).xpos # pytype: disable=attribute-error def get_camera_quat(self, physics: mjcf.Physics) -> np.ndarray: return tr.mat_to_quat( np.reshape(physics.bind(self.camera).xmat, [3, 3])) # pytype: disable=attribute-error def render_rgb(self, physics: mjcf.Physics) -> np.ndarray: return np.atleast_3d( physics.render( height=self._height, width=self._width, camera_id=self.camera.full_identifier, # pytype: disable=attribute-error depth=False)) def render_depth(self, physics: mjcf.Physics) -> np.ndarray: return np.atleast_3d(physics.render( height=self._height, width=self._width, camera_id=self.camera.full_identifier, # pytype: disable=attribute-error depth=True)) def get_intrinsics(self, physics: mjcf.Physics) -> np.ndarray: focal_len = self._height / 2 / np.tan(self._fovy / 2 * np.pi / 180) return np.array([[focal_len, 0, (self._height - 1) / 2, 0], [0, focal_len, (self._height - 1) / 2, 0], [0, 0, 1, 0]]) class Block(Prop): """A block prop.""" def _build( # pylint:disable=arguments-renamed self, name: str = 'box', width=0.04, height=0.04, depth=0.04) -> None: mjcf_root, site = _make_block_model(name, width, height, depth) super()._build(name, mjcf_root, 'prop_root') del site def _make_block_model(name, width, height, depth, color=(1, 0, 0, 1), solimp=(0.95, 0.995, 0.001), solref=(0.002, 0.7)): """Makes a plug model: the mjcf element, and reward sites.""" mjcf_root = mjcf.element.RootElement(model=name) prop_root = mjcf_root.worldbody.add('body', name='prop_root') box = prop_root.add( 'geom', name='body', type='box', pos=(0, 0, 0), size=(width / 2., height / 2., depth / 2.), mass=0.050, solref=solref, solimp=solimp, condim=1, rgba=color) site = prop_root.add( 'site', name='box_centre', type='sphere', rgba=(0.1, 0.1, 0.1, 0.8), size=(0.002,), pos=(0, 0, 0), euler=(0, 0, 0)) # Was (np.pi, 0, np.pi / 2) del box return mjcf_root, site def is_rgba(prop: composer.Entity, rgba: np.ndarray) -> bool: """Returns True if all the prop's geoms are of color `rgba`.""" for geom in prop.mjcf_model.find_all('geom'): if geom.rgba is not None and not np.array_equal(geom.rgba, rgba): return False return True
dm_robotics-main
py/moma/prop.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 subtask -> environment adaptor.""" import enum import sys from typing import Dict, List, Optional, Text, Tuple from absl.testing import absltest from dm_control import composer from dm_control import mjcf from dm_control.composer.observation import observable import dm_env from dm_env import specs from dm_robotics.agentflow import spec_utils from dm_robotics.agentflow import subtask from dm_robotics.agentflow import testing_functions from dm_robotics.agentflow.decorators import overrides from dm_robotics.agentflow.options import basic_options from dm_robotics.moma import base_task from dm_robotics.moma import effector from dm_robotics.moma import entity_initializer from dm_robotics.moma import moma_option from dm_robotics.moma import scene_initializer from dm_robotics.moma import sensor as moma_sensor from dm_robotics.moma import subtask_env from dm_robotics.moma import subtask_env_builder from dm_robotics.moma.models.arenas import empty import numpy as np def action(spec, value): return np.full(shape=spec.shape, fill_value=value, dtype=spec.dtype) def effectors_action_spec(effectors): a_specs = [a.action_spec(None) for a in effectors] return spec_utils.merge_specs(a_specs) class FakeEffector(effector.Effector): def __init__(self, prefix: str, dof: int): self._prefix = prefix self._dof = dof self.received_commands = [] def initialize_episode(self, physics, random_state): pass def action_spec(self, physics): actuator_names = [(self.prefix + str(i)) for i in range(self._dof)] return specs.BoundedArray( shape=(self._dof,), dtype=np.float32, minimum=[-100.0] * self._dof, maximum=[100.0] * self._dof, name='\t'.join(actuator_names)) def set_control(self, physics, command): del physics self.received_commands.append(command) @property def prefix(self): return self._prefix class FakeSubtask(subtask.SubTask): """Adds a 'fake' observation and an action, which is ignored.""" def __init__(self, base_env: dm_env.Environment, effectors: List[FakeEffector], max_steps: int, name: Optional[Text] = None) -> None: super().__init__(name) self._steps_taken = 0 self._max_steps = max_steps self._observation_spec = dict(base_env.observation_spec()) self._observation_spec['fake'] = specs.BoundedArray( shape=(1,), dtype=np.float32, minimum=[0], maximum=[sys.maxsize]) effectors_spec = effectors_action_spec(effectors) action_spec_shape = (effectors_spec.shape[0] + 1,) action_spec_minimum = list(effectors_spec.minimum) + [-1000] action_spec_maximum = list(effectors_spec.maximum) + [1000] self._action_spec = specs.BoundedArray( shape=action_spec_shape, dtype=effectors_spec.dtype, minimum=action_spec_minimum, maximum=action_spec_maximum) self._reward_spec = base_env.reward_spec() self._discount_spec = base_env.discount_spec() self._last_parent_timestep = None @overrides(subtask.SubTask) def observation_spec(self): return self._observation_spec @overrides(subtask.SubTask) def action_spec(self): return self._action_spec @overrides(subtask.SubTask) def reward_spec(self) -> specs.Array: return self._reward_spec @overrides(subtask.SubTask) def discount_spec(self) -> specs.Array: return self._discount_spec @overrides(subtask.SubTask) def arg_spec(self): return None @overrides(subtask.SubTask) def agent_to_parent_action(self, agent_action: np.ndarray) -> np.ndarray: # Throw away the last value in the array return agent_action[:len(agent_action) - 1] @overrides(subtask.SubTask) def reset(self, parent_timestep: dm_env.TimeStep): self._steps_taken = 0 return parent_timestep @overrides(subtask.SubTask) def parent_to_agent_timestep( self, parent_timestep: dm_env.TimeStep, own_arg_key: Optional[Text] = None) -> Tuple[dm_env.TimeStep, float]: self._steps_taken += 1 self._last_parent_timestep = parent_timestep child_observation = dict(parent_timestep.observation) child_observation['fake'] = np.asarray([self._steps_taken], dtype=np.float32) timestep = parent_timestep._replace(observation=child_observation) return timestep def pterm(self, parent_timestep: dm_env.TimeStep, arg_key: Text) -> float: return 1.0 if self._steps_taken >= self._max_steps else 0.0 def assert_timesteps_from_subtask(self, *timesteps: dm_env.TimeStep): for timestep in timesteps: if 'fake' not in timestep.observation: return False return True @property def last_parent_timestep(self) -> Optional[dm_env.TimeStep]: return self._last_parent_timestep class FakeSubTaskObserver(subtask.SubTaskObserver): def __init__(self): self.last_parent_timestep = None self.last_parent_action = None self.last_agent_timestep = None self.last_agent_action = None def step(self, parent_timestep: dm_env.TimeStep, parent_action: Optional[np.ndarray], agent_timestep: dm_env.TimeStep, agent_action: Optional[np.ndarray]) -> None: self.last_parent_timestep = parent_timestep self.last_parent_action = parent_action self.last_agent_timestep = agent_timestep self.last_agent_action = agent_action # Test method: # Create a SubTask and Reset option to drive the environment. # Create an EnvironmentAdaptor from them. # Ensure that both systems drive the underlying Environment the same way. class SubTaskEnvironmentTest(absltest.TestCase): def testEnvironmentDriver(self): base_env = testing_functions.SpyEnvironment() effectors = [ FakeEffector('fake_effector_1', 3), FakeEffector('faky_mcfakeface', 2) ] effectors_spec = effectors_action_spec(effectors) sub_task = FakeSubtask(base_env, effectors, max_steps=3, name='FakeSubTask') # Action that we send to the Environment-from-SubTask adaptor. agent_action = action(sub_task.action_spec(), 22) # Action that this adaptor should send to the base environment. base_agent_action = action(effectors_spec, 22) # Action that the adaptor sends to the base environment for reset(). reset_action = action(effectors_spec, 11) reset = moma_option.MomaOption( physics_getter=lambda: base_env.physics, effectors=effectors, delegate=basic_options.FixedOp(reset_action, num_steps=2, name='Reset')) with subtask_env.SubTaskEnvironment(base_env, effectors, sub_task, reset) as env: timestep1 = env.reset() subtask_timestep1 = sub_task.last_parent_timestep # Step the env 3 times (that's the limit of the subtask) # Check the corresponding actions sent to the base environment. timestep2 = env.step(agent_action) subtask_timestep2 = sub_task.last_parent_timestep timestep3 = env.step(agent_action) subtask_timestep3 = sub_task.last_parent_timestep timestep4 = env.step(agent_action) subtask_timestep4 = sub_task.last_parent_timestep # Check the timesteps are as expected: self.assertEqual(timestep1.step_type, dm_env.StepType.FIRST) self.assertEqual(subtask_timestep1.step_type, dm_env.StepType.FIRST) self.assertEqual(timestep2.step_type, dm_env.StepType.MID) self.assertEqual(subtask_timestep2.step_type, dm_env.StepType.MID) self.assertEqual(timestep3.step_type, dm_env.StepType.MID) self.assertEqual(subtask_timestep3.step_type, dm_env.StepType.MID) self.assertEqual(timestep4.step_type, dm_env.StepType.LAST) self.assertEqual(subtask_timestep4.step_type, dm_env.StepType.LAST) sub_task.assert_timesteps_from_subtask(timestep1, timestep2, timestep3, timestep4) # Check the actions that were received by the base environment # It should get 2 reset steps + 3 subtask steps. self.assertLen(effectors[0].received_commands, 5) self.assertLen(effectors[1].received_commands, 5) self._assert_actions(reset_action[:3], effectors[0].received_commands[0:2]) self._assert_actions(reset_action[3:], effectors[1].received_commands[0:2]) self._assert_actions(base_agent_action[:3], effectors[0].received_commands[2:5]) self._assert_actions(base_agent_action[3:], effectors[1].received_commands[2:5]) effectors[0].received_commands.clear() effectors[1].received_commands.clear() # Now, step the env once more. This should provoke a reset. timestep5 = env.step(agent_action) self.assertEqual(timestep5.step_type, dm_env.StepType.FIRST) sub_task.assert_timesteps_from_subtask(timestep5) self.assertLen(effectors[0].received_commands, 2) self.assertLen(effectors[1].received_commands, 2) self._assert_actions(reset_action[:3], effectors[0].received_commands[0:2]) self._assert_actions(reset_action[3:], effectors[1].received_commands[0:2]) effectors[0].received_commands.clear() effectors[1].received_commands.clear() # Continuing to step the environment should single-step the base env. timestep6 = env.step(agent_action) timestep7 = env.step(agent_action) timestep8 = env.step(agent_action) self.assertEqual(timestep6.step_type, dm_env.StepType.MID) self.assertEqual(timestep7.step_type, dm_env.StepType.MID) self.assertEqual(timestep8.step_type, dm_env.StepType.LAST) sub_task.assert_timesteps_from_subtask(timestep6, timestep7, timestep8) self.assertLen(effectors[0].received_commands, 3) self.assertLen(effectors[1].received_commands, 3) self._assert_actions(base_agent_action[:3], effectors[0].received_commands[0:3]) self._assert_actions(base_agent_action[3:], effectors[1].received_commands[0:3]) effectors[0].received_commands.clear() effectors[1].received_commands.clear() def testAdaptorResetLifecycle(self): # When the environment adaptor uses the reset option, it should LAST step # the reset option - this is a test of that behaviour. base_env = testing_functions.SpyEnvironment() effectors = [ FakeEffector('fake_effector_1', 3), FakeEffector('fake_effector_2', 2) ] effectors_spec = effectors_action_spec(effectors) sub_task = FakeSubtask(base_env, effectors, max_steps=1, name='FakeSubTask') # Action that we send to the Environment-from-SubTask adaptor. agent_action = action(sub_task.action_spec(), 22) # Action that the adaptor sends to the base environment for reset(). reset_action = action(effectors_spec, 11) # Two steps of reset, FIRST, MID. # Thereafter, reset will return pterm() 1.0 and should receive another # step, with step_type LAST. reset = testing_functions.SpyOp(reset_action, num_steps=2, name='Reset') wrapped_reset = moma_option.MomaOption( physics_getter=lambda: base_env.physics, effectors=effectors, delegate=reset) with subtask_env.SubTaskEnvironment(base_env, effectors, sub_task, wrapped_reset) as env: env.reset() # Step the env once (that is the subtask limit) env.step(agent_action) # step again, provoking reset. env.step(agent_action) # We should have reset twice, therefore stepping the reset option: # Reset 1: FIRST, MID, LAST # Reset 2: FIRST, MID, LAST reset_step_timesteps = [ts.step for ts in reset.timesteps if ts.step] step_types = [ts.step_type for ts in reset_step_timesteps] self.assertEqual(step_types, [ dm_env.StepType.FIRST, dm_env.StepType.MID, dm_env.StepType.LAST, dm_env.StepType.FIRST, dm_env.StepType.MID, dm_env.StepType.LAST ]) def testNoneFirstRewardDiscount(self): # The dm_env interface specifies that the first timestep must have None # for the reward and discount. This test checks subtask env complies. base_env = testing_functions.SpyEnvironment() effectors = [ FakeEffector('fake_effector_1', 3), FakeEffector('fake_effector_2', 2) ] effectors_spec = effectors_action_spec(effectors) sub_task = FakeSubtask( base_env, effectors, max_steps=10, name='FakeSubTask') # Action that we send to the Environment-from-SubTask adaptor. agent_action = action(sub_task.action_spec(), 22) # Action that the adaptor sends to the base environment for reset(). reset_action = action(effectors_spec, 11) # Two steps of reset, FIRST, MID. # Thereafter, reset will return pterm() 1.0 and should receive another # step, with step_type LAST. reset = testing_functions.SpyOp(reset_action, num_steps=2, name='Reset') wrapped_reset = moma_option.MomaOption( physics_getter=lambda: base_env.physics, effectors=effectors, delegate=reset) with subtask_env.SubTaskEnvironment(base_env, effectors, sub_task, wrapped_reset) as env: ts = env.step(agent_action) self.assertIsNone(ts.reward) self.assertIsNone(ts.discount) reset_ts = env.reset() self.assertIsNone(reset_ts.reward) self.assertIsNone(reset_ts.discount) def testObserver(self): base_env = testing_functions.SpyEnvironment() effectors = [ FakeEffector('fake_effector_1', 3), FakeEffector('faky_mcfakeface', 2) ] effectors_spec = effectors_action_spec(effectors) sub_task = FakeSubtask(base_env, effectors, max_steps=3, name='FakeSubTask') # Action that we send to the Environment-from-SubTask adaptor. agent_action = action(sub_task.action_spec(), 22) # Action that the adaptor sends to the base environment for reset(). reset_action = action(effectors_spec, 11) reset = moma_option.MomaOption( physics_getter=lambda: base_env.physics, effectors=effectors, delegate=basic_options.FixedOp(reset_action, num_steps=2, name='Reset')) observer = FakeSubTaskObserver() with subtask_env.SubTaskEnvironment(base_env, effectors, sub_task, reset) as env: env.add_observer(observer) timestep1 = env.reset() self.assertIsNone(observer.last_parent_timestep) self.assertIsNone(observer.last_parent_action) self.assertIsNone(observer.last_agent_timestep) self.assertIsNone(observer.last_agent_action) # Step the env 3 times (that's the limit of the subtask) # Check the corresponding actions sent to the base environment. timestep2 = env.step(agent_action) self.assertEqual(observer.last_agent_timestep.step_type, dm_env.StepType.FIRST) # The fake observation is added by the subtask, and should not be present # in the parent timestep. self.assertNotIn('fake', observer.last_parent_timestep.observation) self.assertIn('fake', observer.last_agent_timestep.observation) self.assertTrue( np.array_equal(observer.last_agent_action, [22, 22, 22, 22, 22, 22])) self.assertTrue( np.array_equal(observer.last_parent_action, [22, 22, 22, 22, 22])) timestep3 = env.step(agent_action) self.assertEqual(observer.last_parent_timestep.step_type, dm_env.StepType.MID) self.assertEqual(observer.last_agent_timestep.step_type, dm_env.StepType.MID) self.assertNotIn('fake', observer.last_parent_timestep.observation) self.assertIn('fake', observer.last_agent_timestep.observation) self.assertTrue( np.array_equal(observer.last_agent_action, [22, 22, 22, 22, 22, 22])) self.assertTrue( np.array_equal(observer.last_parent_action, [22, 22, 22, 22, 22])) timestep4 = env.step(agent_action) self.assertEqual(observer.last_agent_timestep.step_type, dm_env.StepType.LAST) self.assertIsNone(observer.last_parent_action) self.assertIsNone(observer.last_agent_action) # Check the timesteps are as expected: self.assertEqual(timestep1.step_type, dm_env.StepType.FIRST) self.assertEqual(timestep2.step_type, dm_env.StepType.MID) self.assertEqual(timestep3.step_type, dm_env.StepType.MID) self.assertEqual(timestep4.step_type, dm_env.StepType.LAST) # Run a second episode. timestep1 = env.reset() # Observer should not have been stepped and wil still have none actions. self.assertIsNone(observer.last_parent_action) self.assertIsNone(observer.last_agent_action) # Step the env 3 times (that's the limit of the subtask) # Check the corresponding actions sent to the base environment. timestep2 = env.step(agent_action) self.assertEqual(observer.last_agent_timestep.step_type, dm_env.StepType.FIRST) # The fake observation is added by the subtask, and should not be present # in the parent timestep. self.assertNotIn('fake', observer.last_parent_timestep.observation) self.assertIn('fake', observer.last_agent_timestep.observation) self.assertTrue( np.array_equal(observer.last_agent_action, [22, 22, 22, 22, 22, 22])) self.assertTrue( np.array_equal(observer.last_parent_action, [22, 22, 22, 22, 22])) timestep3 = env.step(agent_action) self.assertEqual(observer.last_parent_timestep.step_type, dm_env.StepType.MID) self.assertEqual(observer.last_agent_timestep.step_type, dm_env.StepType.MID) self.assertNotIn('fake', observer.last_parent_timestep.observation) self.assertIn('fake', observer.last_agent_timestep.observation) self.assertTrue( np.array_equal(observer.last_agent_action, [22, 22, 22, 22, 22, 22])) self.assertTrue( np.array_equal(observer.last_parent_action, [22, 22, 22, 22, 22])) timestep4 = env.step(agent_action) self.assertEqual(observer.last_agent_timestep.step_type, dm_env.StepType.LAST) self.assertIsNone(observer.last_parent_action) self.assertIsNone(observer.last_agent_action) # Check the timesteps are as expected: self.assertEqual(timestep1.step_type, dm_env.StepType.FIRST) self.assertEqual(timestep2.step_type, dm_env.StepType.MID) self.assertEqual(timestep3.step_type, dm_env.StepType.MID) self.assertEqual(timestep4.step_type, dm_env.StepType.LAST) def _assert_actions(self, expected_action: np.ndarray, actual_actions: List[np.ndarray]): for actual_action in actual_actions: np.testing.assert_array_almost_equal(expected_action, actual_action) class SpySensor(moma_sensor.Sensor): def __init__(self): self.control_timestep_seconds = None self.physics_timestep_seconds = None self.physics_steps_per_control_step = None self.episode_count = 0 def initialize_for_task(self, control_timestep_seconds: float, physics_timestep_seconds: float, physics_steps_per_control_step: int): self.control_timestep_seconds = control_timestep_seconds self.physics_timestep_seconds = physics_timestep_seconds self.physics_steps_per_control_step = physics_steps_per_control_step def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: self.episode_count += 1 @property def observables(self) -> Dict[str, observable.Observable]: return {} @property def name(self) -> str: return 'SpySensor' def get_obs_key(self, obs: enum.Enum) -> str: return '' class SubTaskEnvBuilderTest(absltest.TestCase): def setUp(self): super().setUp() self._arena = _build_arena(name='empty') self._static_initializer = scene_initializer.CompositeSceneInitializer([]) self._dynamic_initializer = entity_initializer.CallableInitializer( lambda unused_physics, unused_state: None) def testSensorSetup(self): spy_sensor = SpySensor() task = base_task.BaseTask( task_name='empty', arena=self._arena, robots=[], props=[], extra_sensors=[spy_sensor], extra_effectors=[], scene_initializer=self._static_initializer, episode_initializer=self._dynamic_initializer, control_timestep=0.1) builder = subtask_env_builder.SubtaskEnvBuilder() self.assertEqual(spy_sensor.physics_steps_per_control_step, 100) builder.set_task(task) builder.build_base_env() def _build_arena(name: str) -> composer.Arena: """Builds an arena Entity.""" arena = empty.Arena(name) arena.ground.size = (2.0, 2.0, 2.0) arena.mjcf_model.option.timestep = 0.001 arena.mjcf_model.option.gravity = (0., 0., -1.0) arena.mjcf_model.size.nconmax = 1000 arena.mjcf_model.size.njmax = 2000 arena.mjcf_model.visual.__getattr__('global').offheight = 480 arena.mjcf_model.visual.__getattr__('global').offwidth = 640 arena.mjcf_model.visual.map.znear = 0.0005 return arena if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/subtask_env_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for base_task.""" import contextlib from absl.testing import absltest from dm_control import composer from dm_control.composer.observation import observable from dm_control.composer.observation import updater from dm_control.rl import control from dm_robotics.moma import base_task from dm_robotics.moma import entity_initializer from dm_robotics.moma import robot from dm_robotics.moma import scene_initializer from dm_robotics.moma.effectors import arm_effector as arm_effector_module from dm_robotics.moma.models.arenas import empty from dm_robotics.moma.models.end_effectors.robot_hands import robotiq_2f85 from dm_robotics.moma.models.robots.robot_arms import sawyer from dm_robotics.moma.sensors import robot_arm_sensor from dm_robotics.moma.sensors import robot_tcp_sensor import numpy as np class BaseTaskTest(absltest.TestCase): def _build_sample_base_task(self): arena = empty.Arena('test_arena') arm = sawyer.Sawyer(with_pedestal=False) gripper = robotiq_2f85.Robotiq2F85() robot.standard_compose( arm=arm, gripper=gripper, wrist_ft=None, wrist_cameras=[]) robot_sensors = [ robot_arm_sensor.RobotArmSensor( arm=arm, name='robot0', have_torque_sensors=True), robot_tcp_sensor.RobotTCPSensor(gripper=gripper, name='robot0'), ] arm_effector = arm_effector_module.ArmEffector( arm=arm, action_range_override=None, robot_name='robot0') rbt = robot.StandardRobot( arm=arm, arm_base_site_name='pedestal_attachment', gripper=gripper, wrist_ft=None, wrist_cameras=[], robot_sensors=robot_sensors, arm_effector=arm_effector, gripper_effector=None, name='robot0') arena.attach(arm) task = base_task.BaseTask( task_name='test', arena=arena, robots=[rbt], props=[], extra_sensors=[], extra_effectors=[], scene_initializer=scene_initializer.CompositeSceneInitializer([]), episode_initializer=entity_initializer.TaskEntitiesInitializer([]), control_timestep=0.1) return task def test_observables(self): """Test that the task observables includes only sensor observables.""" task = self._build_sample_base_task() task_obs = set(task.observables) robot_sensor_obs = [] for s in task.robots[0].sensors: robot_sensor_obs.extend(list(s.observables)) robot_sensor_obs = set(robot_sensor_obs) self.assertEmpty(task_obs ^ robot_sensor_obs) def test_observable_types(self): """Test that the task observables includes only sensor observables.""" task = self._build_sample_base_task() env = composer.Environment(task, strip_singleton_obs_buffer_dim=True) obs_spec = env.observation_spec() acceptable_types = set( [np.dtype(np.uint8), np.dtype(np.int64), np.dtype(np.float32)]) for spec in obs_spec.values(): self.assertIn(np.dtype(spec.dtype), acceptable_types) class FakePhysics(control.Physics): """A fake Physics class for unit testing observations.""" def __init__(self): self._step_counter = 0 self._observables = {} def step(self, sub_steps=1): self._step_counter += 1 @property def observables(self): return self._observables def time(self): return self._step_counter def timestep(self): return 1.0 def set_control(self, ctrl): pass def reset(self): self._step_counter = 0 def after_reset(self): pass @contextlib.contextmanager def suppress_physics_errors(self): yield class CastObservationsTest(absltest.TestCase): def testCastAggregatedObservable(self): physics = FakePhysics() physics.observables['raw_value'] = observable.Generic( raw_observation_callable=lambda unused: np.float64(physics.time()), update_interval=1, buffer_size=2, aggregator=lambda arr: np.asarray([arr[0], arr[1], arr[0] + arr[1]]), corruptor=lambda value, random_state: value * 10.0) physics.observables['cast_value'] = base_task.CastObservable( physics.observables['raw_value']) for obs in physics.observables.values(): obs.enabled = True physics.reset() physics_steps_per_control_step = 2 observation_updater = updater.Updater( physics.observables, physics_steps_per_control_step, strip_singleton_buffer_dim=True) observation_updater.reset(physics=physics, random_state=None) raw_values, cast_values = [], [] for unused_step in range(0, 3): observation_updater.prepare_for_next_control_step() for _ in range(physics_steps_per_control_step): physics.step() observation_updater.update() observation = observation_updater.get_observation() print(observation) raw_values.append(observation['raw_value']) cast_values.append(observation['cast_value']) np.testing.assert_equal(raw_values[0], np.asarray([10.0, 20.0, 30.0])) np.testing.assert_equal(cast_values[0], np.asarray([10.0, 20.0, 30.0])) np.testing.assert_equal(raw_values[1], np.asarray([30.0, 40.0, 70.0])) np.testing.assert_equal(cast_values[1], np.asarray([30.0, 40.0, 70.0])) np.testing.assert_equal(raw_values[2], np.asarray([50.0, 60.0, 110.0])) np.testing.assert_equal(cast_values[2], np.asarray([50.0, 60.0, 110.0])) self.assertEqual(raw_values[0].dtype, np.float64) self.assertEqual(cast_values[0].dtype, np.float32) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/base_task_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 Moma Base Task.""" import collections from typing import Callable, Dict, Optional, Sequence, List from absl import logging from dm_control import composer from dm_control import mjcf from dm_control.composer.observation import observable from dm_env import specs from dm_robotics.agentflow import spec_utils from dm_robotics.moma import effector from dm_robotics.moma import prop from dm_robotics.moma import robot from dm_robotics.moma import sensor as moma_sensor import numpy as np # Internal profiling _REWARD_TYPE = np.float32 _DISCOUNT_TYPE = np.float32 SceneInitializer = Callable[[np.random.RandomState], None] class BaseTask(composer.Task): """Base class for MoMa tasks. This class is parameterized by the required components of a MoMa task. This includes: - the arena (cell, basket, floor, and other world objects) - the robot (an encapsulation of the arm, gripper, and optionally things like bracelet camera) - props (free and fixed elements whose placement can be controlled by the initializer) - the scene initializer (composes the scene and positions objects/robots for each episode) """ def __init__(self, task_name: str, arena: composer.Arena, robots: Sequence[robot.Robot], props: Sequence[prop.Prop], extra_sensors: Sequence[moma_sensor.Sensor], extra_effectors: Sequence[effector.Effector], scene_initializer: SceneInitializer, episode_initializer: composer.Initializer, control_timestep: float): """Base Task Constructor. The initializers are run before every episode, in a two step process. 1. The scene initializer is run which can modify the scene (MJCF), for example by moving bodies that have no joints. 2. The episode initializer is run after the MJCF is compiled, this can modify any degree of freedom in the scene, like props that have a free-joint, robot arm joints, etc. Args: task_name: The name of the task. arena: The arena Entity to use. robots: List of robots that make up the task. props: List of props that are in the scene. extra_sensors: A list of sensors that aren't tied to a specific robot (eg: a scene camera sensors, or a sensor that detects some prop's pose). extra_effectors: A list of effectors that aren't tied to a specific robot. scene_initializer: An initializer, called before every episode, before scene compilation. episode_initializer: An initializer, called before every episode, after scene compilation. control_timestep: The control timestep of the task. """ self._task_name = task_name self._arena = arena self._robots = robots self._props = props self._extra_sensors = extra_sensors self._extra_effectors = extra_effectors self._scene_initializer = scene_initializer self._episode_initializer = episode_initializer self.control_timestep = control_timestep self._initialize_sensors() self._teardown_callables: List[Callable[[], None]] = [] def _initialize_sensors(self): for s in self.sensors: s.initialize_for_task( self.control_timestep, self.physics_timestep, self.physics_steps_per_control_step, ) def name(self): return self._task_name @property def episode_initializer(self): return self._episode_initializer @property def sensors(self) -> Sequence[moma_sensor.Sensor]: """Returns all of the sensors for this task.""" sensors = [] for rbt in self._robots: sensors += rbt.sensors sensors += self._extra_sensors return sensors @property def effectors(self) -> Sequence[effector.Effector]: """Returns all of the effectors for this task.""" effectors = [] for rbt in self._robots: effectors += rbt.effectors effectors += self._extra_effectors return effectors def effectors_action_spec( self, physics: mjcf.Physics, effectors: Optional[Sequence[effector.Effector]] = None ) -> specs.BoundedArray: """Returns the action spec for a sequence of effectors. Args: physics: The environment physics. effectors: Optional subset of effectors for which to get the action spec. If this is None or empty, then all of the tasks effectors are used to compose the action spec. """ a_specs = [a.action_spec(physics) for a in (effectors or self.effectors)] return spec_utils.merge_specs(a_specs) @property def root_entity(self): return self._arena @property def arena(self): return self._arena @property def robots(self) -> Sequence[robot.Robot]: """Returns the task robots.""" return self._robots @property def props(self) -> Sequence[prop.Prop]: """Returns the Props used in the task.""" return self._props @property def observables(self) -> Dict[str, observable.Observable]: # No entity observables, only explicitly defined task observables. base_obs = self.task_observables return collections.OrderedDict(base_obs) @property def task_observables(self) -> Dict[str, observable.Observable]: all_observables = {} for sensor in self.sensors: common = sensor.observables.keys() & all_observables.keys() if common: logging.error('Sensors have conflicting observables: %s', common) all_observables.update(sensor.observables) for k in all_observables: all_observables[k] = self._restrict_type(all_observables[k]) return all_observables # Profiling for .wrap() def before_step(self, physics, actions, random_state): """Function called before every environment step.""" # Moma base task is actuated directly using individual effectors. This is # done by calling each target effector's set_control method prior to calling # the environment step method. This can be done either manually or by # interfacing with a convenient wrapper such as SubTaskEnvironment or # MomaOption. pass def after_compile(self, physics: mjcf.Physics, random_state: np.random.RandomState): """Initialization requiring access to physics or completed mjcf model.""" for ef in self.effectors: ef.after_compile(self.root_entity.mjcf_model.root, physics) for se in self.sensors: se.after_compile(self.root_entity.mjcf_model.root, physics) def add_teardown_callable(self, teardown_fn: Callable[[], None]): """Adds function to be called when the task is closed.""" self._teardown_callables.append(teardown_fn) def close(self): """Closes all the effectors and sensors of the tasks. We might need to do some clean up after the task is over. This is mainly the case when using a real environment when we need to close connections that are made to the real robot. """ for eff in self.effectors: eff.close() for sen in self.sensors: sen.close() for teardown_fn in self._teardown_callables: teardown_fn() def get_reward(self, physics): return _REWARD_TYPE(0.0) def get_discount(self, physics): return _DISCOUNT_TYPE(1.0) def get_reward_spec(self): return specs.Array(shape=(), dtype=_REWARD_TYPE, name='reward') def get_discount_spec(self): return specs.BoundedArray( shape=(), dtype=_DISCOUNT_TYPE, minimum=0., maximum=1., name='discount') def initialize_episode_mjcf(self, random_state): self._scene_initializer(random_state) # Profiling for .wrap() def initialize_episode(self, physics, random_state): """Function called at the beginning of every episode in sim (just once otw). Args: physics: An `mjcf.Physics` random_state: an `np.random.RandomState` """ self._episode_initializer(physics, random_state) for e in self.effectors: e.initialize_episode(physics, random_state) for s in self.sensors: s.initialize_episode(physics, random_state) def action_spec(self, physics): # Moma Base Task has empty action spec as it is actuated directly through # Effectors using their set_control method. This is done by calling each # target effector's set_control method prior to calling the environment step # method. This can be done either manually or by interfacing with a # convenient wrapper such as SubTaskEnvironment or MomaOption. return specs.BoundedArray( shape=(0,), dtype=np.float32, minimum=np.array([], dtype=np.float32), maximum=np.array([], dtype=np.float32)) def set_episode_initializer(self, episode_initializer: composer.Initializer): self._episode_initializer = episode_initializer def set_scene_initializer(self, scene_initializer: SceneInitializer): self._scene_initializer = scene_initializer def _restrict_type(self, obs: observable.Observable) -> observable.Observable: # When saving experiences as tf.Example protos there is some type coercion # involved. By simplifying the observation data types here we can ensure # that the data from loaded experience will match the data types of the # environment spec. casted = CastObservable(obs) casted.enabled = obs.enabled return casted class CastObservable(observable.Observable): """Casts an observable while retaining its other attributes. This ensures that the Updater works correctly with observables that have their data type cast. I.e. the aggregator, update_interval etc continue to work. """ def __init__(self, delegate: observable.Observable): super().__init__(delegate.update_interval, delegate.buffer_size, delegate.delay, delegate.aggregator, delegate.corruptor) self._delegate = delegate @property def array_spec(self) -> specs.Array: delegate_spec = self._delegate.array_spec if delegate_spec is None: return delegate_spec new_type = self._cast_type(delegate_spec.dtype) if new_type == delegate_spec.dtype: return delegate_spec else: return delegate_spec.replace(dtype=new_type) def observation_callable( self, physics: mjcf.Physics, random_state: Optional[np.random.RandomState] = None ) -> Callable[[], np.ndarray]: delegate_callable = self._delegate.observation_callable( physics, random_state) def cast(): source = delegate_callable() new_type = self._cast_type(source.dtype) if new_type == source.dtype: return source else: return source.astype(new_type) return cast def _callable(self, physics: mjcf.Physics): # Overridden, but not used. del physics raise AssertionError('Should not be called') def _cast_type(self, dtype): """Get the type that the given dtype should be cast to.""" if dtype in (np.uint8, np.float32, np.int64): return dtype if np.issubdtype(dtype, np.floating): return np.float32 elif np.issubdtype(dtype, np.integer): return np.int64 else: return dtype
dm_robotics-main
py/moma/base_task.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """Tests for subtask.""" from typing import List, NamedTuple, Optional, Text from typing import Union from unittest import mock from absl.testing import absltest import dm_env from dm_env import specs import dm_robotics.agentflow as af from dm_robotics.agentflow import spec_utils from dm_robotics.agentflow import testing_functions import numpy as np valid_value = testing_functions.valid_value random_timestep = testing_functions.random_timestep def random_step_type(): return np.random.choice(list(dm_env.StepType)) def _random_timestep(obs_spec: Union[None, specs.Array, spec_utils.ObservationSpec] = None): if obs_spec is None: key = testing_functions.random_string(3) spec = testing_functions.random_array_spec() obs_val = valid_value(spec) observation = {key: obs_val} else: observation = valid_value(obs_spec) return dm_env.TimeStep( step_type=random_step_type(), reward=np.float32(np.random.random()), discount=np.float32(np.random.random()), observation=observation) def _random_result(): termination_reason = np.random.choice( [af.TerminationType.SUCCESS, af.TerminationType.FAILURE]) data = np.random.random(size=(5,)).astype(np.float32) return af.OptionResult(termination_reason, data) # A custom comparison function because nan != nan and our timesteps contain nan # when there is no reward. def _timestep_equals(lhs, rhs): # If not iterable do normal comparison. try: iter(lhs) except TypeError: return lhs == rhs for field_a, field_b in zip(lhs, rhs): if field_a == field_b: return True if np.isnan(field_a) and np.isnan(field_b): return True return False class StubSubTask(af.SubTask): def __init__(self, observation_spec: spec_utils.ObservationSpec, action_spec: specs.Array): self._observation_spec = observation_spec self._action_spec = action_spec # A list of the agent actions passed to agent_to_parent_action. self.actual_agent_actions = [] # type: List[np.ndarray] # A list of parent actions to return from agent_to_parent_action. # This list is popped from as agent_to_parent_action is called. self.parent_actions = [] # type: List[np.ndarray] # Timesteps received by parent_to_agent_timestep self.actual_parent_timesteps = [] # type: List[dm_env.TimeStep] # Timesteps to return from parent_to_agent_timestep. # This list is popped from as parent_to_agent_timestep is called. self.agent_timesteps = [] # type: List[dm_env.TimeStep] def observation_spec(self) -> spec_utils.ObservationSpec: return self._observation_spec def arg_spec(self) -> Optional[specs.Array]: return None def action_spec(self) -> specs.BoundedArray: return self._action_spec def agent_to_parent_action(self, agent_action: np.ndarray) -> np.ndarray: self.actual_agent_actions.append(np.copy(agent_action)) if not self.parent_actions: raise ValueError("No more actions to return.") return self.parent_actions.pop(0) def parent_to_agent_timestep(self, parent_timestep: dm_env.TimeStep, arg_key: Text) -> dm_env.TimeStep: self.actual_parent_timesteps.append(parent_timestep) if not self.agent_timesteps: raise ValueError("no more agent timesteps") return self.agent_timesteps.pop(0) def pterm(self, parent_timestep: dm_env.TimeStep, own_arg_key: Text) -> float: return 0. ObserverStep = NamedTuple("ObserverStep", [("parent_timestep", dm_env.TimeStep), ("parent_action", np.ndarray), ("agent_timestep", dm_env.TimeStep), ("agent_action", np.ndarray)]) class SpySubTaskObserver(af.SubTaskObserver): def __init__(self): self.steps = [] # type: List[ObserverStep] def step(self, parent_timestep: dm_env.TimeStep, parent_action: np.ndarray, agent_timestep: dm_env.TimeStep, agent_action: np.ndarray) -> None: self.steps.append( ObserverStep(parent_timestep, parent_action, agent_timestep, agent_action)) class SubTaskOptionTest(absltest.TestCase): def testTaskDefinesOptionArgSpec(self): agent = mock.MagicMock(spec=af.Policy) task = mock.MagicMock(spec=af.SubTask) spec = testing_functions.random_array_spec() task.arg_spec.return_value = spec option = af.SubTaskOption(task, agent) actual_arg_spec = option.arg_spec() self.assertEqual(actual_arg_spec, spec) def testTaskDelegatesArgKeyToOptionIfPossible(self): policy = mock.MagicMock(spec=af.Policy) option = mock.MagicMock(spec=af.Option) random_action_spec = testing_functions.random_array_spec(shape=(5,)) random_observation_spec = testing_functions.random_array_spec(shape=(10,)) task = testing_functions.IdentitySubtask( observation_spec=random_observation_spec, action_spec=random_action_spec, steps=100) task_arg_key = testing_functions.random_string() option_arg_key = testing_functions.random_string() type(option).arg_key = mock.PropertyMock(return_value=option_arg_key) task._default_arg_key = task_arg_key sto_wrapping_policy = af.SubTaskOption(task, policy) sto_wrapping_option = af.SubTaskOption(task, option) self.assertEqual(sto_wrapping_option.arg_key, option_arg_key) self.assertEqual(sto_wrapping_policy.arg_key, task_arg_key) def testPtermTakenFromAgentTimestep(self): # pterm of the SubTaskOption should delegate to the SubTask. # 1. Arrange: task_action_spec = testing_functions.random_array_spec(shape=(5,)) task_obs_spec = testing_functions.random_observation_spec() agent_action = valid_value(task_action_spec) parent_action = np.random.random(size=(5,)).astype(np.float32) subtask_timestep = _random_timestep(task_obs_spec) task = mock.MagicMock(spec=af.SubTask) task.parent_to_agent_timestep.return_value = subtask_timestep task.pterm.return_value = 0.2 task.action_spec.return_value = task_action_spec task.agent_to_parent_action.return_value = parent_action timestep = random_timestep(observation={}) task.observation_spec.return_value = task_obs_spec task.reward_spec.return_value = specs.Array( shape=(), dtype=np.float32, name="reward") task.discount_spec.return_value = specs.Array( shape=(), dtype=np.float32, name="discount") agent = mock.MagicMock(spec=af.Policy) agent.step.return_value = agent_action option = af.SubTaskOption(task, agent) # 2. Act: option.step(timestep) # 3. Assert: self.assertEqual(option.pterm(timestep), 0.2) def testStepTimestepFromSubtask(self): # The timestep the agent sees in begin_episode should come from the task. # 1. Arrange: task_action_spec = testing_functions.random_array_spec(shape=(5,)) task_obs_spec = testing_functions.random_observation_spec(shape=(4,)) agent_action = valid_value(task_action_spec) parent_action = np.random.random(size=(5,)).astype(np.float32) parent_timestep = _random_timestep() parent_timestep_without_reward = parent_timestep._replace( reward=np.float32("nan")) subtask_timestep = _random_timestep(task_obs_spec) pterm = 0.7 task = mock.MagicMock(spec=af.SubTask) task.parent_to_agent_timestep.return_value = subtask_timestep task.pterm.return_value = pterm task.action_spec.return_value = task_action_spec task.agent_to_parent_action.return_value = parent_action task.observation_spec.return_value = task_obs_spec task.reward_spec.return_value = specs.Array( shape=(), dtype=np.float32, name="reward") task.discount_spec.return_value = specs.Array( shape=(), dtype=np.float32, name="discount") agent = mock.MagicMock(spec=af.Policy) agent.step.return_value = agent_action option = af.SubTaskOption(task, agent) # 2. Act: actual_option_action = option.step(parent_timestep) # 3. Assert: # Check that the task was given the correct timestep to pack. testing_functions.assert_calls( task.parent_to_agent_timestep, [(parent_timestep_without_reward, option.arg_key)], equals_fn=_timestep_equals) # Check that the agent was given the timestep from the task. testing_functions.assert_calls(agent.step, [(subtask_timestep,)]) # Check that the task was given the agent aciton to convert to an action # for the parent environment. testing_functions.assert_calls(task.agent_to_parent_action, [(agent_action,)]) # Check that this parent environment action is the one that's returned. np.testing.assert_equal(actual_option_action, parent_action) def testObservable(self): # Arrange: env_def = testing_functions.EnvironmentSpec.random() subtask = StubSubTask( observation_spec=testing_functions.random_observation_spec(), action_spec=testing_functions.random_array_spec()) subtask_def = testing_functions.EnvironmentSpec.for_subtask(subtask) # Agent definition (agent operates 'in' the SubTask): agent_action1 = subtask_def.create_action() agent_action2 = subtask_def.create_action() agent = af.Sequence([af.FixedOp(agent_action1), af.FixedOp(agent_action2)]) # Observer - this is the class under test (CUT / SUT). observer = SpySubTaskObserver() # This is the option that the observer is observing. subtask_option = af.SubTaskOption(subtask, agent, [observer]) # Define how the subtask will behave (two parts): # Part 1 - The timesteps it will pass to the agent agent_timestep1 = subtask_def.create_timestep( step_type=dm_env.StepType.FIRST) agent_timestep2 = subtask_def.create_timestep(step_type=dm_env.StepType.MID) subtask.agent_timesteps.append(agent_timestep1) subtask.agent_timesteps.append(agent_timestep2) # Part 2 - The actions it will return to the parent. env_action1 = env_def.create_action() env_action2 = env_def.create_action() subtask.parent_actions.append(env_action1) subtask.parent_actions.append(env_action2) # Act: # Drive the subtask_option. This should result in our listener being # invoked twice (once per step). Each invocation should contain the # env-side timestep and action and the subtask-side timestep and action. env_timestep1 = env_def.create_timestep(step_type=dm_env.StepType.FIRST) env_timestep2 = env_def.create_timestep(step_type=dm_env.StepType.MID) actual_parent_action1 = subtask_option.step(env_timestep1) actual_parent_action2 = subtask_option.step(env_timestep2) # Assert: # Check that the observer was passed the expected values. np.testing.assert_almost_equal(env_action1, actual_parent_action1) np.testing.assert_almost_equal(env_action2, actual_parent_action2) # Check the timesteps and actions that were given to the listener. self.assertLen(observer.steps, 2) step = observer.steps[0] testing_functions.assert_timestep(env_timestep1, step.parent_timestep) testing_functions.assert_value(env_action1, step.parent_action) testing_functions.assert_timestep(agent_timestep1, step.agent_timestep) testing_functions.assert_value(agent_action1, step.agent_action) step = observer.steps[1] testing_functions.assert_timestep(env_timestep2, step.parent_timestep) testing_functions.assert_value(env_action2, step.parent_action) testing_functions.assert_timestep(agent_timestep2, step.agent_timestep) testing_functions.assert_value(agent_action2, step.agent_action) if __name__ == "__main__": absltest.main()
dm_robotics-main
py/moma/subtask_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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_robotics-main
py/moma/__init__.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Abstract effector interface definition.""" import abc from dm_control import mjcf from dm_env import specs import numpy as np class Effector(abc.ABC): """Abstract effector interface, a controllable element of the environment. An effector provides an interface for an agent to interact in some way with the environment. eg: a robot arm, a gripper, a pan tilt unit, etc. The effector is defined by its action spec, a control method, and a prefix that marks the control components of the effector in the wider task action spec. """ def close(self): """Clean up after we are done using the effector. Called to clean up when we are done using the effector. This is mainly used for real effectors that might need to close all the connections to the robot. """ def after_compile(self, mjcf_model: mjcf.RootElement, physics: mjcf.Physics) -> None: """Method called after the MJCF model has been compiled and finalized. Args: mjcf_model: The root element of the scene MJCF model. physics: Compiled physics. """ @abc.abstractmethod def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: pass @abc.abstractmethod def action_spec(self, physics: mjcf.Physics) -> specs.BoundedArray: pass @abc.abstractmethod def set_control(self, physics: mjcf.Physics, command: np.ndarray) -> None: pass @property @abc.abstractmethod def prefix(self) -> str: pass
dm_robotics-main
py/moma/effector.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 MOMA initializers that return a boolean indicating success.""" import abc from typing import Any from dm_control import composer class Initializer(composer.Initializer): """Composer initializer that returns whether it was successful.""" @abc.abstractmethod def __call__(self, physics: Any, random_state: Any) -> bool: raise NotImplementedError def reset(self, physics: Any) -> bool: """Resets this initializer. Returns true if successful.""" return True
dm_robotics-main
py/moma/initializer.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Package building script.""" import setuptools def _get_requirements(requirements_file): # pylint: disable=g-doc-args """Returns a list of dependencies for setup() from requirements.txt. Currently a requirements.txt is being used to specify dependencies. In order to avoid specifying it in two places, we're going to use that file as the source of truth. Lines starting with -r will be ignored. If the requirements are split across multiple files, call this function multiple times instead and sum the results. """ def line_should_be_included(line): return line and not line.startswith("-r") with open(requirements_file) as f: return [_parse_line(line) for line in f if line_should_be_included(line)] def _parse_line(s): """Parses a line of a requirements.txt file.""" requirement, *_ = s.split("#") return requirement.strip() setuptools.setup( name="dm_robotics-moma", package_dir={"dm_robotics.moma": ""}, packages=[ "dm_robotics.moma", "dm_robotics.moma.effectors", "dm_robotics.moma.models", "dm_robotics.moma.utils", "dm_robotics.moma.sensors", "dm_robotics.moma.tasks", "dm_robotics.moma.tasks.example_task", "dm_robotics.moma.models.arenas", "dm_robotics.moma.models.end_effectors.robot_hands", "dm_robotics.moma.models.end_effectors.wrist_sensors", "dm_robotics.moma.models.robots.robot_arms", ], version="0.5.0", license="Apache 2.0", author="DeepMind", description="Tools for authoring robotic manipulation tasks.", long_description=open("README.md").read(), long_description_content_type="text/markdown", url="https://github.com/deepmind/dm_robotics/tree/main/py/moma", python_requires=">=3.7, <3.11", setup_requires=["wheel >= 0.31.0"], install_requires=(_get_requirements("requirements.txt") + _get_requirements("requirements_external.txt")), classifiers=[ "Development Status :: 5 - Production/Stable", "Programming Language :: Python :: 3", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries", "Topic :: Scientific/Engineering", "Topic :: Scientific/Engineering :: Mathematics", ], zip_safe=True, include_package_data=True)
dm_robotics-main
py/moma/setup.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module for scene initializers. Scene initializers are callables that can change the MJCF of a scene. They are called before each episode, and the MJCF is recompiled afterwards. See `base_task.py` for more information on how they are called. """ import dataclasses from typing import Callable, Iterable, Tuple from dm_control import mjcf from dm_robotics.moma import base_task import numpy as np @dataclasses.dataclass(frozen=True) class CompositeSceneInitializer: initializers: Iterable[base_task.SceneInitializer] def __call__(self, random_state: np.random.RandomState) -> None: for initializer in self.initializers: initializer(random_state) NO_INIT = CompositeSceneInitializer(initializers=tuple()) @dataclasses.dataclass class EntityPoseInitializer: """Pose initializer.""" entity: mjcf.Element pose_sampler: Callable[[np.random.RandomState], Tuple[np.ndarray, np.ndarray]] def __call__(self, random_state: np.random.RandomState) -> None: pos, quat = self.pose_sampler(random_state) # pytype: disable=not-writable self.entity.pos = pos self.entity.quat = quat # pytype: enable=not-writable
dm_robotics-main
py/moma/scene_initializer.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Composes Entities.""" import abc from dm_control import composer class TaskEntitiesComposer(abc.ABC): @abc.abstractmethod def compose_entities(self, arena: composer.Arena) -> None: """Adds all of the necessary objects to the arena and composes objects.""" pass
dm_robotics-main
py/moma/entity_composer.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A module for encapsulating the robot arm, gripper, and bracelet.""" import abc from typing import List, Optional, Sequence, Generic, TypeVar from dm_control import composer from dm_control import mjcf from dm_control.composer.initializers import utils from dm_control.mjcf import traversal_utils from dm_robotics.geometry import geometry from dm_robotics.moma import effector from dm_robotics.moma import prop from dm_robotics.moma import sensor as moma_sensor from dm_robotics.moma.models.end_effectors.robot_hands import robot_hand from dm_robotics.moma.models.robots.robot_arms import robot_arm from dm_robotics.moma.utils import ik_solver import numpy as np Arm = TypeVar('Arm', bound=robot_arm.RobotArm) Gripper = TypeVar('Gripper', bound=robot_hand.AnyRobotHand) # Absolute velocity threshold for a arm joint to be considered settled. _SETTLE_QVEL_TOL = 1e-4 # Absolute acceleration threshold for an arm joint to be considered settled. _SETTLE_QACC_TOL = 1e-1 # Maximum simulation time to allow the robot to settle when positioning it. _MAX_SETTLE_PHYSICS_TIME = 2.0 class Robot(abc.ABC, Generic[Arm, Gripper]): """Abstract base class for MOMA robotic arms and their attachments.""" @property @abc.abstractmethod def name(self): pass @property @abc.abstractmethod def sensors(self) -> Sequence[moma_sensor.Sensor]: pass @property @abc.abstractmethod def effectors(self) -> List[effector.Effector]: pass @property @abc.abstractmethod def arm_effector(self) -> effector.Effector: pass @property @abc.abstractmethod def gripper_effector(self) -> Optional[effector.Effector]: pass @property @abc.abstractmethod def arm(self) -> Arm: pass @property @abc.abstractmethod def gripper(self) -> Gripper: pass @property @abc.abstractmethod def wrist_ft(self): pass @property @abc.abstractmethod def wrist_cameras(self): """Returns a sequence of wrist cameras (if any).""" @property @abc.abstractmethod def arm_base_site(self): """Returns a site at the base of the arm.""" @property @abc.abstractmethod def arm_frame(self): pass @abc.abstractmethod def position_gripper(self, physics: mjcf.Physics, position: np.ndarray, quaternion: np.ndarray): """Moves the gripper ik point position to the (pos, quat) pose tuple.""" @abc.abstractmethod def position_arm_joints(self, physics, joint_angles): """Positions the arm joints to the given angles.""" class StandardRobot(Generic[Arm, Gripper], Robot[Arm, Gripper]): """A Robot class representing the union of arm, gripper, and bracelet.""" def __init__(self, arm: Arm, arm_base_site_name: str, gripper: Gripper, robot_sensors: Sequence[moma_sensor.Sensor], arm_effector: effector.Effector, gripper_effector: Optional[effector.Effector], wrist_ft: Optional[composer.Entity] = None, wrist_cameras: Optional[Sequence[prop.Camera]] = None, name: str = 'robot'): """Robot constructor. Args: arm: The robot arm Entity. arm_base_site_name: The label of the base site of the arm model, so that we can position the robot base in the world. gripper: The gripper Entity to attach to the arm. robot_sensors: List of abstract Sensors that are associated with this robot. arm_effector: An effector for the robot arm. gripper_effector: An effector for the robot gripper. wrist_ft: Optional wrist force-torque Entity to add between the arm and gripper in the kinematic chain. wrist_cameras: Optional list of camera props attached to the robot wrist. name: A unique name for the robot. """ self._arm = arm self._gripper = gripper self._robot_sensors = robot_sensors self._arm_effector = arm_effector self._gripper_effector = gripper_effector self._wrist_ft = wrist_ft self._wrist_cameras = wrist_cameras or [] self._name = name # Site for the robot "base" for reporting wrist-site pose observations. self._arm_base_site = self._arm.mjcf_model.find('site', arm_base_site_name) self._gripper_ik_site = self._gripper.tool_center_point @property def name(self) -> str: return self._name @property def sensors(self) -> Sequence[moma_sensor.Sensor]: return self._robot_sensors @property def effectors(self) -> List[effector.Effector]: effectors = [self._arm_effector] if self.gripper_effector is not None: assert self.gripper_effector is not None # This placates pytype. effectors.append(self.gripper_effector) return effectors @property def arm_effector(self) -> effector.Effector: return self._arm_effector @property def gripper_effector(self) -> Optional[effector.Effector]: return self._gripper_effector @property def arm(self) -> Arm: return self._arm @property def gripper(self) -> Gripper: return self._gripper @property def wrist_ft(self): return self._wrist_ft @property def wrist_cameras(self) -> Sequence[prop.Camera]: return self._wrist_cameras @property def arm_base_site(self): """Returns a site at the base of the arm.""" return self._arm_base_site @property def arm_frame(self): return traversal_utils.get_attachment_frame(self._arm.mjcf_model) def position_gripper(self, physics: mjcf.Physics, position: np.ndarray, quaternion: np.ndarray, settle_physics: bool = False): """Moves the gripper ik point position to the (pos, quat) pose tuple. Args: physics: An MJCF physics. position: The cartesian position of the desired pose given in the world frame. quaternion: The quaternion (wxyz) giving the desired orientation of the gripper in the world frame. settle_physics: If True, will step the physics simulation until the arm joints has velocity and acceleration below a certain threshold. Raises: ValueError: If the gripper cannot be placed at the desired pose. """ # Initialize the ik solver. We create a new version of the solver at every # solve because there is no guarantee that the mjcf_model has not been # modified. mjcf_model = self._arm.mjcf_model.root_model solver = ik_solver.IkSolver( mjcf_model, self._arm.joints, self._gripper_ik_site) qpos = solver.solve(ref_pose=geometry.Pose(position, quaternion)) if qpos is None: if self.gripper_effector is not None: gripper_prefix = self.gripper_effector.prefix # pytype: disable=attribute-error else: gripper_prefix = 'gripper' raise ValueError('IK Failed to converge to the desired target pose' f'{geometry.Pose(position, quaternion)} ' f'for {gripper_prefix} of {self._arm.name}') self.position_arm_joints(physics, qpos, settle_physics=settle_physics) def position_arm_joints( self, physics: mjcf.Physics, joint_angles: np.ndarray, settle_physics: bool = False, max_settle_physics_time: float = _MAX_SETTLE_PHYSICS_TIME, max_qvel_tol=_SETTLE_QVEL_TOL, max_qacc_tol=_SETTLE_QACC_TOL, ): """Move the arm to the desired joint configuration. Args: physics: Instancoe of an mjcf physics. joint_angles: Desired joint angle configuration. settle_physics: If true will step the simulation until the joints have velocity and accelerations lower than `max_qvel_tol` and `max_qacc_tol`. This is desired when the simulation is altered and the robot is not stable in the desired joint configuration. This is for example the case when applying domain randomization to the gears in the simulation. This affects the different forces applied by the actuators and results in movements at the beginning of the episode. Settling the physics prevents this. max_settle_physics_time: Maximum simulation time that we want the physics to settle for. max_qvel_tol: Maximum velocity any joint should have to consider the physics 'settled'. max_qacc_tol: Maximum acceleration any joint should have to consider the physics 'settled'. """ self.arm.set_joint_angles(physics, joint_angles) if settle_physics: # We let the simulation settle once the robot joints have been set. This # is to ensure that the robot is not moving at the beginning of the # episode. original_time = physics.data.time joint_isolator = utils.JointStaticIsolator(physics, self.arm.joints) joints_mj = physics.bind(self.arm.joints) assert joints_mj is not None while physics.data.time - original_time < max_settle_physics_time: with joint_isolator: physics.step() max_qvel = np.max(np.abs(joints_mj.qvel)) max_qacc = np.max(np.abs(joints_mj.qacc)) if (max_qvel < max_qvel_tol) and (max_qacc < max_qacc_tol): break physics.data.time = original_time def standard_compose( arm: Arm, gripper: Gripper, wrist_ft: Optional[composer.Entity] = None, wrist_cameras: Sequence[prop.Camera] = () ) -> None: """Creates arm and attaches gripper.""" if wrist_ft: wrist_ft.attach(gripper) arm.attach(wrist_ft) else: arm.attach(gripper) for cam in wrist_cameras: arm.attach(cam, arm.wrist_site)
dm_robotics-main
py/moma/robot.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 moma_option.""" from unittest import mock from absl.testing import absltest import dm_env from dm_robotics import agentflow as af from dm_robotics.moma import moma_option import numpy as np class MomaOptionTest(absltest.TestCase): def _create_agentflow_lambda_option(self, on_step_func): return af.LambdaOption( delegate=af.FixedOp( action=np.array([], dtype=np.float64), num_steps=1, name='test_option'), on_step_func=on_step_func) def test_sequence_of_options(self): """This tests a sequence of MomaOption and af.coreOption.""" options_stepped = [] def build_option_name_appender(option_name): nonlocal options_stepped def append_option_name(timestep): nonlocal options_stepped # When af.Sequence switches from one option to another, the # previous option gets one more "last" timestep sent to it. # Ignore this in our counting, since we just want to ensure # that both options are stepped. if not timestep.last(): options_stepped.append(option_name) return append_option_name first_option = moma_option.MomaOption( physics_getter=mock.MagicMock(), effectors=[], delegate=self._create_agentflow_lambda_option( build_option_name_appender('first'))) second_option = self._create_agentflow_lambda_option( build_option_name_appender('second')) option_to_test = moma_option.MomaOption( physics_getter=mock.MagicMock(), effectors=[], delegate=af.Sequence([ first_option, second_option, ], allow_stepping_after_terminal=False)) irrelevant_timestep_params = { 'reward': 0, 'discount': 0, 'observation': np.array([], dtype=np.float64) } option_to_test.step(dm_env.TimeStep(dm_env.StepType.FIRST, **irrelevant_timestep_params)) self.assertEqual(options_stepped, ['first']) option_to_test.step(dm_env.TimeStep(dm_env.StepType.MID, **irrelevant_timestep_params)) self.assertEqual(options_stepped, ['first', 'second']) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/moma_option_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Action spaces for manipulation.""" from typing import Callable, List, Optional, Sequence from dm_control import mjcf # type: ignore from dm_env import specs from dm_robotics import agentflow as af from dm_robotics.agentflow import spec_utils from dm_robotics.geometry import geometry from dm_robotics.geometry import mujoco_physics import numpy as np def action_limits( cartesian_translation_action_limit: List[float], cartesian_rotation_action_limit: List[float]) -> List[float]: """Returns the action limits for the robot in this subtask.""" if len(cartesian_translation_action_limit) == 3: cartesian_vals = cartesian_translation_action_limit else: assert len(cartesian_translation_action_limit) == 1 cartesian_vals = cartesian_translation_action_limit * 3 if len(cartesian_rotation_action_limit) == 3: euler_vals = cartesian_rotation_action_limit else: assert len(cartesian_rotation_action_limit) == 1 euler_vals = cartesian_rotation_action_limit * 3 return cartesian_vals + euler_vals class _DelegateActionSpace(af.ActionSpace[specs.BoundedArray]): """Delegate action space. Base class for delegate action spaces that exist to just give a specific type for an action space object (vs using prefix slicer directly). """ def __init__(self, action_space: af.ActionSpace[specs.BoundedArray]): self._action_space = action_space @property def name(self): return self._action_space.name def spec(self) -> specs.BoundedArray: return self._action_space.spec() def project(self, action: np.ndarray) -> np.ndarray: assert len(action) == self._action_space.spec().shape[0] return self._action_space.project(action) class ArmJointActionSpace(_DelegateActionSpace): """Arm joint action space. This is just giving a type name to a particular action space. I.e. while it just delegates to the underlying action space, the name tells us that this projects from an arm joint space to some other space. """ pass class GripperActionSpace(_DelegateActionSpace): """Gripper action space. This is just giving a type name to a particular action space. I.e. while it just delegates to the underlying action space, the name tells us that this projects from a gripper joint space to some other space. """ pass class CartesianTwistActionSpace(_DelegateActionSpace): """Cartesian Twist action space. This is just giving a type name to a particular action space. I.e. while it just delegates to the underlying action space, the name tells us that this projects from a cartesian twist space to some other space. """ pass class RobotArmActionSpace(_DelegateActionSpace): """Action space for a robot arm. This is just giving a type name to a particular action space. I.e. while it just delegates to the underlying action space, the name tells us that this projects an action for the arm. This should be used when users don't care about the nature of the underlying action space (for example, joint action space or cartesian action space). """ pass class ReframeVelocityActionSpace(af.ActionSpace): """Transforms a twist from one frame to another.""" def __init__(self, spec: specs.BoundedArray, physics_getter: Callable[[], mjcf.Physics], input_frame: geometry.Frame, output_frame: geometry.Frame, name: str = 'ReframeVelocity', *, velocity_dims: Optional[Sequence[int]] = None): """Initializes ReframeVelocityActionSpace. Args: spec: The spec for the original un-transformed action. physics_getter: A callable returning a mjcf.Physics input_frame: The frame in which the input twist is defined. output_frame: The frame in which the output twist should be expressed. name: A name for this action_space. velocity_dims: Optional sub-dimensions of the full twist which the action will contain. This can be used to allow `ReframeVelocityActionSpace` to operate on reduced-DOF cartesian action-spaces, e.g. the 4D used by the RGB-stacking tasks. To use, velocity_dims should have the same shape as `spec.shape`, and contain the indices of the twist that that action space uses (e.g. [0, 1, 2, 5] for `Cartesian4dVelocityEffector`). """ self._spec = spec self._physics_getter = physics_getter self._physics = mujoco_physics.from_getter(physics_getter) self._input_frame = input_frame self._output_frame = output_frame self._name = name if velocity_dims is not None and np.shape(velocity_dims) != spec.shape: raise ValueError(f'Expected velocity_dims to have shape {spec.shape} but ' f'it has shape {np.shape(velocity_dims)}.') self._velocity_dims = velocity_dims @property def name(self) -> str: return self._name def spec(self) -> specs.BoundedArray: return self._spec def project(self, action: np.ndarray) -> np.ndarray: if self._velocity_dims is not None: # If action isn't a full twist (e.g. 4-DOF cartesian action space), expand # it for the frame-transformation operation. full_action = np.zeros(6) full_action[self._velocity_dims] = action action = full_action input_twist = geometry.TwistStamped(action, self._input_frame) output_twist = input_twist.to_frame( self._output_frame, physics=self._physics) output_action = output_twist.twist.full if self._velocity_dims is not None: # If action was reduced-dof, slice out the original dims. output_action = output_action[self._velocity_dims] return spec_utils.shrink_to_fit(value=output_action, spec=self._spec)
dm_robotics-main
py/moma/action_spaces.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Moma SubTask Option.""" import re from typing import Callable, Iterable, List, Optional from dm_control import mjcf import dm_env from dm_env import specs from dm_robotics import agentflow as af from dm_robotics.agentflow import spec_utils from dm_robotics.moma import effector import numpy as np def _find_actuator_indices(prefix: str, spec: specs.Array) -> List[bool]: actuator_names = spec.name.split('\t') prefix_expr = re.compile(prefix) return [re.match(prefix_expr, name) is not None for name in actuator_names] class MomaOption(af.DelegateOption): """Adapts an option to control a specific set of effectors. The Moma BaseTask is not actuated through the before_step method. Rather, individual effectors that comprise the base task are controlled individually. This is done by calling their set_control method. This is done so that each Subtask/Option can determine which effectors it controls explicitly, rather than being forced to control all of them. The MomaOption wrapper allows adapting an Option to run against a Moma BaseTask by facilitating the control of a subset of effectors. """ def __init__(self, physics_getter: Callable[[], mjcf.Physics], effectors: Iterable[effector.Effector], delegate: af.Option, name: Optional[str] = None): super().__init__(delegate, name) self._physics_getter = physics_getter self._effectors = list(effectors) self._action_spec = None def step(self, parent_timestep: dm_env.TimeStep) -> np.ndarray: if self._action_spec is None: aspecs = [a.action_spec(self._physics_getter()) for a in self._effectors] self._action_spec = spec_utils.merge_specs(aspecs) action = self.step_delegate(parent_timestep) self._set_control(physics=self._physics_getter(), command=action) # Moma environment step takes zero-length actions. The actuators are driven # directly through effectors rather than through the monolithic per-step # action. return np.array([], dtype=np.float32) def step_delegate(self, parent_timestep: dm_env.TimeStep) -> np.ndarray: return super().step(parent_timestep) def _set_control(self, physics: mjcf.Physics, command: np.ndarray): if len(command) == 0: # pylint: disable=g-explicit-length-test # If the command is empty, there isn't anything to do. # Empty MomaOptions can be used to wrap other MomaOptions that are in # charge of controlling individual effectors. return spec_utils.validate(self._action_spec, command) for ef in self._effectors: e_cmd = command[_find_actuator_indices(ef.prefix, self._action_spec)] ef.set_control(physics, e_cmd)
dm_robotics-main
py/moma/moma_option.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Builder for a SubTaskEnvironment.""" from typing import Optional, Sequence from dm_control import composer from dm_robotics import agentflow as af from dm_robotics.agentflow import spec_utils from dm_robotics.agentflow.preprocessors import timestep_preprocessor from dm_robotics.agentflow.subtasks import parameterized_subtask from dm_robotics.moma import base_task from dm_robotics.moma import effector from dm_robotics.moma import moma_option from dm_robotics.moma import subtask_env import numpy as np # Internal profiling class ComposerEnvironmentForRealMoMaSetup(composer.Environment): """Sublclass of composer environment used when building a real MoMa setup. When we use a real environment, we want to make sure the environment loop is as fast as possible. To do this, we remove the unessary physics simulation stepping. This is done by overriding the relevant class """ def _substep(self, action: np.ndarray): """In case of real environment we don't want to step the phyics.""" class SubtaskEnvBuilder(object): """Builder for a SubTaskEnvironment.""" def __init__(self): self._task = None # type: Optional[base_task.BaseTask] self._base_env = None # type: Optional[composer.Environment] self._action_space = None # type: Optional[af.ActionSpace] self._preprocessors = [] # timestep_preprocessor.TimestepPreprocessor self._reset_option = None # type: Optional[moma_option.MomaOption] self._effectors = None # type: Optional[Sequence[effector.Effector]] def set_task(self, task: base_task.BaseTask) -> 'SubtaskEnvBuilder': self._task = task return self def set_action_space(self, action_space) -> 'SubtaskEnvBuilder': self._action_space = action_space return self def set_reset_option(self, reset_option: moma_option.MomaOption ) -> 'SubtaskEnvBuilder': self._reset_option = reset_option return self def set_effectors( self, effectors: Sequence[effector.Effector]) -> 'SubtaskEnvBuilder': """Allow the effectors to be changed, post-construction.""" self._effectors = effectors return self def add_preprocessor( self, preprocessor: timestep_preprocessor.TimestepPreprocessor ) -> 'SubtaskEnvBuilder': self._preprocessors.append(preprocessor) return self def build_base_env(self, real_env=False) -> composer.Environment: """Builds the base composer.Environment. Factored out as a separate call to allow users to build the base composer env before calling the top-level `build` method. This can be necessary when preprocessors require parameters from the env, e.g. action specs. Args: real_env: If True, will ignore the physics simulation loop. Returns: The base composer.Environment """ if self._task is None: raise ValueError('Cannot build the base_env until the task is built') if self._base_env is None: if real_env: # We set the physics timestep to the control timestep, this ensures that # we are making only a single substep of the composer environment. self._task.physics_timestep = self._task.control_timestep # We then use our custom compoer environment to ensure that we are not # stepping the phyiscs and therefore running the environment faster. self._base_env = ComposerEnvironmentForRealMoMaSetup( self._task, strip_singleton_obs_buffer_dim=True, raise_exception_on_physics_error=True) else: self._base_env = composer.Environment( self._task, strip_singleton_obs_buffer_dim=True) return self._base_env # Profiling for .wrap() def build(self) -> subtask_env.SubTaskEnvironment: """Builds the SubTaskEnvironment from the set components.""" # Ensure base_env has been built. base_env = self.build_base_env() parent_spec = spec_utils.TimeStepSpec(base_env.observation_spec(), base_env.reward_spec(), base_env.discount_spec()) preprocessor = timestep_preprocessor.CompositeTimestepPreprocessor( *self._preprocessors) if self._action_space is None: raise ValueError( 'Cannot build the subtask envrionment until the action space is set') subtask = parameterized_subtask.ParameterizedSubTask( parent_spec=parent_spec, action_space=self._action_space, timestep_preprocessor=preprocessor, name=self._task.name()) # Use the specified effectors if they exist, otherwise default to using all # of the effectors in the base task. effectors = self._effectors or list(self._task.effectors) # Check if there are effectors. if not effectors: raise ValueError( 'Cannot build the subtask envrionment if there are no effectors.') reset_option = (self._reset_option or self._build_noop_reset_option(base_env, effectors)) return subtask_env.SubTaskEnvironment( env=base_env, effectors=effectors, subtask=subtask, reset_option=reset_option) def _build_noop_reset_option( self, env: composer.Environment, effectors: Sequence[effector.Effector] ) -> moma_option.MomaOption: """Builds a no-op MoMa option.""" parent_action_spec = self._task.effectors_action_spec( physics=env.physics, effectors=effectors) noop_action = spec_utils.zeros(parent_action_spec) delegate = af.FixedOp(noop_action, name='NoOp') return moma_option.MomaOption( physics_getter=lambda: env.physics, effectors=effectors, delegate=delegate)
dm_robotics-main
py/moma/subtask_env_builder.py
# Copyright 2022 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 action_spaces.""" from unittest import mock from absl.testing import absltest from absl.testing import parameterized from dm_control import mjcf from dm_env import specs from dm_robotics.agentflow import spec_utils from dm_robotics.geometry import geometry as geo from dm_robotics.moma import action_spaces import numpy as np SEED = 0 class ReframeVelocityActionSpaceTest(parameterized.TestCase): @parameterized.named_parameters( ('_full', None), ('_pos_dims', [0, 1, 2]), ('_rot_dims', [3, 4, 5]), ('_mixed_dims', [0, 2, 4, 5]), ) def test_various_slices(self, velocity_dims): random_state = np.random.RandomState(SEED) action_dim = len(velocity_dims) if velocity_dims else 6 base_spec = specs.BoundedArray( shape=(action_dim,), dtype=np.float32, minimum=[-1] * action_dim, maximum=[1] * action_dim, name='\t'.join([f'a{i}' for i in range(action_dim)])) physics_getter = lambda: mock.MagicMock(spec=mjcf.Physics) for _ in range(10): parent_frame = geo.PoseStamped( geo.Pose.from_poseuler(random_state.randn(6)), frame=None) input_frame = geo.PoseStamped( geo.Pose.from_poseuler(random_state.randn(6)), parent_frame) output_frame = geo.PoseStamped( geo.Pose.from_poseuler(random_state.randn(6)), parent_frame) reframe_space = action_spaces.ReframeVelocityActionSpace( spec=base_spec, physics_getter=physics_getter, input_frame=input_frame, output_frame=output_frame, velocity_dims=velocity_dims, name='test ReframeVelocity') input_action = random_state.randn(action_dim) if velocity_dims is not None: full_action = np.zeros(6) full_action[velocity_dims] = input_action else: full_action = input_action input_twist = geo.TwistStamped(geo.Twist(full_action), input_frame) expected_output_action = input_twist.get_relative_twist(output_frame).full if velocity_dims is not None: expected_output_action = expected_output_action[velocity_dims] output_action = reframe_space.project(input_action) expected_output_action = spec_utils.shrink_to_fit( value=expected_output_action, spec=base_spec) np.testing.assert_almost_equal(output_action, expected_output_action) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/action_spaces_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 AgentFlow Subtask to Environment adaptor.""" import re import traceback from typing import Callable, List, Sequence from absl import logging from dm_control import composer from dm_control import mjcf import dm_env from dm_robotics import agentflow as af from dm_robotics.agentflow import spec_utils from dm_robotics.moma import base_task from dm_robotics.moma import effector from dm_robotics.moma import moma_option import numpy as np # Internal profiling def _fixed_timestep(timestep: dm_env.TimeStep) -> dm_env.TimeStep: if timestep.reward is None: timestep = timestep._replace(reward=0.0) if timestep.discount is None: timestep = timestep._replace(discount=1.0) return timestep class SubTaskEnvironment(dm_env.Environment): """SubTask to `dm_env.Environment` adapter. One important note is that users need to either call close() on the environment when they are done using it or they should use them within a context manager. Example: with subtask_env() as env: ... """ def __init__(self, env: composer.Environment, effectors: Sequence[effector.Effector], subtask: af.SubTask, reset_option: moma_option.MomaOption): if env is None: raise ValueError('env is None') if subtask is None: raise ValueError('subtask is None') if reset_option is None: raise ValueError('reset_option is None') if not effectors: raise ValueError('no effectors specified') self._env = env self._effectors = effectors self._subtask = subtask self._reset_option = reset_option self._reset_required = True self._last_internal_timestep = None # type: dm_env.TimeStep self._last_external_timestep = None # type: dm_env.TimeStep # Stub action for the moma task step. Actual actuation is done directly # through effectors. self._stub_env_action = np.zeros_like( self._env.action_spec().generate_value()) self._effectors_action_spec = None self._observers = [] # type: List [af.SubTaskObserver] self._teardown_callables = [] # type: List [Callable[[], None]] self._is_closed = False # type: bool # If the user does not close the environment we issue an error and # print out where the environment was created self._traceback = traceback.format_stack() def __del__(self): if not self._is_closed: logging.error( 'You must call .close() on the environment created at:\n %s', ''.join(self._traceback)) # Profiling for .wrap() def reset(self) -> dm_env.TimeStep: if self._is_closed: raise RuntimeError( 'The environment has been closed, it can no longer be used.') env_timestep = _fixed_timestep(self._env.reset()) self._reset_option.on_selected(timestep=env_timestep) # Run the reset option to completion. pterm = 0 # An option is stepped before we ask for pterm. while pterm < np.random.random(): # The reset_option is a MomaOption which handles actuating the effectors # internally. self._reset_option.step(env_timestep) env_timestep = self._env.step(self._stub_env_action) pterm = self._reset_option.pterm(env_timestep) # Send LAST timestep to reset option's delegate. This means we want to # step the option without actuating the effectors. Ignore the action it # returns. self._reset_option.step_delegate( env_timestep._replace(step_type=dm_env.StepType.LAST)) # send env_timestep through the subtask. self._last_internal_timestep = env_timestep._replace( step_type=dm_env.StepType.FIRST) self._subtask.reset(env_timestep) timestep = self._subtask.parent_to_agent_timestep( self._last_internal_timestep, own_arg_key=self._subtask.get_arg_key(None)) self._reset_required = False if not timestep.first(): raise ValueError(f'SubTask returned non FIRST timestep: {timestep}') timestep = timestep._replace(reward=None) timestep = timestep._replace(discount=None) self._last_external_timestep = timestep return timestep # Profiling for .wrap() def step(self, action: np.ndarray) -> dm_env.TimeStep: if self._is_closed: raise RuntimeError( 'The environment has been closed, it can no longer be used.') if self._reset_required: return self.reset() # `action` is deliberately ignored. # subtask_env does not use Option-argument mechanism. dummy_arg_key = self._subtask.get_arg_key(None) pterm = self._subtask.pterm(self._last_internal_timestep, dummy_arg_key) action = action.astype(self._subtask.action_spec().dtype) external_action = np.clip(action, self._subtask.action_spec().minimum, self._subtask.action_spec().maximum) internal_action = self._subtask.agent_to_parent_action(external_action) for obs in self._observers: obs.step( parent_timestep=self._last_internal_timestep, parent_action=internal_action, agent_timestep=self._last_external_timestep, agent_action=external_action) self._actuate_effectors(internal_action) internal_timestep = self._env.step(self._stub_env_action) # If subtask wanted to stop, this is the last timestep. if pterm > np.random.random(): internal_timestep = internal_timestep._replace( step_type=dm_env.StepType.LAST) self._last_internal_timestep = internal_timestep external_timestep = self._subtask.parent_to_agent_timestep( internal_timestep, dummy_arg_key) # If subtask or base env emit a LAST timestep, we need to reset next. if external_timestep.last(): self._reset_required = True # For a LAST timestep, step the observers with a None action. This ensures # the observers will see every timestep of the task. for obs in self._observers: obs.step( parent_timestep=internal_timestep, parent_action=None, agent_timestep=external_timestep, agent_action=None) # This shouldn't happen, but just in case. if external_timestep.first(): external_timestep = external_timestep._replace(reward=None) external_timestep = external_timestep._replace(discount=None) self._last_external_timestep = external_timestep return external_timestep def _actuate_effectors(self, action): if self._effectors_action_spec is None: aspecs = [a.action_spec(self.physics) for a in self._effectors] self._effectors_action_spec = spec_utils.merge_specs(aspecs) spec_utils.validate(self._effectors_action_spec, action) for ef in self._effectors: e_cmd = action[self._find_effector_indices(ef)] ef.set_control(self.physics, e_cmd) def _find_effector_indices(self, ef: effector.Effector) -> List[bool]: actuator_names = self._effectors_action_spec.name.split('\t') prefix_expr = re.compile(ef.prefix) return [re.match(prefix_expr, name) is not None for name in actuator_names] def observation_spec(self): return self._subtask.observation_spec() def action_spec(self): return self._subtask.action_spec() def reward_spec(self): return self._subtask.reward_spec() def discount_spec(self): return self._subtask.discount_spec() @property def base_env(self) -> composer.Environment: return self._env @property def physics(self) -> mjcf.Physics: return self._env.physics @property def task(self) -> composer.Task: """Returns the underlying composer.Task, defining the world.""" return self._env.task @property def subtask(self) -> af.SubTask: """Returns the underlying agentflow.SubTask, defining the task.""" return self._subtask @property def reset_option(self) -> moma_option.MomaOption: return self._reset_option @reset_option.setter def reset_option(self, reset_option: moma_option.MomaOption) -> None: """Changes the reset option. Sometimes the correct reset option is not constructible when the SubTaskEnvironment is initialized, so this property allows the caller to overwrite the original reset option. Args: reset_option: New reset option for this environment. """ self._reset_option = reset_option def add_observer(self, observer: af.SubTaskObserver) -> None: """Adds a subtask observer to the environment.""" self._observers.append(observer) def add_teardown_callable(self, teardown_fn: Callable[[], None]): """Adds a function to be called when the environment is closed. When running our environment we might need to start processes that need to be closed when we are done using the environment. Args: teardown_fn: Function to run when we close the environment. """ self._teardown_callables.append(teardown_fn) def close(self) -> None: """Cleanup when we are done using the environment.""" if self._is_closed: logging.warning('The environment has already been closed.') return # A MoMa base tasks holds all the effectors and sensors. When running a # real environment we need to make sure that we close all the sensors and # effectors used with the real robot. The `close` method of the task ensures # this. if isinstance(self.task, base_task.BaseTask): self.task.close() # Call all the provided teardowns when closing the environment. for teardown_callable in self._teardown_callables: teardown_callable() # Close the base class super().close() self._is_closed = True
dm_robotics-main
py/moma/subtask_env.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 action_sensor.""" from absl.testing import absltest from dm_env import specs from dm_robotics.moma import effector as moma_effector from dm_robotics.moma.sensors import action_sensor import numpy as np _DOFS = 7 class _FooEffector(moma_effector.Effector): def __init__(self): pass def initialize_episode(self, physics, random_state) -> None: pass def action_spec(self, physics) -> specs.BoundedArray: return specs.BoundedArray( shape=(_DOFS,), dtype=np.float64, minimum=np.ones((_DOFS,)) * -1.0, maximum=np.ones((_DOFS,))) def set_control(self, physics, command: np.ndarray) -> None: pass @property def prefix(self) -> str: return 'foo_effector' @property def previous_action(self) -> np.ndarray: return self._previous_action class ActionSensorTest(absltest.TestCase): def test_observation_name(self): effector = _FooEffector() effector, sensor = action_sensor.create_sensed_effector(effector) expected_obs_key = 'foo_effector_previous_action' obs_key = sensor.get_obs_key( action_sensor.Observations.PREVIOUS_ACTION) self.assertEqual(expected_obs_key, obs_key) def test_read_previous_action(self): effector = _FooEffector() effector, sensor = action_sensor.create_sensed_effector(effector) command = np.ones(_DOFS) * 0.3 effector.set_control(None, command) obs_key = 'foo_effector_previous_action' np.testing.assert_allclose(command, sensor.observables[obs_key](None)) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/sensors/action_sensor_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sensor for tracking the pose of props in the arena.""" import enum from typing import Dict, Iterable, List from dm_control import mjcf from dm_control.composer.observation import observable from dm_robotics.moma import prop as moma_prop from dm_robotics.moma import sensor as moma_sensor from dm_robotics.moma.utils import pose_utils import numpy as np @enum.unique class Observations(enum.Enum): """Observations exposed by this sensor.""" # The pose of the prop, given as [x, y, z, quat_w, quat_x, quat_y, quat_z]. POSE = '{}_pose' def get_obs_key(self, name: str) -> str: """Returns the key to the observation in the observables dict.""" return self.value.format(name) class PropPoseSensor(moma_sensor.Sensor[Observations]): """Tracks the world pose of an object in the arena.""" def __init__(self, prop: moma_prop.Prop, name: str): self._prop = prop self._name = name self._observables = { self.get_obs_key(Observations.POSE): observable.Generic(self._pose), } for obs in self._observables.values(): obs.enabled = True def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: pass @property def observables(self) -> Dict[str, observable.Observable]: return self._observables @property def name(self) -> str: return self._name def get_obs_key(self, obs: Observations) -> str: return obs.get_obs_key(self._name) def _pose(self, physics: mjcf.Physics) -> np.ndarray: pos, quat = self._prop.get_pose(physics) return np.append(pos, pose_utils.positive_leading_quat(quat)) def build_prop_pose_sensors( props: Iterable[moma_prop.Prop]) -> List[PropPoseSensor]: return [PropPoseSensor(prop=p, name=p.name) for p in props]
dm_robotics-main
py/moma/sensors/prop_pose_sensor.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 site_sensor.""" from absl.testing import absltest from dm_control import mjcf from dm_robotics.moma.sensors import site_sensor from dm_robotics.transformations import transformations as tr import numpy as np class SiteSensorTest(absltest.TestCase): def test_read_value_from_sensor(self): # We create a mjcf body with a site we want to measure. mjcf_root = mjcf.RootElement() box_body = mjcf_root.worldbody.add( "body", pos="0 0 0", axisangle="0 0 1 0", name="box") box_body.add("inertial", pos="0. 0. 0.", mass="1", diaginertia="1 1 1") box_body.add("freejoint") site = box_body.add("site", pos="0 0 0") # Get expected values expected_pos = np.array([1., 2., 3.]) expected_quat = np.array([4.0, 5.0, 6.0, 7.0]) expected_quat = expected_quat/ np.linalg.norm(expected_quat) expected_rmat = np.reshape(tr.quat_to_mat(expected_quat)[:3, :3], (9,)) expected_vel = np.array([8., 9., 10., 11., 12., 13.]) # We then set the position and velocity of the body physics = mjcf.Physics.from_mjcf_model(mjcf_root) physics.data.qpos[:] = np.hstack((expected_pos, expected_quat)) physics.data.qvel[:] = expected_vel physics.forward() # Read the measurements of the sensors and ensure everything is correct sensor = site_sensor.SiteSensor(site, "test_site") pos_callable = sensor.observables[ sensor.get_obs_key(site_sensor.Observations.POS)] np.testing.assert_allclose(expected_pos, pos_callable(physics)) quat_callable = sensor.observables[ sensor.get_obs_key(site_sensor.Observations.QUAT)] np.testing.assert_allclose(expected_quat, quat_callable(physics)) rmat_callable = sensor.observables[ sensor.get_obs_key(site_sensor.Observations.RMAT)] np.testing.assert_allclose(expected_rmat, rmat_callable(physics)) # The qvel that is set has the linear velocity expressed in the world # frame orientation and the angular velocity expressed in the body frame # orientation. We therefore test that the values appear where they should. vel_world_callable = sensor.observables[ sensor.get_obs_key(site_sensor.Observations.VEL_WORLD)] np.testing.assert_allclose( expected_vel[:3], vel_world_callable(physics)[:3]) vel_relative_callable = sensor.observables[ sensor.get_obs_key(site_sensor.Observations.VEL_RELATIVE)] np.testing.assert_allclose( expected_vel[3:], vel_relative_callable(physics)[3:]) def test_passing_a_non_site_raise(self): # We create a mjcf body with a site we want to measure. mjcf_root = mjcf.RootElement() box_body = mjcf_root.worldbody.add( "body", pos="0 0 0", axisangle="0 0 1 0", name="box") with self.assertRaises(ValueError): site_sensor.SiteSensor(box_body, "error") if __name__ == "__main__": absltest.main()
dm_robotics-main
py/moma/sensors/site_sensor_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 external_value_sensor.""" from absl.testing import absltest from absl.testing import parameterized from dm_control import mjcf from dm_robotics.moma.models.arenas import empty from dm_robotics.moma.sensors import external_value_sensor import numpy as np class ExternalValueSensorTest(parameterized.TestCase): @parameterized.parameters([ [np.array([1.0, 2.0]), np.array([3.0, 4.0])], ]) def test_external_value_set(self, init_val, set_val): arena = empty.Arena() physics = mjcf.Physics.from_mjcf_model(arena.mjcf_model) sensor = external_value_sensor.ExternalValueSensor( name='test_sensor', initial_value=init_val) self.assertEqual('test_sensor', sensor.get_obs_key(None)) self.assertIn(sensor.get_obs_key(None), sensor.observables) cur_value = sensor.observables[sensor.get_obs_key(None)](physics) self.assertTrue(np.allclose(cur_value, init_val)) sensor.set_value(set_val) cur_value = sensor.observables[sensor.get_obs_key(None)](physics) self.assertTrue(np.allclose(cur_value, set_val)) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/sensors/external_value_sensor_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 camera sensors.""" import itertools from absl.testing import absltest from absl.testing import parameterized from dm_control import mjcf from dm_robotics.moma.sensors import camera_sensor class CameraPoseSensorTest(absltest.TestCase): def setUp(self): super().setUp() mjcf_root = mjcf.element.RootElement(model='camera') mjcf_root.worldbody.add('body', name='prop_root') prop_root = mjcf_root.find('body', 'prop_root') prop_root.add( 'camera', name='test_camera', pos=[0., 0., 0.], quat=[0., 0., 0., 0.], fovy=90.0) self._camera_element = mjcf_root.find('camera', 'test_camera') def test_pose_camera(self): sensor_name = 'pose_test' sensor = camera_sensor.CameraPoseSensor( camera_element=self._camera_element, name=sensor_name) expected_obs = [ f'{sensor_name}_pos', f'{sensor_name}_quat', f'{sensor_name}_pose', ] self.assertCountEqual(sensor.observables.keys(), expected_obs) class CameraImageSensorTest(parameterized.TestCase): def setUp(self): super().setUp() mjcf_root = mjcf.element.RootElement(model='camera') mjcf_root.worldbody.add('body', name='prop_root') prop_root = mjcf_root.find('body', 'prop_root') prop_root.add( 'camera', name='test_camera', pos=[0., 0., 0.], quat=[0., 0., 0., 0.], fovy=90.0) self._camera_element = mjcf_root.find('camera', 'test_camera') @parameterized.parameters( itertools.product([True, False], [True, False], [True, False])) def test_camera(self, has_rgb, has_depth, has_segmentation): sensor_name = 'camera_sensor_test' camera_config = camera_sensor.CameraConfig( width=128, height=128, fovy=45., has_rgb=has_rgb, has_depth=has_depth, has_segmentation=has_segmentation, ) sensor = camera_sensor.CameraImageSensor( camera_element=self._camera_element, config=camera_config, name=sensor_name, ) expected_obs = [f'{sensor_name}_intrinsics'] if has_rgb: expected_obs.append(f'{sensor_name}_rgb_img') if has_depth: expected_obs.append(f'{sensor_name}_depth_img') if has_segmentation: expected_obs.append(f'{sensor_name}_segmentation_img') self.assertCountEqual(sensor.observables.keys(), expected_obs) class CameraSensorBundleTest(absltest.TestCase): def setUp(self): super().setUp() mjcf_root = mjcf.element.RootElement(model='camera') mjcf_root.worldbody.add('body', name='prop_root') prop_root = mjcf_root.find('body', 'prop_root') prop_root.add( 'camera', name='test_camera', pos=[0., 0., 0.], quat=[0., 0., 0., 0.], fovy=90.0) self._camera_element = mjcf_root.find('camera', 'test_camera') def test_rgb_camera(self): sensor_name = 'rgb_test' camera_config = camera_sensor.CameraConfig( width=128, height=128, fovy=45., has_rgb=True, has_depth=False, ) sensor_bundle = camera_sensor.get_sensor_bundle( camera_element=self._camera_element, config=camera_config, name=sensor_name) self.assertIsInstance(sensor_bundle[0], camera_sensor.CameraPoseSensor) self.assertIsInstance(sensor_bundle[1], camera_sensor.CameraImageSensor) class SensorCreationTest(absltest.TestCase): def test_sensor_creation(self): mjcf_root = mjcf.element.RootElement(model='camera') mjcf_root.worldbody.add('body', name='prop_root') prop_root = mjcf_root.find('body', 'prop_root') prop_root.add('camera', name='camera1', pos=[0., 0., 0.], quat=[0., 0., 0., 0.], fovy=90.0) prop_root.add('camera', name='camera2', pos=[0., 0., 0.], quat=[0., 0., 0., 0.], fovy=90.0) camera_configurations = { 'camera1': camera_sensor.CameraConfig( width=128, height=128, fovy=90.0, has_rgb=True, has_depth=False), 'camera2': camera_sensor.CameraConfig( width=128, height=128, fovy=90.0, has_rgb=True, has_depth=False) } mjcf_full_identifiers = {'camera1': 'camera1', 'camera2': 'camera2'} sensors = camera_sensor.build_camera_sensors( camera_configurations, mjcf_root, mjcf_full_identifiers) self.assertLen(sensors, 4) self.assertIsInstance(sensors[0], camera_sensor.CameraPoseSensor) self.assertIsInstance(sensors[1], camera_sensor.CameraImageSensor) self.assertIsInstance(sensors[2], camera_sensor.CameraPoseSensor) self.assertIsInstance(sensors[3], camera_sensor.CameraImageSensor) def test_failure_for_non_matching_camera_keys(self): mjcf_root = mjcf.element.RootElement(model='camera') mjcf_root.worldbody.add('body', name='prop_root') prop_root = mjcf_root.find('body', 'prop_root') prop_root.add('camera', name='foo', pos=[0., 0., 0.], quat=[0., 0., 0., 0.], fovy=90.0) camera_configurations = { 'foo': camera_sensor.CameraConfig( width=128, height=128, fovy=90.0, has_rgb=True, has_depth=False), } mjcf_full_identifiers = {'not_foo': 'not_foo'} with self.assertRaises(ValueError): camera_sensor.build_camera_sensors( camera_configurations, mjcf_root, mjcf_full_identifiers) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/sensors/camera_sensor_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Enum to help key into a timestep's observations for the Robotiq gripper.""" import abc import enum from typing import Optional from dm_control import mjcf from dm_robotics.moma import sensor as moma_sensor import numpy as np @enum.unique class Observations(enum.Enum): """Observations exposed by a Robotiq gripper sensor.""" # The finger position of the gripper. POS = '{}_pos' # The finger velocity of the gripper. VEL = '{}_vel' # Whether an object is grasped by the gripper. GRASP = '{}_grasp' # Health status of the gripper. HEALTH_STATUS = '{}_health_status' def get_obs_key(self, name: str) -> str: """Returns the key to the observation in the observables dict.""" return self.value.format(name) @enum.unique class HealthStatus(enum.Enum): """Health status reported by the Robotiq gripper. In sim, we can assume the gripper is always `READY`, but for real Robotiq grippers, we get the health status from the hardware. """ UNKNOWN = 0 READY = 1 WARNING = 2 ERROR = 3 STALE = 4 class RobotiqGripperSensor( moma_sensor.Sensor[Observations], metaclass=abc.ABCMeta): @abc.abstractmethod def health_status(self, physics: Optional[mjcf.Physics] = None) -> np.ndarray: """Returns the health status observation for the robotiq sensor.""" pass
dm_robotics-main
py/moma/sensors/robotiq_gripper_observations.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sensor used for measuring positions and velocities of a mujoco site.""" import enum from typing import Dict from dm_control import mjcf from dm_control.composer.observation import observable from dm_robotics.moma import sensor as moma_sensor from dm_robotics.moma.sensors import mujoco_utils from dm_robotics.transformations import transformations as tr import numpy as np _MjcfElement = mjcf.element._ElementImpl # pylint: disable=protected-access @enum.unique class Observations(enum.Enum): """Observations exposed by this sensor.""" # The world x,y,z position of the site. POS = '{}_pos' # The world orientation quaternion of the site. QUAT = '{}_quat' # The concatenated world pos and quat x,y,z,w,i,j,k of the site. POSE = '{}_pose' # The world rotation matrix of the site. RMAT = '{}_rmat' # The Linear+Euler world velocity of the site. VEL_WORLD = '{}_vel_world' # The local velocity (as a twist) of the site in its own frame. VEL_RELATIVE = '{}_vel_relative' def get_obs_key(self, name: str) -> str: """Returns the key to the observation in the observables dict.""" return self.value.format(name) class SiteSensor(moma_sensor.Sensor[Observations]): """Sensor to measure position and velocity of a mujoco site.""" def __init__(self, site: _MjcfElement, name: str): if site.tag != 'site': raise ValueError( f'The provided mjcf element: {site} is not a mujoco site it is a ' f'{site.tag}.') self._site = site self._name = name self._observables = { self.get_obs_key(Observations.POS): observable.Generic(self._site_pos), self.get_obs_key(Observations.QUAT): observable.Generic(self._site_quat), self.get_obs_key(Observations.RMAT): observable.Generic(self._site_rmat), self.get_obs_key(Observations.POSE): observable.Generic(self._site_pose), self.get_obs_key(Observations.VEL_WORLD): observable.Generic(self._site_vel_world), self.get_obs_key(Observations.VEL_RELATIVE): observable.Generic(self._site_vel_relative), } for obs in self._observables.values(): obs.enabled = True def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: pass @property def observables(self) -> Dict[str, observable.Observable]: return self._observables @property def name(self) -> str: return self._name def get_obs_key(self, obs: Observations) -> str: return obs.get_obs_key(self._name) def _site_pos(self, physics: mjcf.Physics) -> np.ndarray: return physics.bind(self._site).xpos # pytype: disable=attribute-error def _site_quat(self, physics: mjcf.Physics) -> np.ndarray: quat = tr.mat_to_quat(np.reshape(self._site_rmat(physics), [3, 3])) return tr.positive_leading_quat(quat) def _site_rmat(self, physics: mjcf.Physics) -> np.ndarray: return physics.bind(self._site).xmat # pytype: disable=attribute-error def _site_pose(self, physics: mjcf.Physics) -> np.ndarray: # TODO(jscholz): rendundant with pos & quat; remove pos & quat? return np.concatenate((self._site_pos(physics), self._site_quat(physics)), axis=0) def _site_vel_world(self, physics: mjcf.Physics) -> np.ndarray: return mujoco_utils.get_site_vel( physics, self._site, world_frame=True) # pytype: disable=attribute-error def _site_vel_relative(self, physics: mjcf.Physics) -> np.ndarray: return mujoco_utils.get_site_vel( physics, self._site, world_frame=False) # pytype: disable=attribute-error
dm_robotics-main
py/moma/sensors/site_sensor.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sensor for a robot arm.""" from typing import Dict from dm_control import mjcf from dm_control.composer.observation import observable from dm_robotics.moma import sensor as moma_sensor from dm_robotics.moma.models.robots.robot_arms import robot_arm from dm_robotics.moma.sensors import joint_observations import numpy as np class RobotArmSensor(moma_sensor.Sensor[joint_observations.Observations]): """Robot arm sensor providing joint-related observations for sim arms.""" def __init__(self, arm: robot_arm.RobotArm, name: str, have_torque_sensors: bool = True): self._arm = arm self._name = name self._observables = { self.get_obs_key(joint_observations.Observations.JOINT_POS): observable.Generic(self._joint_pos), self.get_obs_key(joint_observations.Observations.JOINT_VEL): observable.Generic(self._joint_vel), } if have_torque_sensors: obs_key = self.get_obs_key(joint_observations.Observations.JOINT_TORQUES) self._observables[obs_key] = observable.Generic(self._joint_torques) for obs in self._observables.values(): obs.enabled = True def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: pass @property def observables(self) -> Dict[str, observable.Observable]: return self._observables @property def name(self) -> str: return self._name def get_obs_key(self, obs: joint_observations.Observations) -> str: return obs.get_obs_key(self._name) def _joint_pos(self, physics: mjcf.Physics) -> np.ndarray: return physics.bind(self._arm.joints).qpos # pytype: disable=attribute-error def _joint_vel(self, physics: mjcf.Physics) -> np.ndarray: return physics.bind(self._arm.joints).qvel # pytype: disable=attribute-error def _joint_torques(self, physics: mjcf.Physics) -> np.ndarray: return physics.bind(self._arm.joint_torque_sensors).sensordata[2::3] # pytype: disable=attribute-error
dm_robotics-main
py/moma/sensors/robot_arm_sensor.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sensor for gathering pose and image observations from mjcf cameras.""" import dataclasses import enum from typing import Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging from dm_control import mjcf from dm_control import mujoco from dm_control.composer.observation import observable from dm_control.mujoco.wrapper.mjbindings import enums from dm_robotics.moma import sensor as moma_sensor from dm_robotics.transformations import transformations as tr import numpy as np CameraSensorBundle = Tuple['CameraPoseSensor', 'CameraImageSensor'] # A quatenion representing a rotation from the mujoco camera, which has the -z # axis towards the scene, to the opencv camera, which has +z towards the scene. _OPENGL_TO_OPENCV_CAM_QUAT = np.array([0., 1., 0., 0.]) @enum.unique class PoseObservations(enum.Enum): """Pose observations exposed by a camera pose sensor.""" # The position of the camera. POS = '{}_pos' # The orientation of the camera. QUAT = '{}_quat' # The full pose of the camera, as 7-dim posquat. POSE = '{}_pose' def get_obs_key(self, name: str) -> str: """Returns the key to the observation in the observables dict.""" return self.value.format(name) @enum.unique class ImageObservations(enum.Enum): """Image observations exposed by a camera.""" # The rgb image sensed by the camera. RGB_IMAGE = '{}_rgb_img' # The depth image sensed by the camera. DEPTH_IMAGE = '{}_depth_img' # The segmentation image sensed by the camera. SEGMENTATION_IMAGE = '{}_segmentation_img' # The intrinsics of the cameras. INTRINSICS = '{}_intrinsics' def get_obs_key(self, name: str) -> str: """Returns the key to the observation in the observables dict.""" return self.value.format(name) @dataclasses.dataclass class CameraConfig: """Represents a camera config for the arena. Attributes: width: Width of the camera image. height: Height of the camera image. fovy: Vertical field of view of the camera, expressed in degrees. See http://www.mujoco.org/book/XMLreference.html#camera for more details. Note that we do not use the fovy defined in the `mjcf.Element` as it only contained the fovy information. And not the height which are linked (see `_get_instrinsics`). has_rgb: Is the camera producing rgb channels. has_depth: Is the camera producing a depth channel. has_segmentation: Is the camera producing a segmentation image. If `True`, adds a 2-channel NumPy int32 array of label values where the pixels of each object are labeled with the pair (mjModel ID, mjtObj object_type). Background pixels are labeled (-1, -1) render_shadows: If true the camera will render the shadows of the scene. Note that when using CPU for rendering, shadow rendering increases significantly the amount of processing time. """ width: int = 128 height: int = 128 fovy: float = 90.0 has_rgb: bool = True has_depth: bool = False has_segmentation: bool = False render_shadows: bool = False class CameraPoseSensor(moma_sensor.Sensor[PoseObservations]): """Sensor providing the camera pos observations.""" def __init__(self, camera_element: mjcf.Element, name: str): """Init. Args: camera_element: MJCF camera. name: Name of the pose sensor. """ self.element = camera_element self._name = name self._observables = { self.get_obs_key(PoseObservations.POS): observable.Generic(self._camera_pos), self.get_obs_key(PoseObservations.QUAT): observable.Generic(self._camera_quat), self.get_obs_key(PoseObservations.POSE): observable.Generic(self._camera_pose), } for obs in self._observables.values(): obs.enabled = True def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: pass @property def observables(self) -> Dict[str, observable.Observable]: return self._observables @property def name(self) -> str: return self._name def get_obs_key(self, obs: PoseObservations) -> str: return obs.get_obs_key(self._name) def _camera_pos(self, physics: mjcf.Physics) -> np.ndarray: return physics.bind(self.element).xpos # pytype: disable=attribute-error def _camera_quat(self, physics: mjcf.Physics) -> np.ndarray: # Rotate the camera to have +z towards the scene to be consistent with # real-robot camera calibration. mujoco_cam_quat = tr.mat_to_quat( np.reshape(physics.bind(self.element).xmat, (3, 3))) # pytype: disable=attribute-error return tr.quat_mul(mujoco_cam_quat, _OPENGL_TO_OPENCV_CAM_QUAT) def _camera_pose(self, physics: mjcf.Physics) -> np.ndarray: # TODO(jscholz): rendundant with pos & quat; remove pos & quat? return np.concatenate( (self._camera_pos(physics), self._camera_quat(physics)), axis=-1) class CameraImageSensor(moma_sensor.Sensor[ImageObservations]): """Camera sensor providing the image observations.""" def __init__(self, camera_element: mjcf.Element, config: CameraConfig, name: str): """Init. Args: camera_element: MJCF camera. config: Configuration of the camera sensor. name: Name of the image sensor. """ self.element = camera_element self._cfg = config self._name = name self._camera: Optional[mujoco.Camera] = None self._observables = { self.get_obs_key(ImageObservations.INTRINSICS): observable.Generic(self._camera_intrinsics), } if self._cfg.has_rgb: self._observables[self.get_obs_key( ImageObservations.RGB_IMAGE)] = observable.Generic(self._camera_rgb) if self._cfg.has_depth: self._observables[self.get_obs_key( ImageObservations.DEPTH_IMAGE)] = observable.Generic( self._camera_depth) if self._cfg.has_segmentation: self._observables[self.get_obs_key( ImageObservations.SEGMENTATION_IMAGE)] = observable.Generic( self._camera_segmentation) for obs in self._observables.values(): obs.enabled = True def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: pass def after_compile(self, mjcf_model: mjcf.RootElement, physics: mjcf.Physics) -> None: # We create the camera at the beginning of every episode. This is to improve # speed of rendering. Previously we used `physics.render` which creates a # new camera every single time you render. self._create_camera(physics) @property def observables(self) -> Dict[str, observable.Observable]: return self._observables @property def name(self) -> str: return self._name def get_obs_key(self, obs: ImageObservations) -> str: return obs.get_obs_key(self._name) def _camera_intrinsics(self, physics: mjcf.Physics) -> np.ndarray: del physics # unused. return pinhole_intrinsics( img_shape=(self._cfg.height, self._cfg.width), fovy=self._cfg.fovy) def _camera_rgb(self, physics: mjcf.Physics) -> np.ndarray: return np.atleast_3d(self._camera.render(depth=False, segmentation=False)) def _camera_depth(self, physics: mjcf.Physics) -> np.ndarray: return np.atleast_3d(self._camera.render(depth=True)) def _camera_segmentation(self, physics: mjcf.Physics) -> np.ndarray: return np.atleast_3d(self._camera.render(segmentation=True)) def _create_camera(self, physics: mjcf.Physics) -> None: self._camera = mujoco.Camera( physics=physics, height=self._cfg.height, width=self._cfg.width, camera_id=self.element.full_identifier) if self._cfg.render_shadows: self._camera.scene.flags[enums.mjtRndFlag.mjRND_SHADOW] = 1 else: self._camera.scene.flags[enums.mjtRndFlag.mjRND_SHADOW] = 0 def pinhole_intrinsics(img_shape: Tuple[int, int], fovy: float, negate_x_focal_len: bool = False) -> np.ndarray: """Builds camera intrinsic matrix for simple pinhole model. This function returns a camera intrinsic matrix for projecting 3D camera- frame points to the image plane. For background see: https://en.wikipedia.org/wiki/Pinhole_camera_model Args: img_shape: (2,) array containing image height and width. fovy: Field-of-view in Y, in degrees. negate_x_focal_len: If True, negate the X focal_len following mujoco's -z convention. This matrix will be identical to mujoco's camera intrinsics, but will be inconsistent with the +z-towards-scene achieved by CameraPoseSensor. Returns: (3, 4) array containing camera intrinsics """ height, width = img_shape # Calculate the focal length to get the requested image height given the # field of view. half_angle = fovy / 2 half_angle_rad = half_angle * np.pi / 180 focal_len = height / 2 / np.tan(half_angle_rad) # Note: By default these intrinsics do not include the negation of the x- # focal-length that mujoco uses in its camera matrix. To utilize this camera # matrix for projection and back-projection you must rotate the camera xmat # from mujoco by 180- degrees around the Y-axis. This is performed by # CameraPoseSensor. # # Background: Mujoco cameras view along the -z-axis, and require fovx and # depth-negation to do reprojection. This camera matrix follows the OpenCV # convention of viewing along +z, which does not require these hacks. x_focal_len = -focal_len if negate_x_focal_len else focal_len return np.array([[x_focal_len, 0, (width - 1) / 2, 0], [0, focal_len, (height - 1) / 2, 0], [0, 0, 1, 0]]) def get_sensor_bundle( camera_element: mjcf.Element, config: CameraConfig, name: str ) -> CameraSensorBundle: return (CameraPoseSensor(camera_element, name), CameraImageSensor(camera_element, config, name)) def build_camera_sensors( camera_configurations: Mapping[str, CameraConfig], mjcf_root: mjcf.element.RootElement, mjcf_full_identifiers: Optional[Mapping[str, str]] = None, ) -> Sequence[Union[CameraPoseSensor, CameraImageSensor]]: """Create the camera sensors for a list of cameras. Args: camera_configurations: Configurations of the cameras. Maps from the camera sensor name to the configuration of the camera. mjcf_root: MJCf root element in which the cameras are present. mjcf_full_identifiers: Mapping of the `camera_configurations` sensor names to the full identifiers of the cameras used in the MJCF model. If `None`, it is set as an identity mapping of `camera_configurations` names. Returns: A list of camera pose and camera image sensor for each camera. Raise: ValueError if the camera_configurations and mjcf_full_identifiers do not have the same set of keys. """ if mjcf_full_identifiers is None: mjcf_full_identifiers = { name: name for name in camera_configurations.keys()} if mjcf_full_identifiers.keys() != camera_configurations.keys(): raise ValueError( f'mjcf_full_identifiers: {mjcf_full_identifiers.keys()} and ' f'camera_configurations: {camera_configurations.keys()} ' 'do not contain the same set of keys.') camera_sensors = [] for name, identifier in mjcf_full_identifiers.items(): camera_prop = mjcf_root.find('camera', identifier) all_cameras = [ elmt.full_identifier for elmt in mjcf_root.find_all('camera')] if camera_prop is None: logging.warning('Could not find camera with identifier %s ' 'in the workspace. Available cameras: %s. ' 'There will be no camera sensor for %s.', identifier, all_cameras, identifier) else: config = camera_configurations[name] pose_sensor, image_sensor = get_sensor_bundle(camera_prop, config, name) camera_sensors.append(pose_sensor) camera_sensors.append(image_sensor) return camera_sensors
dm_robotics-main
py/moma/sensors/camera_sensor.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The observation enum used by all wrench sensors.""" import enum @enum.unique class Observations(enum.Enum): """Observations exposed by a wrench sensor.""" # The 3D force sensed by the sensor. FORCE = '{}_force' # The 3D torque sensed by the sensor. TORQUE = '{}_torque' def get_obs_key(self, name: str) -> str: """Returns the key to the observation in the observables dict.""" return self.value.format(name)
dm_robotics-main
py/moma/sensors/wrench_observations.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 robot_wrist_ft_sensor.""" from absl.testing import absltest from dm_robotics.moma.models.end_effectors.wrist_sensors import robotiq_fts300 from dm_robotics.moma.sensors import robot_wrist_ft_sensor from dm_robotics.moma.sensors import wrench_observations class RobotWristFTSensorTest(absltest.TestCase): def test_sensor_has_all_observables(self): wrist_ft_sensor = robotiq_fts300.RobotiqFTS300() sensor = robot_wrist_ft_sensor.RobotWristFTSensor( wrist_ft_sensor=wrist_ft_sensor, name='ft_sensor') for obs in wrench_observations.Observations: self.assertIn(sensor.get_obs_key(obs), sensor.observables) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/sensors/robot_wrist_ft_sensor_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sensor for exposing a pose.""" import enum from typing import Callable, Dict from dm_control import mjcf from dm_control.composer.observation import observable from dm_robotics.geometry import geometry from dm_robotics.moma import sensor as moma_sensor from dm_robotics.moma.utils import pose_utils import numpy as np @enum.unique class Observations(enum.Enum): """Observations exposed by this sensor.""" # The pose of the prop, given as [x, y, z, quat_w, quat_x, quat_y, quat_z]. POSE = '{}_pose' def get_obs_key(self, name: str) -> str: """Returns the key to the observation in the observables dict.""" return self.value.format(name) class GenericPoseSensor(moma_sensor.Sensor[Observations]): """Pose sensor to expose a geometry pose. This sensor is used to expose an arbitrary pose as an observable of the environment. An toy example use case would be: pos = [1.0, 2.0, 3.0] quat = [0.0, 1.0, 0.0, 0.1] pose_fn = lambda _: geometry.Pose(position=pos, quaternion=quat) sensor = generic_pose_sensor.GenericPoseSensor(pose_fn, name='generic') """ def __init__(self, pose_fn: Callable[[mjcf.Physics], geometry.Pose], name: str): """Initialization. Args: pose_fn: Callable that takes the physics and returns a geometry.Pose. The pose returned by the callable is the observation provided by this sensor. name: Name of the observed element. """ self._pose_fn = pose_fn self._name = name self._observables = { self.get_obs_key(Observations.POSE): observable.Generic(self._pose), } for obs in self._observables.values(): obs.enabled = True def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: pass @property def observables(self) -> Dict[str, observable.Observable]: return self._observables @property def name(self) -> str: return self._name def get_obs_key(self, obs: Observations) -> str: return obs.get_obs_key(self._name) def _pose(self, physics: mjcf.Physics) -> np.ndarray: pose = self._pose_fn(physics) pos, quat = pose.position, pose.quaternion return np.append(pos, pose_utils.positive_leading_quat(quat))
dm_robotics-main
py/moma/sensors/generic_pose_sensor.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sensor for measuring the wrist force and torque.""" from typing import Dict from dm_control import mjcf from dm_control.composer.observation import observable from dm_robotics.moma import sensor as moma_sensor from dm_robotics.moma.sensors import wrench_observations import numpy as np class RobotWristFTSensor(moma_sensor.Sensor[wrench_observations.Observations]): """Sensor providing force and torque observations of a mujoco ft sensor.""" def __init__(self, wrist_ft_sensor, name: str): """Constructor. Args: wrist_ft_sensor: Object that exposes: - A `force_sensor` property that returns a mujoco force sensor. - A `torque_sensor` property that returns a mujoco torque sensor. MuJoCo force and torque sensors report forces in the child->parent direction. However, the real F/T sensors may report forces with Z pointing outwards, that is, in the parent->child direction. These should be transformed to a canonical coordinate system either by a bespoke Sensor or a TimestepPreprocessor. name: The name of the sensor. """ self._wrist_ft_sensor = wrist_ft_sensor self._name = name self._observables = { self.get_obs_key(wrench_observations.Observations.FORCE): observable.Generic(self._wrist_force), self.get_obs_key(wrench_observations.Observations.TORQUE): observable.Generic(self._wrist_torque), } for obs in self._observables.values(): obs.enabled = True def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: pass @property def observables(self) -> Dict[str, observable.Observable]: return self._observables @property def name(self) -> str: return self._name def get_obs_key(self, obs: wrench_observations.Observations) -> str: return obs.get_obs_key(self._name) def _wrist_force(self, physics: mjcf.Physics) -> np.ndarray: force_sensor = self._wrist_ft_sensor.force_sensor return physics.bind(force_sensor).sensordata # pytype: disable=attribute-error def _wrist_torque(self, physics: mjcf.Physics) -> np.ndarray: torque_sensor = self._wrist_ft_sensor.torque_sensor return physics.bind(torque_sensor).sensordata # pytype: disable=attribute-error
dm_robotics-main
py/moma/sensors/robot_wrist_ft_sensor.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sensor for measuring pose and vel of TCP.""" from typing import Dict from dm_control import mjcf from dm_control.composer.observation import observable from dm_robotics.moma import sensor as moma_sensor from dm_robotics.moma.models.end_effectors.robot_hands import robot_hand from dm_robotics.moma.sensors import site_sensor import numpy as np # Observation enum listing all the observations exposed by the sensor. Observations = site_sensor.Observations class RobotTCPSensor(moma_sensor.Sensor[Observations]): """Robot tcp sensor providing measurements of the Tool Center Point.""" def __init__(self, gripper: robot_hand.AnyRobotHand, name: str): self._name = f'{name}_tcp' self._gripper_site_sensor = site_sensor.SiteSensor( site=gripper.tool_center_point, name=self._name) self._observables = self._gripper_site_sensor.observables def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: self._gripper_site_sensor.initialize_episode(physics, random_state) @property def observables(self) -> Dict[str, observable.Observable]: return self._observables @property def name(self) -> str: return self._name def get_obs_key(self, obs: Observations) -> str: return obs.get_obs_key(self._name)
dm_robotics-main
py/moma/sensors/robot_tcp_sensor.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Enum to help key into a timestep's observations dictionary for joint obs.""" import enum @enum.unique class Observations(enum.Enum): """Joint state observations exposed by a MoMa sensor.""" # The joint angles, in radians. JOINT_POS = '{}_joint_pos' # The joint velocities, in rad/s. JOINT_VEL = '{}_joint_vel' # The joint torques of the arm. JOINT_TORQUES = '{}_joint_torques' def get_obs_key(self, name: str) -> str: """Returns the key to the observation in the observables dict.""" return self.value.format(name)
dm_robotics-main
py/moma/sensors/joint_observations.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 robot_tcp_sensor.""" from absl.testing import absltest from dm_robotics.moma.models.end_effectors.robot_hands import robotiq_2f85 from dm_robotics.moma.sensors import robot_tcp_sensor class RobotArmSensorTest(absltest.TestCase): def setUp(self): super().setUp() self._gripper = robotiq_2f85.Robotiq2F85(name='gripper') self._name = 'gripper' def test_sensor_has_all_observables(self): sensor = robot_tcp_sensor.RobotTCPSensor(self._gripper, self._name) for obs in robot_tcp_sensor.Observations: self.assertIn(sensor.get_obs_key(obs), sensor.observables) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/sensors/robot_tcp_sensor_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sensor to measure the previous command received by an effector.""" import enum from typing import Dict, Tuple, Optional from dm_control import mjcf from dm_control.composer.observation import observable from dm_env import specs from dm_robotics.moma import effector as moma_effector from dm_robotics.moma import sensor import numpy as np class SpyEffector(moma_effector.Effector): """Effector used to cache the last command used by the delegate effector.""" def __init__(self, effector: moma_effector.Effector): self._previous_action: Optional[np.ndarray] = None self._delegate_effector = effector def after_compile(self, mjcf_model: mjcf.RootElement, physics: mjcf.Physics) -> None: self._delegate_effector.after_compile(mjcf_model, physics) def initialize_episode(self, physics, random_state) -> None: self._previous_action = self.action_spec(physics).minimum self._delegate_effector.initialize_episode(physics, random_state) def action_spec(self, physics) -> specs.BoundedArray: return self._delegate_effector.action_spec(physics) def set_control(self, physics, command: np.ndarray) -> None: self._previous_action = command[:] self._delegate_effector.set_control(physics, command) @property def prefix(self) -> str: return self._delegate_effector.prefix def close(self): self._delegate_effector.close() @property def previous_action(self) -> Optional[np.ndarray]: return self._previous_action @enum.unique class Observations(enum.Enum): """Observations exposed by this sensor.""" # The previous command that was used by the effector. PREVIOUS_ACTION = '{}_previous_action' def get_obs_key(self, name: str) -> str: """Returns the key to the observation in the observables dict.""" return self.value.format(name) class ActionSensor(sensor.Sensor[Observations]): """Tracks the previous command that was received by an effector. In most cases, we chain several effectors when controlling our robots. For example, we expose a cartesian effector to the agent. This cartesian command is changed to a joint command and is passed to a joint effector that actuates the robot. This sensor is used to capture the command that is received by the joint effector. """ def __init__(self, effector: SpyEffector, name: str): """Constructor. The ActionSensor should be built using the create_sensed_effector function below. Args: effector: Effector that exposes a `previous_action` property that is read by the sensor. name: Name of the sensor. """ self._effector = effector self._name = name self._observables = { self.get_obs_key(Observations.PREVIOUS_ACTION): observable.Generic( self._previous_action), } for obs in self._observables.values(): obs.enabled = True def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: pass @property def observables(self) -> Dict[str, observable.Observable]: return self._observables @property def name(self) -> str: return self._name def get_obs_key(self, obs: Observations) -> str: return obs.get_obs_key(self._name) def _previous_action(self, physics: mjcf.Physics): if self._effector.previous_action is None: self._effector.initialize_episode(physics, None) return self._effector.previous_action def create_sensed_effector( effector: moma_effector.Effector ) -> Tuple[moma_effector.Effector, ActionSensor]: """Returns the effector and sensor to measure the last command received.""" new_effector = SpyEffector(effector) action_sensor = ActionSensor(new_effector, name=effector.prefix) return new_effector, action_sensor
dm_robotics-main
py/moma/sensors/action_sensor.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 utility functions.""" from typing import Tuple from dm_control.mujoco.wrapper import mjbindings from dm_control.mujoco.wrapper.mjbindings import enums from dm_robotics.transformations import transformations as tr import numpy as np mjlib = mjbindings.mjlib def actuator_spec(physics, actuators) -> Tuple[np.ndarray, np.ndarray]: """Returns the spec of the actuators.""" num_actions = len(actuators) control_range = physics.bind(actuators).ctrlrange is_limited = physics.bind(actuators).ctrllimited.astype(bool) minima = np.full(num_actions, fill_value=-np.inf, dtype=np.float32) maxima = np.full(num_actions, fill_value=np.inf, dtype=np.float32) minima[is_limited], maxima[is_limited] = control_range[is_limited].T return minima, maxima def get_site_pose(physics, site_entity): """Returns world pose of prop as homogeneous transform. Args: physics: A mujoco.Physics site_entity: The entity of a prop site (with prefix) Returns: A 4x4 numpy array containing the world site pose """ binding = physics.bind(site_entity) xpos = binding.xpos.reshape(3, 1) xmat = binding.xmat.reshape(3, 3) transform_world_site = np.vstack( [np.hstack([xmat, xpos]), np.array([0, 0, 0, 1])]) return transform_world_site def get_site_relative_pose(physics, site_a, site_b): """Computes pose of site_a in site_b frame. Args: physics: The physics object. site_a: The site whose pose to calculate. site_b: The site whose frame of reference to use. Returns: transform_siteB_siteA: A 4x4 transform representing the pose of siteA in the siteB frame """ transform_world_a = get_site_pose(physics, site_a) transform_world_b = get_site_pose(physics, site_b) transform_b_world = tr.hmat_inv(transform_world_b) return transform_b_world.dot(transform_world_a) def get_site_vel(physics, site_entity, world_frame=False, reorder=True): """Returns the 6-dim [rotational, translational] velocity of the named site. This 6-vector represents the instantaneous velocity of coordinate system attached to the site. If flg_local==0, this vector is rotated to world coordinates. Args: physics: A mujoco.Physics site_entity: The entity of a prop site (with prefix) world_frame: If True return vel in world frame, else local to site. reorder: (bool) If True, swaps the order of the return velocity from [rotational, translational] to [translational, rotational] """ flg_local = 0 if world_frame else 1 idx = physics.model.name2id(site_entity.full_identifier, enums.mjtObj.mjOBJ_SITE) site_vel = np.zeros(6) mjlib.mj_objectVelocity(physics.model.ptr, physics.data.ptr, enums.mjtObj.mjOBJ_SITE, idx, site_vel, flg_local) if reorder: return np.hstack([site_vel[3:], site_vel[0:3]]) else: return site_vel def get_site_relative_vel(physics, site_a, site_b, frame='world'): """Returns the relative velocity of the named sites. This 6-vector represents the instantaneous velocity of coordinate system attached to the site. Args: physics: The physics object. site_a: The site whose pose to calculate. site_b: The site whose frame of reference to use. frame: (str) A string indicating the frame in which the relative vel is reported. Options: "world", "a", "b" (Default: "world") Raises: ValueError: if invalid frame argument """ v_world_a = get_site_vel(physics, site_a, world_frame=True, reorder=True) v_world_b = get_site_vel(physics, site_b, world_frame=True, reorder=True) vrel_world = v_world_a - v_world_b if frame == 'world': return vrel_world elif frame == 'a': rot_world_a = get_site_pose(physics, site_a) rot_world_a[0:3, 3] = 0 rot_a_world = np.linalg.inv(rot_world_a) vrel_a = tr.velocity_transform(rot_a_world, vrel_world) return vrel_a elif frame == 'b': rot_world_b = get_site_pose(physics, site_b) rot_world_b[0:3, 3] = 0 rot_b_world = np.linalg.inv(rot_world_b) vrel_b = tr.velocity_transform(rot_b_world, vrel_world) return vrel_b else: raise ValueError('Invalid frame spec \'{}\''.format(frame))
dm_robotics-main
py/moma/sensors/mujoco_utils.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 robot_arm_sensor.py.""" from absl.testing import absltest from absl.testing import parameterized from dm_control import mjcf from dm_robotics.moma.models.robots.robot_arms import sawyer from dm_robotics.moma.sensors import joint_observations from dm_robotics.moma.sensors import robot_arm_sensor import numpy as np # Joint configuration that places each joint in the center of its range _JOINT_QPOS = [0., 0., 0., -1.5, 0., 1.9, 0.] # Joint velocities that are safe. _JOINT_QVEL = [0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01] # Absolute tolerance parameter. _A_TOL = 5e-03 # Relative tolerance parameter. _R_TOL = 0.01 class RobotArmSensorTest(parameterized.TestCase): def setUp(self): super().setUp() self._arm = sawyer.Sawyer(with_pedestal=False) self._name = 'sawyer' self._physics = mjcf.Physics.from_mjcf_model(self._arm.mjcf_model) def _verify_observable(self, sensor, obs_enum, expected_value): observable = sensor.observables[sensor.get_obs_key(obs_enum)] np.testing.assert_allclose(observable(self._physics), expected_value, rtol=_R_TOL, atol=_A_TOL) @parameterized.named_parameters(('_with_torques', True), ('_without_torques', False),) def test_sensor_has_working_observables(self, torques): sensor = robot_arm_sensor.RobotArmSensor(arm=self._arm, name=self._name, have_torque_sensors=torques) self.assertIn(sensor.get_obs_key(joint_observations.Observations.JOINT_POS), sensor.observables) self.assertIn(sensor.get_obs_key(joint_observations.Observations.JOINT_VEL), sensor.observables) # Check that the observations are giving the correct values. expected_joint_angles = _JOINT_QPOS self._physics.bind(self._arm.joints).qpos = expected_joint_angles self._verify_observable(sensor, joint_observations.Observations.JOINT_POS, expected_joint_angles) expected_joint_vel = _JOINT_QVEL self._physics.bind(self._arm.joints).qvel = expected_joint_vel self._verify_observable(sensor, joint_observations.Observations.JOINT_VEL, expected_joint_vel) if torques: self.assertIn( sensor.get_obs_key(joint_observations.Observations.JOINT_TORQUES), sensor.observables) else: self.assertNotIn( sensor.get_obs_key(joint_observations.Observations.JOINT_TORQUES), sensor.observables) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/sensors/robot_arm_sensor_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 robotiq_gripper_sensor.""" from absl.testing import absltest from dm_robotics.moma.models.end_effectors.robot_hands import robotiq_2f85 from dm_robotics.moma.sensors import robotiq_gripper_observations from dm_robotics.moma.sensors import robotiq_gripper_sensor # Absolute tolerance parameter. _A_TOL = 5e-03 # Relative tolerance parameter. _R_TOL = 0.01 class RobotiqGripperSensorTest(absltest.TestCase): def test_sensor_has_all_observables(self): name = 'gripper' gripper = robotiq_2f85.Robotiq2F85(name=name) sensor = robotiq_gripper_sensor.RobotiqGripperSensor( gripper=gripper, name=name) sensor.initialize_for_task(0.1, 0.001, 100) expected_observable_names = set( sensor.get_obs_key(obs) for obs in robotiq_gripper_observations.Observations) actual_observable_names = set(sensor.observables.keys()) self.assertSameElements(expected_observable_names, actual_observable_names) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/sensors/robotiq_gripper_sensor_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Integration test for the gripper, its sensor and effector.""" from absl.testing import absltest from dm_control import composer from dm_robotics import agentflow as af from dm_robotics.geometry import pose_distribution from dm_robotics.moma import action_spaces from dm_robotics.moma import base_task from dm_robotics.moma import entity_initializer from dm_robotics.moma import robot from dm_robotics.moma import scene_initializer from dm_robotics.moma import subtask_env_builder from dm_robotics.moma.effectors import arm_effector from dm_robotics.moma.effectors import default_gripper_effector from dm_robotics.moma.models.arenas import empty from dm_robotics.moma.models.end_effectors.robot_hands import robotiq_2f85 from dm_robotics.moma.models.robots.robot_arms import sawyer from dm_robotics.moma.models.robots.robot_arms import sawyer_constants from dm_robotics.moma.sensors import robotiq_gripper_sensor import numpy as np class GripperSensorIntegrationTest(absltest.TestCase): def setUp(self): super().setUp() self._arena = _build_arena(name='arena') self._robot = _build_sawyer_with_gripper(robot_name='robot0') self._arena.attach(self._robot.arm) robot_pose = pose_distribution.ConstantPoseDistribution( np.array([-0.75, 0., 0., 0., 0., 0.])) robot_pose_initializer = scene_initializer.EntityPoseInitializer( entity=self._robot.arm_frame, pose_sampler=robot_pose.sample_pose) gripper_pose = pose_distribution.ConstantPoseDistribution( np.array([-0.1, 0., 0.4, -np.pi, 0., 0.])) gripper_initializer = entity_initializer.PoseInitializer( self._robot.position_gripper, gripper_pose.sample_pose) static_initializer = robot_pose_initializer dynamic_initializer = gripper_initializer self._task = base_task.BaseTask( task_name='handshake', arena=self._arena, robots=[self._robot], props=[], extra_sensors=[], extra_effectors=[], scene_initializer=static_initializer, episode_initializer=dynamic_initializer, control_timestep=0.1) def test_actuator_and_sensor(self): env_builder = subtask_env_builder.SubtaskEnvBuilder() env_builder.set_task(self._task) task_env = env_builder.build_base_env() parent_action_spec = self._task.effectors_action_spec(task_env.physics) gripper_action_space = action_spaces.GripperActionSpace( af.prefix_slicer( parent_action_spec, self._robot.gripper_effector.prefix, default_value=0.0)) env_builder.set_action_space(gripper_action_space) with env_builder.build() as env: timestep = env.reset() # Assert the shapes of the observations: self.assertEqual(timestep.observation['robot0_gripper_pos'].shape, (1,)) self.assertEqual(timestep.observation['robot0_gripper_vel'].shape, (1,)) self.assertEqual(timestep.observation['robot0_gripper_grasp'].shape, (1,)) for i in range(5000): old_pos = timestep.observation['robot0_gripper_pos'] # We send the max command. timestep = env.step(np.asarray([255.0])) cur_pos = timestep.observation['robot0_gripper_pos'] vel = timestep.observation['robot0_gripper_vel'] self.assertEqual(vel, cur_pos - old_pos) # We can never reach to position 255 because we are using a p controller # and there will therefore always be a steady state error. More details # in the actuation of the gripper. if cur_pos[0] >= 254: break self.assertLess(i, 4999) # 5000 steps should be enough to get to 255. def _build_arena(name: str) -> composer.Arena: """Builds an arena Entity.""" arena = empty.Arena(name) arena.ground.size = (2.0, 2.0, 2.0) arena.mjcf_model.option.timestep = 0.001 arena.mjcf_model.option.gravity = (0., 0., -1.0) arena.mjcf_model.size.nconmax = 1000 arena.mjcf_model.size.njmax = 2000 arena.mjcf_model.visual.__getattr__('global').offheight = 480 arena.mjcf_model.visual.__getattr__('global').offwidth = 640 arena.mjcf_model.visual.map.znear = 0.0005 return arena def _build_sawyer_with_gripper(robot_name: str) -> robot.Robot: """Returns a Sawyer robot.""" arm = sawyer.Sawyer( name=robot_name, actuation=sawyer_constants.Actuation.INTEGRATED_VELOCITY) gripper = robotiq_2f85.Robotiq2F85() arm.attach(gripper) robot_sensors = [ robotiq_gripper_sensor.RobotiqGripperSensor( gripper=gripper, name=f'{robot_name}_gripper') ] robot_effector = arm_effector.ArmEffector( arm=arm, action_range_override=None, robot_name=robot_name) gripper_effector = default_gripper_effector.DefaultGripperEffector( gripper, robot_name) return robot.StandardRobot( arm=arm, arm_base_site_name='pedestal_attachment', gripper=gripper, robot_sensors=robot_sensors, arm_effector=robot_effector, gripper_effector=gripper_effector, name=robot_name) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/sensors/robotiq_gripper_sensor_integration_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sensor for a sim Robotiq gripper.""" from typing import Dict, Optional from dm_control import mjcf from dm_control.composer.observation import observable from dm_robotics.moma.sensors import robotiq_gripper_observations import numpy as np import typing_extensions @typing_extensions.runtime class Gripper(typing_extensions.Protocol): def convert_position(self, position, **unused_kwargs): pass def grasp_sensor_callable(self, physics) -> int: pass class RobotiqGripperSensor(robotiq_gripper_observations.RobotiqGripperSensor): """Robotiq gripper sensor for pos, vel, and grasp related observations.""" def __init__(self, gripper: Gripper, name: str): self._gripper = gripper self._name = name self._observables = None def initialize_for_task(self, control_timestep_seconds: float, physics_timestep_seconds: float, physics_steps_per_control_step: int): def velocity_from_positions(cur_prev_positions): return cur_prev_positions[1] - cur_prev_positions[0] observations = robotiq_gripper_observations.Observations self._observables = { self.get_obs_key(observations.POS): observable.Generic( self._pos, # Convert the raw joint pos to a sensor output. corruptor=self._gripper.convert_position), self.get_obs_key(observations.VEL): observable.Generic( self._pos, buffer_size=2, update_interval=physics_steps_per_control_step, corruptor=self._gripper.convert_position, aggregator=velocity_from_positions), self.get_obs_key(observations.GRASP): observable.Generic(self._grasp), self.get_obs_key(observations.HEALTH_STATUS): observable.Generic(self.health_status), } for obs in self._observables.values(): obs.enabled = True def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: pass @property def observables(self) -> Dict[str, observable.Observable]: return self._observables @property def name(self) -> str: return self._name def get_obs_key(self, obs: robotiq_gripper_observations.Observations) -> str: return obs.get_obs_key(self._name) def _pos(self, physics: mjcf.Physics) -> np.ndarray: return physics.bind(self._gripper.joint_sensor).sensordata # pytype: disable=attribute-error def _grasp(self, physics: mjcf.Physics) -> np.ndarray: return np.array([self._gripper.grasp_sensor_callable(physics)], dtype=np.uint8) def health_status(self, physics: Optional[mjcf.Physics] = None) -> np.ndarray: del physics # Always report a "ready" status for the sim grippers. return np.array([robotiq_gripper_observations.HealthStatus.READY.value], dtype=np.uint8)
dm_robotics-main
py/moma/sensors/robotiq_gripper_sensor.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sensor to expose some externally defined value.""" from typing import Dict from dm_control import mjcf from dm_control.composer.observation import observable from dm_robotics.moma import sensor as moma_sensor import numpy as np class ExternalValueSensor(moma_sensor.Sensor): """Sensor to expose some externally defined value. This can be useful when we need to expose to the agent some value that is determined by a non-physical process (eg: the progress of a curriculum). """ def __init__(self, name: str, initial_value: np.ndarray): self._name = name self._value = initial_value self._observables = { self._name: observable.Generic(lambda _: self._value), } for obs in self._observables.values(): obs.enabled = True def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: pass @property def observables(self) -> Dict[str, observable.Observable]: return self._observables @property def name(self) -> str: return self._name def get_obs_key(self, obs) -> str: del obs return self._name def set_value(self, value: np.ndarray) -> None: if value.shape != self._value.shape: raise ValueError('Incompatible value shape') self._value = value
dm_robotics-main
py/moma/sensors/external_value_sensor.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 generic_pose_sensor.""" from absl.testing import absltest from dm_robotics.geometry import geometry from dm_robotics.moma.sensors import generic_pose_sensor import numpy as np class GenericPoseSensorTest(absltest.TestCase): def test_sensor(self): pos = [1.0, 2.0, 3.0] quat = [0.0, 1.0, 0.0, 0.1] pose_fn = lambda _: geometry.Pose(position=pos, quaternion=quat) sensor = generic_pose_sensor.GenericPoseSensor(pose_fn, name='generic') key = 'generic_pose' # Check that the observables is added. self.assertIn(key, sensor.observables) # Check that the pose is returned. sensor_pose = sensor.observables[key](None) np.testing.assert_equal(sensor_pose, np.concatenate((pos, quat))) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/sensors/generic_pose_sensor_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for prop_pose_sensor.""" from absl.testing import absltest from absl.testing import parameterized from dm_control import mjcf from dm_robotics.moma import prop as moma_prop from dm_robotics.moma.models.arenas import empty from dm_robotics.moma.sensors import prop_pose_sensor import numpy as np # Absolute tolerance parameter. _A_TOL = 5e-03 # Relative tolerance parameter. _R_TOL = 0.01 class PropPoseSensorTest(parameterized.TestCase): def test_sensor_returns_pose(self): arena = empty.Arena() name = 'prop' prop = moma_prop.Block() frame = arena.add_free_entity(prop) prop.set_freejoint(frame.freejoint) physics = mjcf.Physics.from_mjcf_model(arena.mjcf_model) sensor = prop_pose_sensor.PropPoseSensor(prop=prop, name=name) self.assertIn( sensor.get_obs_key(prop_pose_sensor.Observations.POSE), sensor.observables) expected_pose = [1., 2., 3., 1., 0., 0., 0.] prop.set_pose(physics, expected_pose[:3], expected_pose[3:]) physics.step() observable = sensor.observables[sensor.get_obs_key( prop_pose_sensor.Observations.POSE)] np.testing.assert_allclose( observable(physics), expected_pose, rtol=_R_TOL, atol=_A_TOL) class SensorCreationTest(absltest.TestCase): def test_sensor_creation(self): mjcf_root = mjcf.element.RootElement(model='arena') names = ['foo', 'baz', 'wuz'] moma_props = [] for name in names: mjcf_root.worldbody.add('body', name=name) moma_props.append( moma_prop.Prop(name=name, mjcf_root=mjcf_root, prop_root=name)) sensors = prop_pose_sensor.build_prop_pose_sensors(moma_props) self.assertLen(sensors, 3) for sensor in sensors: self.assertIsInstance(sensor, prop_pose_sensor.PropPoseSensor) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/sensors/prop_pose_sensor_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Simple run loop for an agent and environment.""" import numpy as np def run(environment, agent, observers, max_steps): """Runs the agent 'in' the environment. The loop is: 1. The `environment` is reset, producing a state. 2. The `agent` is given that state and produces an action. 3. That action is given to the environment. 4. The `environment` produces a new state. 5. GOTO 2 At most `max_steps` are demanded from the agent. The `environment` cam produce three types of step: * FIRST: The first step in an episode. The next step will be MID or LAST. * MID: A step that is neither the first nor last. * LAST: The last step in this episode. The next step will be FIRST. Depending on the type of step emitted by the environment, the `observers` have different methods called: * FIRST: `observer.begin_episode(0)` * MID: `observer.step(0, env_timestep, agent_action)` * LAST: `observer.end_episode(0, 0, env_timestep)` The `agent_action` passed to `observer.step` is the action the agent emitted given `env_timestep`, at the time the observer is called, the action has not yet been given to the environment. When a LAST timestep is received, the agent is given that timestep, but the action it emits is discarded. Args: environment: The environment to run the agent "in". agent: The agent that produced actions. observers: A sequence of observers, see the docstring. max_steps: The maximum number of time to step the agent. """ step_count = 0 while step_count < max_steps: # Start a new episode: timestep = _start_new_episode(environment) _observe_begin(observers) # Step until the end of episode (or max_steps hit): while not timestep.last() and step_count < max_steps: # Get an action from the agent: action = agent.step(timestep) step_count += 1 _ensure_no_nans(action) _observe_step(observers, timestep, action) # Get a new state (timestep) from the environment: timestep = environment.step(action) timestep = _fix_timestep(timestep, environment) # Tell the observers the episode has ended. if step_count < max_steps: agent.step(timestep) step_count += 1 _observe_end(observers, timestep) def _start_new_episode(env): timestep = _fix_timestep(env.reset(), env) if not timestep.first(): raise ValueError('Expected first timestep, but received {}.'.format( str(timestep.step_type))) return timestep def _fix_timestep(timestep, env): """Ensures the output timestep has a reward and discount.""" if timestep.reward is None: reward_spec = env.reward_spec() if reward_spec.shape: reward = np.zeros(shape=reward_spec.shape, dtype=reward_spec.dtype) else: reward = reward_spec.dtype.type(0.0) timestep = timestep._replace(reward=reward) if timestep.discount is None: timestep = timestep._replace(discount=env.discount_spec().dtype.type(1.0)) return timestep def _observe_begin(observers): for obs in observers: obs.begin_episode(0) def _observe_step(observers, timestep, action): for obs in observers: obs.step(0, timestep, action) def _observe_end(observers, timestep): for obs in observers: obs.end_episode(0, 0, timestep) def _ensure_no_nans(action): if any(np.isnan(action)): raise ValueError('NaN in agent actions')
dm_robotics-main
py/moma/tasks/run_loop.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 run_loop.""" import copy import itertools from absl.testing import absltest from absl.testing import parameterized import dm_env from dm_env import specs from dm_robotics.moma.tasks import run_loop import numpy as np @parameterized.parameters([True, False]) class RunLoopTest(parameterized.TestCase): def test_actions_given_to_environment(self, use_scalar_rewards: bool): env = SpyEnv(use_scalar_rewards) action_1 = np.asarray([0.1]) action_2 = np.asarray([0.2]) agent = CycleStepsAgent([action_1, action_2]) run_loop.run(env, agent, [], max_steps=5) # env method, agent timestep, agent action produced # env.reset, FIRST, 0.1 # env.step, MID, 0.2 # env.step, MID, 0.1 # env.step, LAST, 0.2 (Discarded) # env.step, FIRST, 0.1 expected_actions_sent_to_environment = [ SpyEnv.RESET_CALLED, # reset comes without an action. action_1, # agent step 1 action_2, # agent step 2 action_1, # agent step 3 SpyEnv.RESET_CALLED, # agent step 4, action discarded action_1, # agent step 5, the last step the agent is asked for. ] self.assertEqual(env.actions_received, expected_actions_sent_to_environment) def test_timesteps_given_to_agent(self, use_scalar_rewards: bool): env = SpyEnv(use_scalar_rewards) agent = CycleStepsAgent([(np.asarray([0.1]))]) run_loop.run(env, agent, [], max_steps=5) expected_timestep_types = [ dm_env.StepType.FIRST, dm_env.StepType.MID, dm_env.StepType.MID, dm_env.StepType.LAST, dm_env.StepType.FIRST, ] actual_timestep_types = [ timestep.step_type for timestep in agent.timesteps_received ] self.assertEqual(actual_timestep_types, expected_timestep_types) def test_observer_calls(self, use_scalar_rewards: bool): env = SpyEnv(use_scalar_rewards) action_1 = np.asarray([0.1]) action_2 = np.asarray([0.2]) agent = CycleStepsAgent([action_1, action_2]) observer = SpyObserver() run_loop.run(env, agent, [observer], max_steps=5) expected_observations = [ (SpyObserver.BEGIN_EPISODE, None, None), (SpyObserver.STEP, dm_env.StepType.FIRST, action_1), (SpyObserver.STEP, dm_env.StepType.MID, action_2), (SpyObserver.STEP, dm_env.StepType.MID, action_1), (SpyObserver.END_EPISODE, dm_env.StepType.LAST, None), # a2 (SpyObserver.BEGIN_EPISODE, None, None), # no agent interaction (SpyObserver.STEP, dm_env.StepType.FIRST, action_1), ] # "act" = actual, "ex" = expected. # unzip the call, timestep and actions from the SpyObserver. act_calls, act_timesteps, act_actions = zip(*observer.notifications) ex_calls, ex_step_types, ex_actions = zip(*expected_observations) act_step_types = [ts.step_type if ts else None for ts in act_timesteps] self.assertEqual(act_calls, ex_calls) self.assertEqual(act_step_types, list(ex_step_types)) self.assertEqual(act_actions, ex_actions) class SpyObserver: BEGIN_EPISODE = 'begin_ep' STEP = 'step' END_EPISODE = 'end_ep' def __init__(self): self.notifications = [] def begin_episode(self, agent_id): del agent_id self.notifications.append((SpyObserver.BEGIN_EPISODE, None, None)) def step(self, agent_id, timestep, action): del agent_id self.notifications.append((SpyObserver.STEP, timestep, action)) def end_episode(self, agent_id, term_reason, timestep): del agent_id, term_reason self.notifications.append((SpyObserver.END_EPISODE, timestep, None)) class SpyEnv(dm_env.Environment): RESET_CALLED = 'reset' def __init__(self, use_scalar_rewards: bool): self._step_types = self._initialize_step_type_sequence() self.actions_received = [] self.steps_emitted = [] self._use_scalar_rewards = use_scalar_rewards def _initialize_step_type_sequence(self): return iter( itertools.cycle([ dm_env.StepType.FIRST, dm_env.StepType.MID, dm_env.StepType.MID, dm_env.StepType.LAST, ])) def reset(self) -> dm_env.TimeStep: self._step_types = self._initialize_step_type_sequence() step = self._create_step(next(self._step_types)) self.actions_received.append(SpyEnv.RESET_CALLED) self.steps_emitted.append(step) return copy.deepcopy(step) def _create_step(self, step_type): return dm_env.TimeStep( step_type=step_type, reward=0.0 if self._use_scalar_rewards else np.zeros(3,), discount=0.9, observation={'state': np.random.random(size=(1,))}) def step(self, action) -> dm_env.TimeStep: step = self._create_step(next(self._step_types)) self.actions_received.append(np.copy(action)) self.steps_emitted.append(step) return copy.deepcopy(step) def reward_spec(self): shape = () if self._use_scalar_rewards else (3,) return specs.Array(shape=shape, dtype=float, name='reward') def discount_spec(self): return specs.BoundedArray( shape=(), dtype=float, minimum=0., maximum=1., name='discount') def observation_spec(self): return { 'state': specs.BoundedArray( shape=(1,), dtype=np.float32, minimum=[0], maximum=[1]) } def action_spec(self): return specs.BoundedArray( shape=(1,), dtype=np.float32, minimum=[0], maximum=[1]) def close(self): pass class CycleStepsAgent: def __init__(self, steps): self._steps = itertools.cycle(steps) self.timesteps_received = [] def step(self, timestep) -> np.ndarray: self.timesteps_received.append(timestep) return next(self._steps) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/tasks/run_loop_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sample task runner that creates a task environments and runs it.""" from absl import app from dm_env import specs from dm_robotics.moma.tasks import run_loop from dm_robotics.moma.tasks.example_task import example_task from dm_robotics.moma.utils import mujoco_rendering import numpy as np def main(argv): del argv # We need to ensure that we close the environment with example_task.build_task_environment() as env: agent = RandomAgent(env.action_spec()) rendering_obs = mujoco_rendering.Observer.build(env) rendering_obs.camera_config = { 'distance': 2.5, 'lookat': [0., 0., 0.], 'elevation': -45.0, 'azimuth': 90.0, } run_loop.run(env, agent, observers=[rendering_obs], max_steps=100) class RandomAgent: """An agent that emits uniform random actions.""" def __init__(self, action_spec: specs.BoundedArray): self._spec = action_spec self._shape = action_spec.shape self._range = action_spec.maximum - action_spec.minimum def step(self, unused_timestep): action = (np.random.rand(*self._shape) - 0.5) * self._range np.clip(action, self._spec.minimum, self._spec.maximum, action) return action.astype(self._spec.dtype) if __name__ == '__main__': app.run(main)
dm_robotics-main
py/moma/tasks/example_task/run.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Task builder for the dm_env interface to the example task. In this example task, the agent is controlling 2 robots and is rewarded for bringing the tcp of both robots close to one another. """ import dm_env from dm_robotics import agentflow as af from dm_robotics.agentflow.preprocessors import observation_transforms from dm_robotics.agentflow.preprocessors import rewards from dm_robotics.agentflow.subtasks import subtask_termination from dm_robotics.moma import action_spaces from dm_robotics.moma import subtask_env_builder from dm_robotics.moma.tasks.example_task import task_builder def build_task_environment() -> dm_env.Environment: """Returns the environment.""" # We first build the base task that contains the simulation model as well # as all the initialization logic, the sensors and the effectors. task, components = task_builder.build_task() del components env_builder = subtask_env_builder.SubtaskEnvBuilder() env_builder.set_task(task) # Build a composer environment. task_env = env_builder.build_base_env() # Define the action space. This defines what action spec is exposed to the # agent along with how to project the action received by the agent to the one # exposed by the composer environment. Here the action space is a collection # of actions spaces, one for the arm and one for the gripper. parent_action_spec = task.effectors_action_spec(physics=task_env.physics) robot_action_spaces = [] for rbt in task.robots: # Joint space control of each individual robot. joint_action_space = action_spaces.ArmJointActionSpace( af.prefix_slicer(parent_action_spec, rbt.arm_effector.prefix)) gripper_action_space = action_spaces.GripperActionSpace( af.prefix_slicer(parent_action_spec, rbt.gripper_effector.prefix)) # Gripper isn't controlled by the agent for this task. gripper_action_space = af.FixedActionSpace( gripper_action_space, gripper_action_space.spec().minimum) robot_action_spaces.extend([joint_action_space, gripper_action_space]) env_builder.set_action_space( af.CompositeActionSpace(robot_action_spaces)) # We add a preprocessor that casts all the observations to float32 env_builder.add_preprocessor(observation_transforms.CastPreprocessor()) env_builder.add_preprocessor( rewards.L2Reward(obs0='robot0_tcp_pos', obs1='robot1_tcp_pos')) # End episodes after 100 steps. env_builder.add_preprocessor(subtask_termination.MaxStepsTermination(100)) return env_builder.build()
dm_robotics-main
py/moma/tasks/example_task/example_task.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 example_task.example_task.""" from absl.testing import absltest from dm_robotics.moma.tasks.example_task import example_task import numpy as np class ExampleTaskTest(absltest.TestCase): def test_environment_stepping(self): np.random.seed(42) with example_task.build_task_environment() as env: action = np.zeros(env.action_spec().shape) env.step(action) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/tasks/example_task/example_task_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A module for constructing an example handshake task and its dependencies.""" from typing import Sequence, Text, Tuple import attr from dm_control import composer from dm_robotics.geometry import pose_distribution from dm_robotics.moma import base_task from dm_robotics.moma import entity_composer from dm_robotics.moma import entity_initializer from dm_robotics.moma import prop from dm_robotics.moma import robot from dm_robotics.moma import scene_initializer from dm_robotics.moma.effectors import arm_effector as arm_effector_module from dm_robotics.moma.effectors import default_gripper_effector from dm_robotics.moma.models.arenas import empty from dm_robotics.moma.models.end_effectors.robot_hands import robotiq_2f85 from dm_robotics.moma.models.end_effectors.wrist_sensors import robotiq_fts300 from dm_robotics.moma.models.robots.robot_arms import sawyer from dm_robotics.moma.models.robots.robot_arms import sawyer_constants from dm_robotics.moma.sensors import robot_arm_sensor from dm_robotics.moma.sensors import robot_tcp_sensor import numpy as np @attr.s(auto_attribs=True) class MutableTaskComponents: """Components that are returned with the task for easier access.""" robot0_pose_initializer: scene_initializer.EntityPoseInitializer = None robot1_pose_initializer: scene_initializer.EntityPoseInitializer = None gripper0_initializer: entity_initializer.PoseInitializer = None gripper1_initializer: entity_initializer.PoseInitializer = None prop_initializer: entity_initializer.PoseInitializer = None @attr.s(frozen=True) class TaskComponents(MutableTaskComponents): pass class ExampleTaskComposer(entity_composer.TaskEntitiesComposer): """Task composer that performs entity composition on the scene.""" def __init__(self, task_robots: Sequence[robot.Robot], task_props: Sequence[prop.Prop]): self._robots = task_robots self._props = task_props def compose_entities(self, arena: composer.Arena) -> None: """Adds all of the necessary objects to the arena and composes objects.""" for rbt in self._robots: arena.attach(rbt.arm) for p in self._props: frame = arena.add_free_entity(p) p.set_freejoint(frame.freejoint) def build_task() -> Tuple[base_task.BaseTask, TaskComponents]: """Builds a BaseTask and all dependencies.""" arena = _build_arena(name='arena') task_props = _build_props() task_robots = [ _build_sawyer_robot(robot_name='robot0'), _build_sawyer_robot(robot_name='robot1') ] task_composer = ExampleTaskComposer(task_robots, task_props) task_composer.compose_entities(arena) components = MutableTaskComponents() _populate_scene_initializers(task_robots, components) _populate_gripper_initializers(task_robots, components) _populate_prop_initializer(task_props, components) # This initializer is used to place the robots before compiling the model. static_initializer = scene_initializer.CompositeSceneInitializer([ components.robot0_pose_initializer, components.robot1_pose_initializer, ]) # This initializer is used to set the state of the simulation once the # physics model as be compiled. dynamic_initializer = entity_initializer.TaskEntitiesInitializer([ components.gripper0_initializer, components.gripper1_initializer, components.prop_initializer, ]) task = base_task.BaseTask( task_name='handshake', arena=arena, robots=task_robots, props=task_props, extra_sensors=[], extra_effectors=[], scene_initializer=static_initializer, episode_initializer=dynamic_initializer, control_timestep=0.1) return task, TaskComponents(**attr.asdict(components)) def _populate_scene_initializers(task_robots: Sequence[robot.Robot], components: MutableTaskComponents) -> None: """Populates components with initializers that arrange the scene.""" pose0 = pose_distribution.ConstantPoseDistribution( np.array([-0.75, 0., 0., 0., 0., 0.])) pose1 = pose_distribution.ConstantPoseDistribution( np.array([0.75, 0., 0.0, 0., 0., 0.])) components.robot0_pose_initializer = scene_initializer.EntityPoseInitializer( entity=task_robots[0].arm_frame, pose_sampler=pose0.sample_pose) components.robot1_pose_initializer = scene_initializer.EntityPoseInitializer( entity=task_robots[1].arm_frame, pose_sampler=pose1.sample_pose) def _populate_gripper_initializers(task_robots: Sequence[robot.Robot], components: MutableTaskComponents) -> None: """Populates components with gripper initializers.""" pose0 = pose_distribution.ConstantPoseDistribution( np.array([-0.1, 0., 0.4, -np.pi, 0., 0.])) pose1 = pose_distribution.ConstantPoseDistribution( np.array([0.1, 0., 0.4, np.pi, 0., 0.])) components.gripper0_initializer = entity_initializer.PoseInitializer( task_robots[0].position_gripper, pose0.sample_pose) components.gripper1_initializer = entity_initializer.PoseInitializer( task_robots[1].position_gripper, pose1.sample_pose) def _populate_prop_initializer(task_props: Sequence[prop.Prop], components: MutableTaskComponents): """Populates components with prop pose initializers.""" prop_pose = pose_distribution.ConstantPoseDistribution( np.array([0.2, 0.2, 0.06, 0., 0., 0.])) components.prop_initializer = entity_initializer.PoseInitializer( initializer_fn=task_props[0].set_pose, pose_sampler=prop_pose.sample_pose) def _build_arena(name: Text) -> composer.Arena: """Builds an arena Entity.""" arena = empty.Arena(name) arena.mjcf_model.option.timestep = 0.001 arena.mjcf_model.option.gravity = (0., 0., -1.0) arena.mjcf_model.size.nconmax = 1000 arena.mjcf_model.size.njmax = 2000 arena.mjcf_model.visual.__getattr__('global').offheight = 480 arena.mjcf_model.visual.__getattr__('global').offwidth = 640 arena.mjcf_model.visual.map.znear = 0.0005 return arena def _build_sawyer_robot(robot_name: str) -> robot.Robot: """Returns a Sawyer robot.""" arm = sawyer.Sawyer( name=robot_name, actuation=sawyer_constants.Actuation.INTEGRATED_VELOCITY) gripper = robotiq_2f85.Robotiq2F85() wrist_ft = robotiq_fts300.RobotiqFTS300() # Compose the robot after its model components are constructed. This should # usually be done early on as some Effectors (and possibly Sensors) can only # be constructed after the robot components have been composed. robot.standard_compose( arm=arm, gripper=gripper, wrist_ft=wrist_ft, wrist_cameras=[]) robot_sensors = [ robot_arm_sensor.RobotArmSensor( arm=arm, name=robot_name, have_torque_sensors=True), robot_tcp_sensor.RobotTCPSensor(gripper=gripper, name=robot_name) ] arm_effector = arm_effector_module.ArmEffector( arm=arm, action_range_override=None, robot_name=robot_name) gripper_effector = default_gripper_effector.DefaultGripperEffector( gripper, robot_name) return robot.StandardRobot( arm=arm, arm_base_site_name='pedestal_attachment', gripper=gripper, wrist_ft=wrist_ft, robot_sensors=robot_sensors, arm_effector=arm_effector, gripper_effector=gripper_effector, name=robot_name) def _build_props() -> Sequence[prop.Prop]: """Build task props.""" block = prop.Block() return (block,)
dm_robotics-main
py/moma/tasks/example_task/task_builder.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 mujoco_rendering.""" from unittest import mock from absl.testing import absltest from dm_robotics.moma.utils import mujoco_rendering import numpy as np _GUI_PATH = mujoco_rendering.__name__ + '.gui' _WINDOW_PARAMS = (640, 480, 'title') class BasicRenderingObserverTest(absltest.TestCase): def setUp(self): super().setUp() self.env = mock.MagicMock() self.env.physics = mock.MagicMock() with mock.patch(_GUI_PATH): self.observer = mujoco_rendering.Observer(self.env, *_WINDOW_PARAMS) self.observer._viewer = mock.MagicMock() self.observer._render_surface = mock.MagicMock() def test_deinitializing_viewer_on_episode_end(self): self.observer.end_episode( agent_id=0, termination_reason=1, agent_time_step=2) self.observer._viewer.deinitialize.assert_called_once() def test_set_camera_config_full_dict(self): initial_camera_cfg = { 'distance': 1.0, 'azimuth': 30.0, 'elevation': -45.0, 'lookat': [0.0, 0.1, 0.2], } self.observer.camera_config = initial_camera_cfg self.observer._viewer.camera.settings.lookat = np.zeros(3) self.observer.step(0, None, None) self.assertEqual(self.observer._viewer.camera.settings.distance, 1.0) self.assertEqual(self.observer._viewer.camera.settings.azimuth, 30.0) self.assertEqual(self.observer._viewer.camera.settings.elevation, -45.0) self.assertTrue(np.array_equal( self.observer._viewer.camera.settings.lookat, [0.0, 0.1, 0.2])) def test_set_camera_config_single_field(self): initial_camera_cfg = { 'distance': 1.0, 'azimuth': 30.0, 'elevation': -45.0, 'lookat': [0.0, 0.1, 0.2], } self.observer.camera_config = initial_camera_cfg self.observer._viewer.camera.settings.lookat = np.zeros(3) self.observer.step(0, None, None) self.assertEqual(self.observer._viewer.camera.settings.distance, 1.0) self.observer.camera_config = { 'distance': 3.0, } self.observer.step(0, None, None) self.assertEqual(self.observer._viewer.camera.settings.distance, 3.0) def test_set_camera_config_fails(self): with self.assertRaises(ValueError): self.observer.camera_config = {'not_a_valid_key': 0} if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/utils/mujoco_rendering_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Util functions for dealing with poses.""" import numpy as np def positive_leading_quat(quat: np.ndarray) -> np.ndarray: """Returns the quaternion with a positive leading scalar (wxyz).""" quat = np.copy(quat) if quat[0] < 0: quat *= -1 return quat
dm_robotics-main
py/moma/utils/pose_utils.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """IK solver for initialization of robot arms.""" import copy from typing import List, NamedTuple, Optional, Sequence, Union from absl import logging from dm_control import mjcf from dm_control.mujoco.wrapper import mjbindings from dm_control.mujoco.wrapper.mjbindings.enums import mjtObj from dm_robotics.controllers import cartesian_6d_to_joint_velocity_mapper from dm_robotics.geometry import geometry from dm_robotics.geometry import mujoco_physics from dm_robotics.transformations import transformations as tr import numpy as np # Default value for the nullspace gain parameter. _NULLSPACE_GAIN = 0.4 # Gain for the linear and angular twist computation, these values should always # be between 0 and 1. 0 corresponds to not move and 1 corresponds to move to the # target in a single integration timestep. _LINEAR_VELOCITY_GAIN = 0.95 _ANGULAR_VELOCITY_GAIN = 0.95 # Integration timestep used when solving the IK. _INTEGRATION_TIMESTEP_SEC = 1.0 # At each step of the solve, we measure how much the tracked element # translated (linear progress) and rotated (angular progress). We compare this # progress to the total linear and angular error and if not enough progress is # made stop the solve before the maximum number of steps is reached. _ERR_TO_PROGRESS_THRESHOLD = 20.0 ### ---------------PARAMETERS USED FOR THE QP MAPPER: START----------------- ### # Regularisation parameter used by the qp to compute joint velocities. _REGULARIZATION_WEIGHT = 0.01 # Ensure that the joint limits are respected. _ENABLE_JOINT_POSITION_LIMITS = True # Gain that scales the joint velocities down when close to the joint limits. _JOINT_POSITION_LIMIT_VELOCITY_SCALE = 1.0 # The minimal distance to joint limits the IK solution can have. _MINIMUM_DISTANCE_FROM_JOINT_POSITION_LIMIT = 0.0 # Maximum number of iteration to find a joint velocity command that applies the # desired twist to the element. _MAX_CARTESIAN_VELOCITY_CONTROL_ITERATIONS = 300 # Number of iterations for the nullspace control problem. _MAX_NULLSPACE_CONTROL_ITERATIONS = 300 # Maximum error allowed for the nullspace problem. _NULLSPACE_PROJECTION_SLACK = 1e-5 # Maximum error allowed between the requested twist command and the actual one. _SOLUTION_TOLERANCE = 1e-4 # Remove the logging when the nullspace cannot find a solution as this # clutters the logging. _LOG_NULLSPACE_FAILURE_WARNINGS = False ### -----------------PARAMETERS USED FOR THE QP MAPPER: END----------------- ### _Binding = Union[mjcf.physics.Binding, mjcf.physics._EmptyBinding] # pylint: disable=protected-access _MjcfElement = mjcf.element._ElementImpl # pylint: disable=protected-access class _Solution(NamedTuple): """Return value of an ik solution. Attributes: qpos: The joint configuration. linear_err: The linear error between the target pose and desired pose. angular_err: The angular error between the target pose and desired pose. """ qpos: np.ndarray linear_err: float angular_err: float class IkSolver(): """Inverse kinematics solver. This class computes a joint configuration that brings an element to a certain pose. """ # The cartesian velocity controller used to solve the IK. _qp_mapper: cartesian_6d_to_joint_velocity_mapper.Mapper # Array of indices that sorts the joints in ascending order. The qp_mapper # returns values in joint-ID ascending order which could be different than # the order of the joints provided by the user. _joints_argsort: List[int] # The desired joint configuration that is set as the nullspace goal. This # corresponds to the mid-range of each joint. The user can override this # reference configuration in the `solve` method. _nullspace_joint_position_reference: List[float] def __init__( self, model: mjcf.RootElement, controllable_joints: List[_MjcfElement], element: _MjcfElement, nullspace_gain: float = _NULLSPACE_GAIN, ): """Constructor. Args: model: The MJCF model root. controllable_joints: The joints that can be controlled to achieve the desired target pose. Only 1 DoF joints are supported. element: The MJCF element that is being placed by the inverse kinematics solver. Only body, geoms, and sites are supported nullspace_gain: Scales the nullspace velocity bias. If the gain is set to 0, there will be no nullspace optimization during the solve process. """ self._physics = mjcf.Physics.from_mjcf_model(model) self._geometry_physics = mujoco_physics.wrap(self._physics) self._joints_binding = _binding(self._physics, controllable_joints) self._num_joints = len(controllable_joints) self._element = element self._nullspace_gain = nullspace_gain self._create_qp_mapper() def solve(self, ref_pose: geometry.Pose, linear_tol: float = 1e-3, angular_tol: float = 1e-3, max_steps: int = 100, early_stop: bool = False, num_attempts: int = 30, stop_on_first_successful_attempt: bool = False, inital_joint_configuration: Optional[np.ndarray] = None, nullspace_reference: Optional[np.ndarray] = None ) -> Optional[np.ndarray]: """Attempts to solve the inverse kinematics. This method computes joint configuration that solves the inverse kinematics problem. Returns None if no solution is found. If multiple solutions are found, the solver will return the one where the joints are closer to the `nullspace_reference`. If none is provided uses the center of the joint ranges Args: ref_pose: Target pose of the controlled element, it must be in the world frame. linear_tol: The linear tolerance, in meters, that determines if the solution found is valid. angular_tol: The angular tolerance, in radians, to determine if the solution found is valid. max_steps: Maximum number of integration steps that can be used. The larger the number of steps the more likely it is a solution will be found but a larger number of steps increases computation time. early_stop: If true, stops the attempt as soon as the configuration is within the linear and angular tolerances. If false, it will always run `max_steps` iterations per attempt and return the last configuration. num_attempts: The number of different attempts the solver should do. For a given target pose, there exists an infinite number of possible solutions, having more attempts allows to compare different joint configurations. The solver will return the solution where the joints are closer to the `nullspace_reference`. Note that not all attempts are successful, and thus, having more attempts gives better chances of finding a correct solution. stop_on_first_successful_attempt: If true, the method will return the first solution that meets the tolerance criteria. If false, returns the solution where the joints are closer the center of their respective range. inital_joint_configuration: A joint configuration that will be used for the first attempt. This can be useful in the case of a complex pose, a user could provide the initial guess that is close to the desired solution. If None, all the joints will be set to 0 for the first attempt. nullspace_reference: The desired joint configuration. When the controlled element is in the desired pose, the solver will try and bring the joint configuration closer to the nullspace reference without moving the element. If no nullspace reference is provided, the center of the joint ranges is used as reference. Returns: If a solution is found, returns the corresponding joint configuration. If the inverse kinematics failed, returns None. Raises: ValueError: If the `nullspace_reference` does not have the correct length. ValueError: If the `inital_joint_configuration` does not have the correct length. """ nullspace_reference = ( nullspace_reference or self._nullspace_joint_position_reference) if len(nullspace_reference) != self._num_joints: raise ValueError( 'The provided nullspace reference does not have the right number of ' f'elements expected length of {self._num_joints}.' f' Got {nullspace_reference}') if inital_joint_configuration is not None: if len(inital_joint_configuration) != self._num_joints: raise ValueError( 'The provided inital joint configuration does not have the right ' f'number of elements expected length of {self._num_joints}.' f' Got {inital_joint_configuration}') inital_joint_configuration = inital_joint_configuration or np.zeros( self._num_joints) nullspace_jnt_qpos_min_err = np.inf sol_qpos = None success = False # Each iteration of this loop attempts to solve the inverse kinematics. # If a solution is found, it is compared to previous solutions. for attempt in range(num_attempts): # Use the user provided joint configuration for the first attempt. if attempt == 0: self._joints_binding.qpos[:] = inital_joint_configuration else: # Randomize the initial joint configuration so that the IK can find # different solutions. qpos_new = np.random.uniform( self._joints_binding.range[:, 0], self._joints_binding.range[:, 1]) self._joints_binding.qpos[:] = qpos_new # Solve the IK. joint_qpos, linear_err, angular_err = self._solve_ik( ref_pose, linear_tol, angular_tol, max_steps, early_stop, nullspace_reference) # Check if the attempt was successful. The solution is saved if the joints # are closer to the nullspace reference. if (linear_err <= linear_tol and angular_err <= angular_tol): success = True nullspace_jnt_qpos_err = np.linalg.norm( joint_qpos - nullspace_reference) if nullspace_jnt_qpos_err < nullspace_jnt_qpos_min_err: nullspace_jnt_qpos_min_err = nullspace_jnt_qpos_err sol_qpos = joint_qpos if success and stop_on_first_successful_attempt: break if not success: logging.warning('Unable to solve the inverse kinematics for ref_pose: ' '%s', ref_pose) return sol_qpos def _create_qp_mapper(self): """Instantiates the cartesian velocity controller used by the ik solver.""" qp_params = cartesian_6d_to_joint_velocity_mapper.Parameters() qp_params.model = self._physics.model qp_params.joint_ids = self._joints_binding.jntid qp_params.object_type = _get_element_type(self._element) qp_params.object_name = self._element.full_identifier qp_params.integration_timestep = _INTEGRATION_TIMESTEP_SEC qp_params.enable_joint_position_limits = _ENABLE_JOINT_POSITION_LIMITS qp_params.joint_position_limit_velocity_scale = ( _JOINT_POSITION_LIMIT_VELOCITY_SCALE) qp_params.minimum_distance_from_joint_position_limit = ( _MINIMUM_DISTANCE_FROM_JOINT_POSITION_LIMIT) qp_params.regularization_weight = _REGULARIZATION_WEIGHT qp_params.max_cartesian_velocity_control_iterations = ( _MAX_CARTESIAN_VELOCITY_CONTROL_ITERATIONS) if self._nullspace_gain > 0: qp_params.enable_nullspace_control = True else: qp_params.enable_nullspace_control = False qp_params.max_nullspace_control_iterations = ( _MAX_NULLSPACE_CONTROL_ITERATIONS) qp_params.nullspace_projection_slack = _NULLSPACE_PROJECTION_SLACK qp_params.solution_tolerance = _SOLUTION_TOLERANCE qp_params.log_nullspace_failure_warnings = _LOG_NULLSPACE_FAILURE_WARNINGS self._qp_mapper = cartesian_6d_to_joint_velocity_mapper.Mapper(qp_params) self._joints_argsort = np.argsort(self._joints_binding.jntid) self._nullspace_joint_position_reference = 0.5 * np.sum( self._joints_binding.range, axis=1) def _solve_ik(self, ref_pose: geometry.Pose, linear_tol: float, angular_tol: float, max_steps: int, early_stop: bool, nullspace_reference: np.ndarray ) -> _Solution: """Finds a joint configuration that brings element pose to target pose.""" cur_frame = geometry.PoseStamped(pose=None, frame=self._element) linear_err = np.inf angular_err = np.inf cur_pose = cur_frame.get_world_pose(self._geometry_physics) previous_pose = copy.copy(cur_pose) # Each iteration of this loop attempts to reduce the error between the # element's pose and the target pose. for _ in range(max_steps): # Find the twist that will bring the element's pose closer to the desired # one. twist = _compute_twist( cur_pose, ref_pose, _LINEAR_VELOCITY_GAIN, _ANGULAR_VELOCITY_GAIN, _INTEGRATION_TIMESTEP_SEC) # Computes the joint velocities to achieve the desired twist. # The joint velocity vector passed to mujoco's integration # needs to have a value for all the joints in the model. The velocity # for all the joints that are not controlled is set to 0. qdot_sol = np.zeros(self._physics.model.nv) joint_vel = self._compute_joint_velocities( twist.full, nullspace_reference) # If we are unable to compute joint velocities we stop the iteration # as the solver is stuck and cannot make any more progress. if joint_vel is not None: qdot_sol[self._joints_binding.dofadr] = joint_vel else: break # The velocity vector is passed to mujoco to be integrated. mjbindings.mjlib.mj_integratePos( self._physics.model.ptr, self._physics.data.qpos, qdot_sol, _INTEGRATION_TIMESTEP_SEC) self._update_physics_data() # Get the distance and the angle between the current pose and the # target pose. cur_pose = cur_frame.get_world_pose(self._geometry_physics) linear_err = np.linalg.norm(ref_pose.position - cur_pose.position) angular_err = np.linalg.norm(_get_orientation_error( ref_pose.quaternion, cur_pose.quaternion)) # Stop if the pose is close enough to the target pose. if (early_stop and linear_err <= linear_tol and angular_err <= angular_tol): break # We measure the progress made during this step. If the error is not # reduced fast enough the solve is stopped to save computation time. linear_change = np.linalg.norm( cur_pose.position - previous_pose.position) angular_change = np.linalg.norm(_get_orientation_error( cur_pose.quaternion, previous_pose.quaternion)) if (linear_err / (linear_change + 1e-10) > _ERR_TO_PROGRESS_THRESHOLD and angular_err / (angular_change + 1e-10) > _ERR_TO_PROGRESS_THRESHOLD): break previous_pose = copy.copy(cur_pose) qpos = np.array(self._joints_binding.qpos) return _Solution(qpos=qpos, linear_err=linear_err, angular_err=angular_err) def _compute_joint_velocities( self, cartesian_6d_target: np.ndarray, nullspace_reference: np.ndarray ) -> Optional[np.ndarray]: """Maps a Cartesian 6D target velocity to joint velocities. Args: cartesian_6d_target: array of size 6 describing the desired 6 DoF Cartesian target [(lin_vel), (ang_vel)]. Must be expressed about the element's origin in the world orientation. nullspace_reference: The desired joint configuration used to compute the nullspace bias. Returns: Computed joint velocities in the same order as the `joints` sequence passed during construction. If a solution could not be found, returns None. """ joint_velocities = np.empty(self._num_joints) nullspace_bias = None if self._nullspace_gain > 0: nullspace_bias = self._nullspace_gain * ( nullspace_reference - self._joints_binding.qpos) / _INTEGRATION_TIMESTEP_SEC # Sort nullspace_bias by joint ID, ascending. The QP requires this. nullspace_bias = nullspace_bias[self._joints_argsort] # Compute joint velocities. The Python bindings throw an exception whenever # the mapper fails to find a solution, in which case we return None. # We need to catch a general exception because the StatusOr->Exception # conversion can result in a wide variety of different exceptions. try: # Reorder the joint velocities to be in the same order as the joints # sequence. The QP returns joints by ascending joint ID which could be # different. joint_velocities[self._joints_argsort] = np.array( self._qp_mapper.compute_joint_velocities( self._physics.data, cartesian_6d_target.tolist(), nullspace_bias)) except Exception: # pylint: disable=broad-except joint_velocities = None logging.warning('Failed to compute joint velocities, returning None.') return joint_velocities def _update_physics_data(self): """Updates the physics data following the integration of the velocities.""" # Clip joint positions; the integration done previously can make joints # out of range. qpos = self._joints_binding.qpos min_range = self._joints_binding.range[:, 0] max_range = self._joints_binding.range[:, 1] qpos = np.clip(qpos, min_range, max_range) self._joints_binding.qpos[:] = qpos # Forward kinematics to update the pose of the tracked element. mjbindings.mjlib.mj_normalizeQuat( self._physics.model.ptr, self._physics.data.qpos) mjbindings.mjlib.mj_kinematics( self._physics.model.ptr, self._physics.data.ptr) mjbindings.mjlib.mj_comPos(self._physics.model.ptr, self._physics.data.ptr) def _get_element_type(element: _MjcfElement): """Returns the MuJoCo enum corresponding to the element type.""" if element.tag == 'body': return mjtObj.mjOBJ_BODY elif element.tag == 'geom': return mjtObj.mjOBJ_GEOM elif element.tag == 'site': return mjtObj.mjOBJ_SITE else: raise ValueError('Element must be a MuJoCo body, geom, or site. Got ' f'[{element.tag}].') def _binding(physics: mjcf.Physics, elements: Union[Sequence[mjcf.Element], mjcf.Element] ) -> _Binding: """Binds the elements with physics and returns a non optional object.""" physics_elements = physics.bind(elements) if physics_elements is None: raise ValueError(f'Calling physics.bind with {elements} returns None.') return physics_elements def _get_orientation_error( to_quat: np.ndarray, from_quat: np.ndarray) -> np.ndarray: """Returns error between the two quaternions.""" err_quat = tr.quat_diff_active(from_quat, to_quat) return tr.quat_to_axisangle(err_quat) def _compute_twist(init_pose: geometry.Pose, ref_pose: geometry.Pose, linear_velocity_gain: float, angular_velocity_gain: float, control_timestep_seconds: float, ) -> geometry.Twist: """Returns the twist to apply to the end effector to reach ref_pose. This function returns the twist that moves init_pose closer to ref_pose. Both poses need to be expressed in the same frame. The returned twist is expressed in the frame located at the initial pose and with the same orientation as the world frame. Args: init_pose: The inital pose. ref_pose: The target pose that we want to reach. linear_velocity_gain: Scales the linear velocity. The value should be between 0 and 1. A value of 0 corresponds to not moving. A value of 1 corresponds to moving from the inital pose to the target pose in a single timestep. angular_velocity_gain: Scales the angualr velocity. The value should be between 0 and 1. A value of 0 corresponds to not rotating. A value of 1 corresponds to rotating from the inital pose to the target pose in a single timestep. control_timestep_seconds: Duration of the control timestep. The outputed twist is intended to be used over that duration. Returns: The twist to be applied to `init_pose` to move in closer to `ref_pose`. The twist is expressed in the frame located at `init_pose` and with the same orientation as the world frame. """ position_error = ref_pose.position - init_pose.position orientation_error = _get_orientation_error( from_quat=init_pose.quaternion, to_quat=ref_pose.quaternion) linear = linear_velocity_gain * position_error / control_timestep_seconds angular = angular_velocity_gain * orientation_error / control_timestep_seconds return geometry.Twist(np.concatenate((linear, angular)))
dm_robotics-main
py/moma/utils/ik_solver.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 related to MuJoCo's collision-detection. This module provides a way of excluding collision detection between geoms that cannot collide because of the contype and conaffinity parameters of Mujoco. This speeds up the simulation. """ from typing import Optional from dm_control import mjcf from dm_control import mujoco def exclude_bodies_based_on_contype_conaffinity( mjcf_model: mjcf.RootElement, exclude_exception_str: Optional[str] = None): """Adds a contact-exclude MJCF element for the body pairs described below. A contact-exclude MJCF element is added for every body pair for which all of their geoms do not pass the contype/conaffinity check. This ensures that the contype/conaffinity filtering happens right after the broad-phase collision detection mechanism, usually decreasing the amount of geoms that are checked through MuJoCo's bounding sphere test. This may improve computation significantly in cases where the broad-phase collision detection is ineffective in pruning geoms. This should be called after mjcf_model has been finalized, to ensure that the body names in the exclude element match those of the compiled model. Args: mjcf_model: mjcf.RootElement of the finalized MuJoCo XML for the scene. exclude_exception_str: if this string is found in the name of the body that body is exempt from the contact.add exclude operation. """ # We compile the model first to make sure all the contypes/conaffinities are # set. xml_string = mjcf_model.to_xml_string() assets = mjcf_model.get_assets() model = mujoco.wrapper.MjModel.from_xml_string(xml_string, assets=assets) # We loop through all body pairs, and exclude them if none of the geoms in the # first body pass the contype/conaffinity check against the geoms in the # second body. for body1_id in range(model.nbody): body1_name = model.id2name(body1_id, "body") if (exclude_exception_str is None or exclude_exception_str not in body1_name): for body2_id in range(body1_id): body2_name = model.id2name(body2_id, "body") if (exclude_exception_str is None or exclude_exception_str not in body2_name): if not _is_any_geom_pass_contype_conaffinity_check( model, body1_id, body2_id): mjcf_model.contact.add( "exclude", body1=body1_name, body2=body2_name) def _is_any_geom_pass_contype_conaffinity_check(model: mujoco.wrapper.MjModel, body1_id: int, body2_id: int): """Returns true if any geom pair passes the contype/conaff check.""" body1_geomadr = model.body_geomadr[body1_id] body2_geomadr = model.body_geomadr[body2_id] body1_geomnum = model.body_geomnum[body1_id] body2_geomnum = model.body_geomnum[body2_id] # If one of the bodies has no geoms we can skip. if body1_geomnum == 0 or body2_geomnum == 0: return True for geom1_id in range(body1_geomadr, body1_geomadr + body1_geomnum): for geom2_id in range(body2_geomadr, body2_geomadr + body2_geomnum): if _is_pass_contype_conaffinity_check(model, geom1_id, geom2_id): return True return False def _is_pass_contype_conaffinity_check(model: mujoco.wrapper.MjModel, geom1_id: int, geom2_id: int): """Returns true if the geoms pass the contype/conaffinity check.""" return model.geom_contype[geom1_id] & model.geom_conaffinity[ geom2_id] or model.geom_contype[geom2_id] & model.geom_conaffinity[ geom1_id]
dm_robotics-main
py/moma/utils/mujoco_collisions.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 pose_utils.""" from absl.testing import absltest from dm_robotics.moma.utils import pose_utils import numpy as np class PoseUtilsTest(absltest.TestCase): def test_positive_leading_quat(self): # Should not change a quaternion with a positive leading scalar. input_quat = [1., 2., 3., 4.] # unnormalized, but doesn't matter. expected_quat = input_quat np.testing.assert_almost_equal( pose_utils.positive_leading_quat(np.array(input_quat)), expected_quat, decimal=3) # But it should change a quaternion with a negative leading scalar. input_quat = [-1., 2., 3., 4.] # unnormalized, but doesn't matter. expected_quat = [1., -2., -3., -4.] np.testing.assert_almost_equal( pose_utils.positive_leading_quat(np.array(input_quat)), expected_quat, decimal=3) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/utils/pose_utils_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 ik_solver.""" from absl.testing import absltest from absl.testing import parameterized from dm_robotics.geometry import geometry from dm_robotics.geometry import mujoco_physics from dm_robotics.geometry import pose_distribution from dm_robotics.moma.models.end_effectors.robot_hands import robotiq_2f85 from dm_robotics.moma.models.robots.robot_arms import sawyer from dm_robotics.moma.utils import ik_solver from dm_robotics.transformations import transformations as tr import numpy as np # Linear and angular tolerance when comparing the end pose and the target pose. _LINEAR_TOL = 1e-4 _ANGULAR_TOL = 1e-4 class IkSolverTest(parameterized.TestCase): @parameterized.named_parameters( ('sawyer_with_gripper', True), ('sawyer_without_gripper', False),) def test_ik_solver_with_pose(self, with_gripper): # Seed for randomness to prevent flaky tests. np.random.seed(42) rng = np.random.RandomState(42) # Change the ik site depending if the gripper is attached or not. arm = sawyer.Sawyer() if with_gripper: gripper = robotiq_2f85.Robotiq2F85() arm.attach(gripper) ik_site = gripper.tool_center_point else: ik_site = arm.wrist_site solver = ik_solver.IkSolver( arm.mjcf_model, arm.joints, ik_site) # Create the distibution from which the ref_poses will be sampled. pos_dist = pose_distribution.UniformPoseDistribution( min_pose_bounds=[ 0.30, -0.15, 0.10, 2 * np.pi / 3, -np.pi / 5, -np.pi / 4], max_pose_bounds=[ 0.55, 0.15, 0.40, 4 * np.pi / 3, np.pi / 5, np.pi / 4]) # Each iteration samples a new target position, solves the IK and checks # that the solution is correct. for _ in range(500): # Sample a new ref_pose position, quaternion = pos_dist.sample_pose(rng) ref_pose = geometry.Pose(position, quaternion) # Check that we can solve the problem and that the solution is within # the joint ranges. qpos_sol = solver.solve( ref_pose, linear_tol=_LINEAR_TOL, angular_tol=_ANGULAR_TOL, early_stop=True, stop_on_first_successful_attempt=True) self.assertIsNotNone(qpos_sol) min_range = solver._joints_binding.range[:, 0] max_range = solver._joints_binding.range[:, 1] np.testing.assert_array_compare(np.less_equal, qpos_sol, max_range) np.testing.assert_array_compare(np.greater_equal, qpos_sol, min_range) # Check the max linear and angular errors are satisfied. geometry_physics = mujoco_physics.wrap(solver._physics) solver._joints_binding.qpos[:] = qpos_sol end_pose = geometry_physics.world_pose(ik_site) linear_error = np.linalg.norm(end_pose.position - ref_pose.position) angular_error = np.linalg.norm(_get_orientation_error( end_pose.quaternion, ref_pose.quaternion)) self.assertLessEqual(linear_error, _LINEAR_TOL) self.assertLessEqual(angular_error, _ANGULAR_TOL) def test_ik_solver_when_solution_found_but_last_attempt_failed(self): """Test correct qpos is returned when last attempt failed. This test is used to ensure that if the solver finds a solution on one of the attempts and that the final attempt the solver does fails, the correct qpos is returned. """ # Seed for randomness to prevent flaky tests. np.random.seed(42) rng = np.random.RandomState(42) arm = sawyer.Sawyer() ik_site = arm.wrist_site solver = ik_solver.IkSolver( arm.mjcf_model, arm.joints, ik_site) # Create the distibution from which the ref_poses will be sampled. pos_dist = pose_distribution.UniformPoseDistribution( min_pose_bounds=[ 0.30, -0.15, 0.10, 2 * np.pi / 3, -np.pi / 5, -np.pi / 4], max_pose_bounds=[ 0.55, 0.15, 0.40, 4 * np.pi / 3, np.pi / 5, np.pi / 4]) # We continue until we find a solve where we can test the behaviour. found_solution_and_final_attempt_failed = False while not found_solution_and_final_attempt_failed: # Sample a new ref_pose position, quaternion = pos_dist.sample_pose(rng) ref_pose = geometry.Pose(position, quaternion) # Check that a solution has been found qpos_sol = solver.solve(ref_pose) self.assertIsNotNone(qpos_sol) # Check if the final attempt joint configuration is a solution. geometry_physics = mujoco_physics.wrap(solver._physics) last_attempt_end_pose = geometry_physics.world_pose(ik_site) last_attempt_linear_error = np.linalg.norm( last_attempt_end_pose.position - ref_pose.position) last_attempt_angular_error = np.linalg.norm(_get_orientation_error( last_attempt_end_pose.quaternion, ref_pose.quaternion)) # If it is not a solution check that the returned qpos is a solution. if (last_attempt_linear_error > _LINEAR_TOL or last_attempt_angular_error > _ANGULAR_TOL): found_solution_and_final_attempt_failed = True solver._joints_binding.qpos[:] = qpos_sol solution_pose = geometry_physics.world_pose(ik_site) linear_error = np.linalg.norm( solution_pose.position - ref_pose.position) angular_error = np.linalg.norm(_get_orientation_error( solution_pose.quaternion, ref_pose.quaternion)) self.assertLessEqual(linear_error, _LINEAR_TOL) self.assertLessEqual(angular_error, _ANGULAR_TOL) def test_raises_when_nullspace_reference_wrong_length(self): # Change the ik site depending if the gripper is attached or not. arm = sawyer.Sawyer() solver = ik_solver.IkSolver( arm.mjcf_model, arm.joints, arm.wrist_site) ref_pose = geometry.Pose([0., 0., 0.], [1., 0., 0., 0.]) wrong_nullspace_ref = np.asarray([0., 0., 0.]) with self.assertRaises(ValueError): solver.solve(ref_pose, nullspace_reference=wrong_nullspace_ref) def test_raises_when_initial_joint_confiugration_wrong_length(self): # Change the ik site depending if the gripper is attached or not. arm = sawyer.Sawyer() solver = ik_solver.IkSolver( arm.mjcf_model, arm.joints, arm.wrist_site) ref_pose = geometry.Pose([0., 0., 0.], [1., 0., 0., 0.]) wrong_initial_joint_configuration = np.asarray([0., 0., 0.]) with self.assertRaises(ValueError): solver.solve( ref_pose, inital_joint_configuration=wrong_initial_joint_configuration) def test_return_none_when_passing_impossible_target(self): # Change the ik site depending if the gripper is attached or not. arm = sawyer.Sawyer() solver = ik_solver.IkSolver( arm.mjcf_model, arm.joints, arm.wrist_site) ref_pose = geometry.Pose([3., 3., 3.], [1., 0., 0., 0.]) qpos_sol = solver.solve(ref_pose) self.assertIsNone(qpos_sol) def _get_orientation_error( to_quat: np.ndarray, from_quat: np.ndarray) -> np.ndarray: """Returns error between the two quaternions.""" err_quat = tr.quat_diff_active(from_quat, to_quat) return tr.quat_to_axisangle(err_quat) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/utils/ik_solver_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 mujoco_collisions.""" from absl.testing import absltest from dm_control import mjcf from dm_robotics.moma.utils import mujoco_collisions class MujocoCollisionsTest(absltest.TestCase): def test_collision_are_excluded_when_contype_is_zero(self): # We create a mjcf model with 3 boxes and disable the contype for 2 of them. mjcf_root = mjcf.RootElement() box1_body = mjcf_root.worldbody.add( 'body', pos='0 0 0', axisangle='0 0 1 0', name='box1') box1_body.add( 'geom', name='box1', type='box', size='.2 .2 .2', contype='0') box2_body = mjcf_root.worldbody.add( 'body', pos='0 1 0', axisangle='0 0 1 0', name='box2',) box2_body.add( 'geom', name='box2', type='box', size='.2 .2 .2', contype='0') # For the third body disable conaffinity and ensure it does not exclude the # contacts between this box and the first two. box3_body = mjcf_root.worldbody.add( 'body', pos='0 0 1', axisangle='0 0 1 0', name='box3') box3_body.add( 'geom', name='box3', type='box', size='.2 .2 .2', conaffinity='0') mujoco_collisions.exclude_bodies_based_on_contype_conaffinity(mjcf_root) # We assert that the contact array only excludes contacts between box 1 and # box 2. [child] = mjcf_root.contact.all_children() self.assertEqual('exclude', child.spec.name) self.assertEqual('box2', child.body1) self.assertEqual('box1', child.body2) def test_collision_are_excluded_when_conaffinity_is_zero(self): # We create a mjcf model with 3 boxes and disable the conaffinity for # 2 of them. mjcf_root = mjcf.RootElement() box1_body = mjcf_root.worldbody.add( 'body', pos='0 0 0', axisangle='0 0 1 0', name='box1') box1_body.add( 'geom', name='box1', type='box', size='.2 .2 .2', conaffinity='0') box2_body = mjcf_root.worldbody.add( 'body', pos='0 1 0', axisangle='0 0 1 0', name='box2',) box2_body.add( 'geom', name='box2', type='box', size='.2 .2 .2', conaffinity='0') # For the third body disable contype and ensure it does not exclude the # contacts between this box and the first two. box3_body = mjcf_root.worldbody.add( 'body', pos='0 0 1', axisangle='0 0 1 0', name='box3') box3_body.add( 'geom', name='box3', type='box', size='.2 .2 .2', contype='0') mujoco_collisions.exclude_bodies_based_on_contype_conaffinity(mjcf_root) # We assert that the contact array only excludes contacts between box 1 and # box 2. [child] = mjcf_root.contact.all_children() self.assertEqual('exclude', child.spec.name) self.assertEqual('box2', child.body1) self.assertEqual('box1', child.body2) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/utils/mujoco_collisions_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Stripped down Mujoco environment renderer implemented as an Observer.""" from dm_control import _render from dm_control.viewer import gui from dm_control.viewer import renderer from dm_control.viewer import viewer _DEFAULT_WIDTH = 640 _DEFAULT_HEIGHT = 480 _MAX_FRONTBUFFER_SIZE = 2048 _DEFAULT_WINDOW_TITLE = 'Rendering Observer' class Observer: """A stripped down 3D renderer for Mujoco environments. Attributes: camera_config: A dict. The camera configuration for the observer. """ def __init__(self, env, width, height, name): """Observer constructor. Args: env: The environment. width: Window width, in pixels. height: Window height, in pixels. name: Window name. """ self._env = env self._viewport = renderer.Viewport(width, height) self._viewer = None self._camera_config = { 'lookat': None, 'distance': None, 'azimuth': None, 'elevation': None } self._camera_config_dirty = False self._render_surface = _render.Renderer( max_width=_MAX_FRONTBUFFER_SIZE, max_height=_MAX_FRONTBUFFER_SIZE) self._renderer = renderer.NullRenderer() self._window = gui.RenderWindow(width, height, name) @classmethod def build(cls, env, height=_DEFAULT_HEIGHT, width=_DEFAULT_WIDTH, name=_DEFAULT_WINDOW_TITLE): """Returns a Observer with a default platform. Args: env: The environment. height: Window height, in pixels. width: Window width, in pixels. name: Window name. Returns: Newly constructor Observer. """ return cls(env, width, height, name) def _apply_camera_config(self): for key, value in self._camera_config.items(): if value is not None: if key == 'lookat': # special case since we can't just set this attr. self._viewer.camera.settings.lookat[:] = self._camera_config['lookat'] else: setattr(self._viewer.camera.settings, key, value) self._camera_config_dirty = False @property def camera_config(self): """Retrieves the current camera configuration.""" if self._viewer: for key, value in self._camera_config.items(): self._camera_config[key] = getattr(self._viewer.camera.settings, key, value) return self._camera_config @camera_config.setter def camera_config(self, camera_config): for key, value in camera_config.items(): if key not in self._camera_config: raise ValueError(('Key {} is not a valid key in camera_config. ' 'Valid keys are: {}').format( key, list(camera_config.keys()))) self._camera_config[key] = value self._camera_config_dirty = True def begin_episode(self, *unused_args, **unused_kwargs): """Notifies the observer that a new episode is about to begin. Args: *unused_args: ignored. **unused_kwargs: ignored. """ if not self._viewer: self._viewer = viewer.Viewer( self._viewport, self._window.mouse, self._window.keyboard) if self._viewer: self._renderer = renderer.OffScreenRenderer( self._env.physics.model, self._render_surface) self._viewer.initialize(self._env.physics, self._renderer, False) def end_episode(self, *unused_args, **unused_kwargs): """Notifies the observer that an episode has ended. Args: *unused_args: ignored. **unused_kwargs: ignored. """ if self._viewer: self._viewer.deinitialize() def _render(self): self._viewport.set_size(*self._window.shape) self._viewer.render() return self._renderer.pixels def step(self, *unused_args, **unused_kwargs): """Notifies the observer that an agent has taken a step. Args: *unused_args: ignored. **unused_kwargs: ignored. """ if self._viewer: if self._camera_config_dirty: self._apply_camera_config() self._window.update(self._render)
dm_robotics-main
py/moma/utils/mujoco_rendering.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Type declaration used in models.""" from typing import Union from dm_control import mjcf # Return type of physics.bind() Binding = Union[mjcf.physics.Binding, mjcf.physics._EmptyBinding] # pylint: disable=protected-access # Type of the mjcf elements. This is needed for pytype compatibility because # mcjf.Element doesn't implement anything and therefor has none of the # properties that are being access. MjcfElement = mjcf.element._ElementImpl # pylint: disable=protected-access
dm_robotics-main
py/moma/models/types.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """MoMA Models utils.""" from typing import Any, Dict, List, Optional, Union, Sequence from dm_control import mjcf from dm_robotics.moma.models import types # Parameters that are added to every # collision geom to ensure they are all # uniform in color, contype/conaffinity, and # group. _COLLISION_GEOMS_KWARGS = { 'element_name': 'geom', 'contype': '0', 'conaffinity': '0', 'rgba': '1 1 1 0.3', 'group': '5' } def default_collision_geoms_kwargs() -> Dict[str, Any]: return _COLLISION_GEOMS_KWARGS.copy() def attach_collision_geoms( mjcf_model: mjcf.RootElement, collision_geoms_dict: Dict[str, List[Dict[str, str]]], shared_kwargs: Optional[Dict[str, str]] = None): """Attaches primitive collision geoms as defined by collision_geoms_dict. Args: mjcf_model: MJCF model on which to attach the collision geoms. collision_geoms_dict: Dictionary mapping body names to primitive geom parameters. For every collision geom parameter, the shared collision parameters specified by shared_kwargs will be added, and a new geom will be attached to the respective body name. shared_kwargs: Parameters to be shared between all collision geoms. If this is None (which is the default value), then the values from `default_collision_geoms_kwargs` are used. An empty dict will result in no shared kwargs. Returns: List of collision geoms attached to their respective bodies. """ if shared_kwargs is None: shared_kwargs = default_collision_geoms_kwargs() attached_collision_geoms = [] for body_name, collision_geoms in collision_geoms_dict.items(): for kwargs in collision_geoms: merged_kwargs = kwargs.copy() merged_kwargs.update(shared_kwargs) attached_collision_geoms.append( mjcf_model.find('body', body_name).add(**merged_kwargs)) return attached_collision_geoms def binding(physics: mjcf.Physics, elements: Union[Sequence[mjcf.Element], mjcf.Element] ) -> types.Binding: """Binds the elements with physics and returns a non optional object. The goal of this function is to return a non optional element so that when the physics_elements object is used, there is no pytype error. Args: physics: The mujoco physics instance. elements: The mjcf elements to bind. Returns: The non optional binding of the elements. """ physics_elements = physics.bind(elements) if physics_elements is None: raise ValueError(f'Calling physics.bind with {elements} returns None.') return physics_elements
dm_robotics-main
py/moma/models/utils.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 empty.""" from absl.testing import absltest from dm_control import mjcf from dm_robotics.moma.models.arenas import empty class TestArena(absltest.TestCase): def test_initialize(self): arena = empty.Arena() physics = mjcf.Physics.from_mjcf_model(arena.mjcf_model) physics.step() if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/models/arenas/empty_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 empty space.""" import os from typing import Optional from dm_control import composer from dm_control import mjcf RESOURCES_ROOT_DIR = os.path.dirname(__file__) # arenas _EMPTY_CELL_XML_PATH = os.path.join(RESOURCES_ROOT_DIR, 'empty_assets/arena.xml') class Arena(composer.Arena): """An empty arena with a ground plane and camera.""" def _build(self, name: Optional[str] = None): """Initializes this arena. Args: name: (optional) A string, the name of this arena. If `None`, use the model name defined in the MJCF file. """ super()._build(name) self._mjcf_root.include_copy( mjcf.from_path(_EMPTY_CELL_XML_PATH), override_attributes=True) self._ground = self._mjcf_root.find('geom', 'ground') @property def ground(self): """The ground plane mjcf element.""" return self._ground @property def mjcf_model(self) -> mjcf.RootElement: """Returns the `mjcf.RootElement` object corresponding to this arena.""" return self._mjcf_root
dm_robotics-main
py/moma/models/arenas/empty.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Defines Robotiq 2-finger 85 adaptive gripper constants.""" import os # pylint: disable=unused-import NO_GRASP = 1 # no object grasped INWARD_GRASP = 2 # grasp while moving inwards OUTWARD_GRASP = 3 # grasp while moving outwards # pylint: disable=line-too-long # XML path of the Robotiq 2F85 robot hand. XML_PATH = (os.path.join(os.path.dirname(__file__), '..', '..', 'vendor', 'robotiq_beta_robots', 'mujoco', 'robotiq_2f85_v2.xml')) # pylint: enable=line-too-long # Located at the center of the finger contact surface. TCP_SITE_POS = (0., 0., 0.1489)
dm_robotics-main
py/moma/models/end_effectors/robot_hands/robotiq_2f85_constants.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """MOMA Composer Robot Hand. Rationale and difference to `robot_base.RobotHand`: MoMa communicates to hardware (sim and real) though the Sensor and Actuator interfaces. It does not intend users (for example scripted policies) to perform these actions through the set_grasp function. While sim hardware can and should be reset (aka initialized) differently to real hardware, it's expected that normal behavioural policies, learnt or not, use the Sensor and Actuator interfaces. In this way the same control mechanisms, e.g. collision avoidance, cartesian to joint mapping can be used without special cases. """ import abc from typing import Sequence from typing import Union from dm_control import composer from dm_control.entities.manipulators import base as robot_base from dm_robotics.moma.models import types class RobotHand(abc.ABC, composer.Entity): """MOMA composer robot hand base class.""" @abc.abstractmethod def _build(self): """Entity initialization method to be overridden by subclasses.""" raise NotImplementedError @property @abc.abstractmethod def joints(self) -> Sequence[types.MjcfElement]: """List of joint elements belonging to the hand.""" raise NotImplementedError @property @abc.abstractmethod def actuators(self) -> Sequence[types.MjcfElement]: """List of actuator elements belonging to the hand.""" raise NotImplementedError @property @abc.abstractmethod def mjcf_model(self) -> types.MjcfElement: """Returns the `mjcf.RootElement` object corresponding to the robot hand.""" raise NotImplementedError @property @abc.abstractmethod def name(self) -> str: """Name of the robot hand.""" raise NotImplementedError @property @abc.abstractmethod def tool_center_point(self) -> types.MjcfElement: """Tool center point site of the hand.""" raise NotImplementedError # The interfaces of moma's RobotHand and dm_control's RobotHand intersect. # In particular: # * tool_center_point # * actuators # * dm_control.composer.Entity as a common base class. # # Some code is intended to be compatible with either type, and can use this # Gripper type to express that intent. AnyRobotHand = Union[RobotHand, robot_base.RobotHand]
dm_robotics-main
py/moma/models/end_effectors/robot_hands/robot_hand.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 Robotiq 2-finger 85 adaptive gripper.""" from absl.testing import absltest from absl.testing import parameterized from dm_control import composer from dm_control import mjcf from dm_robotics.moma.models.end_effectors.robot_hands import robotiq_2f85 from dm_robotics.moma.models.end_effectors.robot_hands import robotiq_2f85_constants as consts import numpy as np # The default control time step between two agent actions. _DEFAULT_CONTROL_TIMESTEP = 0.05 # The default physics timestep used by the simulation. _DEFAULT_PHYSICS_TIMESTEP = 0.0005 _GRIPPER_CLOSED_ANGLE_THRESHOLD = 254 _GRIPPER_OPENED_ANGLE_THRESHOLD = 1 _OPEN_VEL = -255 _CLOSE_VEL = 255 _POS_SCALE = 255 class GripperTask(composer.Task): """Dummy task containing only a gripper.""" def __init__(self, gripper): self.gripper = gripper self.set_timesteps( control_timestep=_DEFAULT_CONTROL_TIMESTEP, physics_timestep=_DEFAULT_PHYSICS_TIMESTEP) def get_reward(self, physics): return 0. @property def name(self): return 'gripper_task' @property def root_entity(self): return self.gripper def _get_pos(environment): return environment.task.gripper.convert_position( environment.physics.bind( environment.task.gripper.joint_sensor).sensordata) def measure_open_ticks_per_sec(environment, velocity): while _get_pos(environment) < _GRIPPER_CLOSED_ANGLE_THRESHOLD: environment.step(np.array([_CLOSE_VEL])) start_time = environment.physics.time() while _get_pos(environment) > _GRIPPER_OPENED_ANGLE_THRESHOLD: environment.step(np.array([velocity])) end_time = environment.physics.time() return -1.0 * _POS_SCALE / (end_time - start_time) def measure_close_ticks_per_sec(environment, velocity): while _get_pos(environment) > _GRIPPER_OPENED_ANGLE_THRESHOLD: environment.step(np.array([_OPEN_VEL])) start_time = environment.physics.time() while _get_pos(environment) < _GRIPPER_CLOSED_ANGLE_THRESHOLD: environment.step(np.array([velocity])) end_time = environment.physics.time() return 1.0 * _POS_SCALE / (end_time - start_time) class Robotiq2F85Test(parameterized.TestCase): """Tests for the Robotiq 2-finger 85 adaptive gripper.""" def test_physics_step(self): gripper = robotiq_2f85.Robotiq2F85() physics = mjcf.Physics.from_mjcf_model(gripper.mjcf_model) physics.step() def test_ctrlrange(self): gripper = robotiq_2f85.Robotiq2F85() physics = mjcf.Physics.from_mjcf_model(gripper.mjcf_model) min_ctrl, max_ctrl = physics.bind(gripper.actuators[0]).ctrlrange self.assertEqual(255.0, max_ctrl) self.assertEqual(-255.0, min_ctrl) def test_action_spec(self): gripper = robotiq_2f85.Robotiq2F85() task = GripperTask(gripper) environment = composer.Environment(task) action_spec = environment.action_spec() self.assertEqual(-255.0, action_spec.minimum[0]) self.assertEqual(255.0, action_spec.maximum[0]) def test_grasp_fully_open(self): gripper = robotiq_2f85.Robotiq2F85() task = GripperTask(gripper) environment = composer.Environment(task) while _get_pos(environment) > _GRIPPER_OPENED_ANGLE_THRESHOLD: environment.step(np.array([_OPEN_VEL])) self.assertEqual(0, _get_pos(environment)) def test_grasp_fully_closeed(self): gripper = robotiq_2f85.Robotiq2F85() task = GripperTask(gripper) environment = composer.Environment(task) while _get_pos(environment) < _GRIPPER_CLOSED_ANGLE_THRESHOLD: environment.step(np.array([_CLOSE_VEL])) self.assertEqual(255, _get_pos(environment)) def test_boxes_in_fingertips(self): gripper = robotiq_2f85.Robotiq2F85() for side in ('left', 'right'): for idx in (1, 2): self.assertIsNotNone(gripper.mjcf_model.find( 'geom', f'{side}_collision_box{idx}')) def test_inwards_grasp(self): gripper = robotiq_2f85.Robotiq2F85() gripper.tool_center_point.parent.add( 'geom', name='inward_colliding_box', type='box', size='0.03 0.03 0.03', pos=gripper.tool_center_point.pos) task = GripperTask(gripper) environment = composer.Environment(task) # Check that we start with no grasp. self.assertEqual( gripper.grasp_sensor_callable(environment.physics), consts.NO_GRASP) while gripper.grasp_sensor_callable( environment.physics) is not consts.INWARD_GRASP: environment.step(np.array([_CLOSE_VEL])) # Check that we have inward grasp. self.assertEqual( gripper.grasp_sensor_callable(environment.physics), consts.INWARD_GRASP) def test_actuation_is_valid(self): gripper = robotiq_2f85.Robotiq2F85() physics = mjcf.Physics.from_mjcf_model(gripper.mjcf_model) act_min = 0.0 act_max = 255.0 actuators = physics.bind(gripper.actuators) # Actuator state should be clipped if the actuation goes over or below the # control range. actuators.act = [-10] gripper.after_substep(physics, None) np.testing.assert_array_equal(actuators.act, act_min) actuators.act = [666] gripper.after_substep(physics, None) np.testing.assert_array_equal(actuators.act, act_max) # Actuator state should not change the actuation actuators.act = [123] gripper.after_substep(physics, None) np.testing.assert_array_equal(actuators.act, 123) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/models/end_effectors/robot_hands/robotiq_2f85_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Robotiq 2-finger 85 adaptive gripper class.""" from typing import List, Tuple, Optional from dm_control import mjcf from dm_robotics.moma.models import types from dm_robotics.moma.models import utils as models_utils from dm_robotics.moma.models.end_effectors.robot_hands import robot_hand from dm_robotics.moma.models.end_effectors.robot_hands import robotiq_2f85_constants as consts import numpy as np _GRIPPER_SITE_NAME = 'pinch_site' _ACTUATOR_NAME = 'fingers_actuator' _SENSOR_NAME = 'fingers_pos' _JOINT_NAME = 'left_driver_joint' COLLISION_CLASS = 'reinforced_fingertip' _PAD_GEOM_NAMES = [ 'reinforced_right_fingertip_geom', 'reinforced_left_fingertip_geom', ] _PAD_COLOR = (1., 1., 1., 1.) _POS_SCALE = 255. _VELOCITY_CTRL_TOL = 2 _DEFAULT_GRIPPER_FRICTION = (0.5, 0.1, 0.01) _LEGACY_GRIPPER_FRICTION = (1.5, 0.1, 0.001) # The torque tau that is applied to the actuator is: # tau = gainprm[0] * act + bias[1] * q + bias[2] * q_dot # where `act` is the current target reference of the actuator, # `q` is the current position of the joint and `q_dot` is the joint velocity. # `q_dot` is used for damping but we add it to the joint instead of the # actuator. This has to do with the underlying simulation as joint damping is # more stable. # The control range of the actuator is [0, 255] but the actual joint range is # [0 0.8] so we need to ensure that there is a mapping that is done from one # range to the other. We want an effective torque of bias[0] Nm when the # actuator is fully closed. Therefore we have the following equality: # gainprm[0] * 255 + x * 0.8 = 0 # gainprm[0] = - bias[0] * 0.8 / 255 _GAINPRM = (100. * 0.8 / 255, 0.0, 0.0) _BIASPRM = (0.0, -100, 0.0) _BASE_COLLISION_KWARGS = [{ 'name': 'base_CollisionGeom_1', 'type': 'cylinder', 'pos': '0 0 0.01', 'size': '0.04 0.024', }, { 'name': 'base_CollisionGeom_2', 'type': 'sphere', 'pos': '0 0 0.05', 'size': '0.045', }] _RIGHT_DRIVER_COLLISION_KWARGS = [{ 'name': 'right_driver_CollisionGeom', 'type': 'capsule', 'fromto': '0 0 0 0 0.027 0.0018', 'size': '0.015', }] _RIGHT_COUPLER_COLLISION_KWARGS = [{ 'name': 'right_coupler_CollisionGeom', 'type': 'capsule', 'fromto': '0 0 0 0 0.005 0.045', 'size': '0.015', }] _RIGHT_SPRING_LINK_COLLISION_KWARGS = [{ 'name': 'right_spring_link_CollisionGeom', 'type': 'capsule', 'fromto': '0 0 0 0 0.031 0.036', 'size': '0.02', }] _RIGHT_FOLLOWER_COLLISION_KWARGS = [{ 'name': 'right_follower_CollisionGeom', 'type': 'sphere', 'pos': '0 -0.01 0.005', 'size': '0.015', }] _LEFT_DRIVER_COLLISION_KWARGS = [{ 'name': 'left_driver_CollisionGeom', 'type': 'capsule', 'fromto': '0 0 0 0 0.027 0.0018', 'size': '0.015', }] _LEFT_COUPLER_COLLISION_KWARGS = [{ 'name': 'left_coupler_CollisionGeom', 'type': 'capsule', 'fromto': '0 0 0 0 0.005 0.045', 'size': '0.015', }] _LEFT_SPRING_LINK_COLLISION_KWARGS = [{ 'name': 'left_spring_link_CollisionGeom', 'type': 'capsule', 'fromto': '0 0 0 0 0.031 0.036', 'size': '0.02', }] _LEFT_FOLLOWER_COLLISION_KWARGS = [{ 'name': 'left_follower_CollisionGeom', 'type': 'sphere', 'pos': '0 -0.01 0.005', 'size': '0.015', }] _RIGHT_PAD_COLLISION_KWARGS = [{ 'name': 'right_pad_CollisionGeom', 'type': 'box', 'pos': '0 0.004 0.019', 'size': '0.012 0.01 0.019', }] _LEFT_PAD_COLLISION_KWARGS = [{ 'name': 'left_pad_CollisionGeom', 'type': 'box', 'pos': '0 0.004 0.019', 'size': '0.012 0.01 0.019', }] # Dictionary mapping body names to a list of their collision geoms _COLLISION_GEOMS_DICT = { 'base': _BASE_COLLISION_KWARGS, 'right_driver': _RIGHT_DRIVER_COLLISION_KWARGS, 'right_coupler': _RIGHT_COUPLER_COLLISION_KWARGS, 'right_spring_link': _RIGHT_SPRING_LINK_COLLISION_KWARGS, 'right_follower': _RIGHT_FOLLOWER_COLLISION_KWARGS, 'left_driver': _LEFT_DRIVER_COLLISION_KWARGS, 'left_coupler': _LEFT_COUPLER_COLLISION_KWARGS, 'left_spring_link': _LEFT_SPRING_LINK_COLLISION_KWARGS, 'left_follower': _LEFT_FOLLOWER_COLLISION_KWARGS, 'right_pad': _RIGHT_PAD_COLLISION_KWARGS, 'left_pad': _LEFT_PAD_COLLISION_KWARGS, } class Robotiq2F85(robot_hand.RobotHand): """Robotiq 2-finger 85 adaptive gripper.""" _mjcf_root: mjcf.RootElement def _build(self, name: str = 'robotiq_2f85', gainprm: Tuple[float, float, float] = _GAINPRM, biasprm: Tuple[float, float, float] = _BIASPRM, tcp_orientation: Optional[np.ndarray] = None, use_realistic_friction: bool = True): """Initializes the Robotiq 2-finger 85 gripper. Args: name: The name of this robot. Used as a prefix in the MJCF name gainprm: The gainprm of the finger actuator. biasprm: The biasprm of the finger actuator. tcp_orientation: Quaternion [w, x, y, z] representing the orientation of the tcp frame of the gripper. This is needed for compatibility between sim and real. This depends on which robot is being used so we need it to be parametrizable. If None, use the original tcp site. use_realistic_friction: If true will use friction parameters which result in a more realistic. Should only be set to False for backwards compatibility. """ self._mjcf_root = mjcf.from_path(consts.XML_PATH) self._mjcf_root.model = name # If the user provided a quaternion, rotate the tcp site. Otherwise use the # default one. if tcp_orientation is not None: gripper_base = self.mjcf_model.find('body', 'base') gripper_base.add( 'site', type='sphere', name='aligned_gripper_tcp', pos=consts.TCP_SITE_POS, quat=tcp_orientation) self._tool_center_point = self.mjcf_model.find( 'site', 'aligned_gripper_tcp') else: self._tool_center_point = self._mjcf_root.find('site', _GRIPPER_SITE_NAME) self._finger_actuator = self._mjcf_root.find('actuator', _ACTUATOR_NAME) self._joint_sensor = self._mjcf_root.find('sensor', _SENSOR_NAME) self._joints = [self._mjcf_root.find('joint', _JOINT_NAME)] # Use integrated velocity control. self._define_integrated_velocity_actuator(gainprm, biasprm) # Cache the limits for the finger joint. joint_min, joint_max = self._finger_actuator.tendon.joint[ 0].joint.dclass.joint.range self._joint_offset = joint_min self._joint_scale = joint_max - joint_min self._color_pads() self._add_collision_geoms() self._add_collisions_boxes() self._set_physics_properties(use_realistic_friction) def _set_physics_properties(self, use_realistic_friction: bool): """Set physics related properties.""" # Set collision and friction parameter to the same values as in the jaco # hand - as we know they work very stable. padbox_class = self._mjcf_root.find('default', COLLISION_CLASS) if use_realistic_friction: padbox_class.geom.friction = _DEFAULT_GRIPPER_FRICTION else: padbox_class.geom.friction = _LEGACY_GRIPPER_FRICTION # These values of solimp and solref have been tested at different physics # timesteps [5e-4, 5e-3]. They make the gripper less stiff and allow a # proper object-gripper interaction at larger physics timestep. padbox_class.geom.solimp = (0.9, 0.95, 0.001, 0.01, 2) padbox_class.geom.solref = (-30000, -200) # Adapt spring link stiffness to allow proper initialisation and more # realistic behaviour. The original value will cause one of the links # to get stuck in a bent position after initialisation sometimes. spring_link_class = self._mjcf_root.find('default', 'spring_link') spring_link_class.joint.stiffness = 0.01 # Adapt the driver joint to make movement of gripper slower, similar to the # real hardware. driver_class = self._mjcf_root.find('default', 'driver') driver_class.joint.armature = 0.1 # Add in the damping on the joint level instead of on the actuator level # this results in a more stable damping. driver_class.joint.damping = 1 def _add_collisions_boxes(self): """Adds two boxes to each of the fingertips to improve physics stability.""" for side in ('left', 'right'): pad = self._mjcf_root.find('body', f'{side}_pad') pad.add( 'geom', name=f'{side}_collision_box1', dclass='reinforced_fingertip', size=[0.007, 0.0021575, 0.005], type='box', rgba=[0.0, 0.0, 0.0, 0.0], pos=[0.0, 0.0117, 0.03]) pad.add( 'geom', name=f'{side}_collision_box2', dclass='reinforced_fingertip', size=[0.007, 0.0021575, 0.005], type='box', rgba=[0.0, 0.0, 0.0, 0.0], pos=[0.0, 0.0117, 0.015]) def _add_collision_geoms(self): """Add collision geoms use by the QP velocity controller for avoidance.""" self._collision_geoms = models_utils.attach_collision_geoms( self.mjcf_model, _COLLISION_GEOMS_DICT) def _color_pads(self) -> None: """Define the color for the gripper pads.""" for geom_name in _PAD_GEOM_NAMES: geom = self._mjcf_root.find('geom', geom_name) geom.rgba = _PAD_COLOR def _define_integrated_velocity_actuator(self, gainprm: Tuple[float, float, float], biasprm: Tuple[float, float, float]): """Define integrated velocity actuator.""" self._finger_actuator.ctrlrange = (-255.0, 255.0) self._finger_actuator.dyntype = 'integrator' self._finger_actuator.gainprm = gainprm self._finger_actuator.biasprm = biasprm def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState): """Function called at the beginning of every episode.""" del random_state # Unused. # Apply gravity compensation body_elements = self.mjcf_model.find_all('body') gravity = np.hstack([physics.model.opt.gravity, [0, 0, 0]]) physics_bodies = physics.bind(body_elements) if physics_bodies is None: raise ValueError('Calling physics.bind with bodies returns None.') physics_bodies.xfrc_applied[:] = -gravity * physics_bodies.mass[..., None] @property def joints(self) -> List[types.MjcfElement]: """List of joint elements belonging to the hand.""" if not self._joints: raise AttributeError('Robot joints is None.') return self._joints @property def actuators(self) -> List[types.MjcfElement]: """List of actuator elements belonging to the hand.""" if not self._finger_actuator: raise AttributeError('Robot actuators is None.') return [self._finger_actuator] @property def mjcf_model(self) -> mjcf.RootElement: """Returns the `mjcf.RootElement` object corresponding to the robot hand.""" if not self._mjcf_root: raise AttributeError('Robot mjcf_root is None.') return self._mjcf_root @property def name(self) -> str: """Name of the robot hand.""" return self.mjcf_model.model @property def tool_center_point(self) -> types.MjcfElement: """Tool center point site of the hand.""" return self._tool_center_point @property def joint_sensor(self) -> types.MjcfElement: """Joint sensor of the hand.""" return self._joint_sensor def after_substep(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: """A callback which is executed after a simulation step. This function is necessary when using the integrated velocity mujoco actuator. Mujoco will limit the incoming velocity but the hidden state of the integrated velocity actuators must be clipped to the actuation range. Args: physics: An instance of `mjcf.Physics`. random_state: An instance of `np.random.RandomState`. """ del random_state # Unused. # Clip the actuator.act with the actuator limits. physics_actuators = models_utils.binding(physics, self.actuators) physics_actuators.act[:] = np.clip( physics_actuators.act[:], a_min=0., a_max=255.) def convert_position(self, position, **unused_kwargs): """Converts raw joint position to sensor output.""" normed_pos = (position - self._joint_offset) / self._joint_scale # [0, 1] rescaled_pos = np.clip(normed_pos * _POS_SCALE, 0, _POS_SCALE) return np.round(rescaled_pos) def grasp_sensor_callable(self, physics) -> int: """Simulate the robot's gOBJ object detection flag.""" # No grasp when no collision. collision_geoms_colliding = _are_all_collision_geoms_colliding( physics, self.mjcf_model) if not collision_geoms_colliding: return consts.NO_GRASP # No grasp when no velocity ctrl command. desired_vel = physics.bind(self.actuators[0]).ctrl if np.abs(desired_vel) < _VELOCITY_CTRL_TOL: return consts.NO_GRASP # If ctrl is positive, the gripper is closing. Hence, inward grasp. if desired_vel > 0: return consts.INWARD_GRASP else: return consts.OUTWARD_GRASP @property def collision_geom_group(self): collision_geom_group = [ geom.full_identifier for geom in self._collision_geoms ] return collision_geom_group def _is_geom_in_collision(physics: mjcf.Physics, geom_name: str, geom_exceptions: Optional[List[str]] = None) -> bool: """Returns true if a geom is in collision in the physics object.""" for contact in physics.data.contact: geom1_name = physics.model.id2name(contact.geom1, 'geom') geom2_name = physics.model.id2name(contact.geom2, 'geom') if contact.dist > 1e-8: continue if (geom1_name == geom_name and geom2_name not in geom_exceptions) or ( geom2_name == geom_name and geom1_name not in geom_exceptions): return True return False def _are_all_collision_geoms_colliding(physics: mjcf.Physics, mjcf_root: mjcf.RootElement) -> bool: """Returns true if the collision geoms in the model are colliding.""" collision_geoms = [ mjcf_root.find('geom', name).full_identifier for name in _PAD_GEOM_NAMES ] return all([ _is_geom_in_collision(physics, geom, collision_geoms) for geom in collision_geoms ])
dm_robotics-main
py/moma/models/end_effectors/robot_hands/robotiq_2f85.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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_robotics.moma.models.end_effectors.wrist_sensors.robotiq_fts300.""" from absl.testing import absltest from absl.testing import parameterized from dm_control import mjcf from dm_robotics.moma.models.end_effectors.wrist_sensors import robotiq_fts300 class RobotiqFTS300Test(parameterized.TestCase): """Tests for the Robotiq FTS300 force/torque sensor.""" def test_load_sensor(self): """Check RobotiqFTS300 can be instantiated and physics step() executed.""" entity = robotiq_fts300.RobotiqFTS300() physics = mjcf.Physics.from_mjcf_model(entity.mjcf_model) physics.step() def test_zero_gravity_readings(self): """Measure the force applied to F/T sensor when gravity is disabled.""" entity = robotiq_fts300.RobotiqFTS300() physics = mjcf.Physics.from_mjcf_model(entity.mjcf_model) with physics.model.disable("gravity"): physics.forward() force_z = physics.bind(entity.force_sensor).sensordata[2] self.assertEqual(force_z, 0.) if __name__ == "__main__": absltest.main()
dm_robotics-main
py/moma/models/end_effectors/wrist_sensors/robotiq_fts300_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Defines Robotiq FTS300 constants.""" import os # pylint: disable=unused-import # pylint: disable=line-too-long # XML path of the Robotiq FTS300. XML_PATH = os.path.join(os.path.dirname(__file__), 'robotiq_fts300.xml') # end effectors # pylint: enable=line-too-long
dm_robotics-main
py/moma/models/end_effectors/wrist_sensors/robotiq_fts300_constants.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing Robotiq FTS300 Sensor.""" import collections from dm_control import composer from dm_control import mjcf from dm_robotics.moma.models import types from dm_robotics.moma.models import utils as models_utils from dm_robotics.moma.models.end_effectors.wrist_sensors import robotiq_fts300_constants as consts import numpy as np _ROBOTIQ_ASSETS_PATH = 'robots/robotiq/assets' _ATTACHMENT_SITE = 'ft_sensor_attachment_site' _FRAME_SITE = 'ft_sensor_frame_site' _FORCE_SENSOR_NAME = 'ft_sensor_force' _TORQUE_SENSOR_NAME = 'ft_sensor_torque' _SensorParams = collections.namedtuple( 'SensorParams', ['force_std', 'torque_std', 'max_abs_force', 'max_abs_torque']) _COLLISION_KWARGS = [{ 'name': 'base_mount_CollisionGeom', 'type': 'sphere', 'pos': '0 0.0 0.015', 'size': '0.05' }] # Dictionary mapping body names to a list of their collision geoms _COLLISION_GEOMS_DICT = { 'base_mount': _COLLISION_KWARGS, } class RobotiqFTS300(composer.Entity): """A class representing Robotiq FTS300 force/torque sensor.""" _mjcf_root: mjcf.RootElement def _build( self, name: str = 'robotiq_fts300', ) -> None: """Initializes RobotiqFTS300. Args: name: The name of this sensor. Used as a prefix in the MJCF name attributes. """ self._mjcf_root = mjcf.from_path(consts.XML_PATH) self._mjcf_root.model = name self._attachment_site = self._mjcf_root.find('site', _ATTACHMENT_SITE) self._sensor_frame_site = self._mjcf_root.find('site', _FRAME_SITE) self._force_sensor = self._mjcf_root.find('sensor', _FORCE_SENSOR_NAME) self._torque_sensor = self._mjcf_root.find('sensor', _TORQUE_SENSOR_NAME) self._add_collision_geoms() def _add_collision_geoms(self): """Add collision geoms.""" self._collision_geoms = models_utils.attach_collision_geoms( self.mjcf_model, _COLLISION_GEOMS_DICT) def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState): """Function called at the beginning of every episode.""" del random_state # Unused. # Apply gravity compensation body_elements = self.mjcf_model.find_all('body') gravity = np.hstack([physics.model.opt.gravity, [0, 0, 0]]) physics_bodies = physics.bind(body_elements) if physics_bodies is None: raise ValueError('Calling physics.bind with bodies returns None.') physics_bodies.xfrc_applied[:] = -gravity * physics_bodies.mass[..., None] @property def force_sensor(self) -> types.MjcfElement: return self._force_sensor @property def torque_sensor(self) -> types.MjcfElement: return self._torque_sensor @property def mjcf_model(self) -> mjcf.RootElement: return self._mjcf_root @property def attachment_site(self) -> types.MjcfElement: return self._attachment_site @property def frame_site(self) -> types.MjcfElement: return self._sensor_frame_site @property def sensor_params(self): """`_SensorParams` namedtuple specifying noise and clipping parameters.""" return _SensorParams( # The noise values (zero-mean standard deviation) below were extracted # from the manufacturer's datasheet. Whilst torque drift is non- # significant as per the manual, force drift (+/-3N over 24h) is not # currently modelled. force_std=(1.2, 1.2, 0.5), torque_std=(0.02, 0.02, 0.12), # The absolute force/torque range values below were also extracted from # the manufacturer's datasheet. max_abs_force=300., max_abs_torque=30.) @property def collision_geom_group(self): collision_geom_group = [ geom.full_identifier for geom in self._collision_geoms ] return collision_geom_group
dm_robotics-main
py/moma/models/end_effectors/wrist_sensors/robotiq_fts300.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """MOMA Composer Robot Arm.""" import abc from typing import List from dm_control import composer from dm_control import mjcf from dm_robotics.moma.models import types import numpy as np class RobotArm(abc.ABC, composer.Entity): """MOMA composer robot arm base class.""" @abc.abstractmethod def _build(self): """Entity initialization method to be overridden by subclasses.""" pass @property @abc.abstractmethod def joints(self) -> List[types.MjcfElement]: """List of joint elements belonging to the arm.""" pass @property @abc.abstractmethod def actuators(self) -> List[types.MjcfElement]: """List of actuator elements belonging to the arm.""" pass @property @abc.abstractmethod def mjcf_model(self) -> mjcf.RootElement: """Returns the `mjcf.RootElement` object corresponding to this robot arm.""" pass @property @abc.abstractmethod def name(self) -> str: """Name of the robot arm.""" pass @property @abc.abstractmethod def wrist_site(self) -> types.MjcfElement: """Get the MuJoCo site of the wrist. Returns: MuJoCo site """ pass @property def attachment_site(self): """Make the wrist site the default attachment site for mjcf elements.""" return self.wrist_site @abc.abstractmethod def set_joint_angles(self, physics: mjcf.Physics, joint_angles: np.ndarray) -> None: """Sets the joints of the robot to a given configuration.""" pass
dm_robotics-main
py/moma/models/robots/robot_arms/robot_arm.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Defines Sawyer robot arm constants.""" import enum import os # Available actuation methods available for the Sawyer. # In integrated velocity, the joint actuators receive a velocity that is # integrated and a position controller is used to maintain the integrated # joint configuration. class Actuation(enum.Enum): INTEGRATED_VELOCITY = 0 # Number of degrees of freedom of the Sawyer robot arm. NUM_DOFS = 7 # Joint names of Sawyer robot (without any namespacing). These names are defined # by the Sawyer controller and are immutable. JOINT_NAMES = ('right_j0', 'right_j1', 'right_j2', 'right_j3', 'right_j4', 'right_j5', 'right_j6') WRIST_SITE_NAME = 'wrist_site' # Effort limits of the Sawyer robot arm in Nm. EFFORT_LIMITS = { 'min': (-80, -80, -40, -40, -9, -9, -9), 'max': (80, 80, 40, 40, 9, 9, 9), } JOINT_LIMITS = { 'min': (-3.0503, -3.8095, -3.0426, -3.0439, -2.9761, -2.9761, -4.7124), 'max': (3.0503, 2.2736, 3.0426, 3.0439, 2.9761, 2.9761, 4.7124), } VELOCITY_LIMITS = { 'min': (-1.74, -1.328, -1.957, -1.957, -3.485, -3.485, -4.545), 'max': (1.74, 1.328, 1.957, 1.957, 3.485, 3.485, 4.545), } # Quaternion to align the attachment site with real ROTATION_QUATERNION_MINUS_90DEG_AROUND_Z = (0.70711, 0, 0, 0.70711) # Actuation limits of the Sawyer robot arm. ACTUATION_LIMITS = { Actuation.INTEGRATED_VELOCITY: VELOCITY_LIMITS } # pylint: disable=line-too-long _RETHINK_ASSETS_PATH = (os.path.join(os.path.dirname(__file__), '..', '..', 'vendor', 'rethink', 'sawyer_description', 'mjcf')) # pylint: enable=line-too-long SAWYER_XML = os.path.join(_RETHINK_ASSETS_PATH, 'sawyer.xml') SAWYER_PEDESTAL_XML = os.path.join(_RETHINK_ASSETS_PATH, 'sawyer_pedestal.xml')
dm_robotics-main
py/moma/models/robots/robot_arms/sawyer_constants.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 sawyer.Sawyer class.""" from absl.testing import absltest from absl.testing import parameterized from dm_control import composer from dm_control import mjcf from dm_robotics.moma.models import types from dm_robotics.moma.models.robots.robot_arms import sawyer from dm_robotics.moma.models.robots.robot_arms import sawyer_constants as consts import numpy as np _JOINT_ANGLES = np.array(consts.NUM_DOFS * [np.pi]) @parameterized.named_parameters( {'testcase_name': 'Integrated_velocity_with_pedestal', 'actuation': consts.Actuation.INTEGRATED_VELOCITY, 'with_pedestal': True}, {'testcase_name': 'Integrated_velocity_without_pedestal', 'actuation': consts.Actuation.INTEGRATED_VELOCITY, 'with_pedestal': False}, ) class SawyerTest(parameterized.TestCase): def test_physics_step(self, actuation, with_pedestal): robot = sawyer.Sawyer(actuation=actuation, with_pedestal=with_pedestal) physics = mjcf.Physics.from_mjcf_model(robot.mjcf_model) physics.step() def test_initialize_episode(self, actuation, with_pedestal): robot = sawyer.Sawyer(actuation=actuation, with_pedestal=with_pedestal) physics = mjcf.Physics.from_mjcf_model(robot.mjcf_model) robot.initialize_episode(physics, np.random.RandomState(3)) def test_joints(self, actuation, with_pedestal): robot = sawyer.Sawyer(actuation=actuation, with_pedestal=with_pedestal) self.assertLen(robot.joints, consts.NUM_DOFS) for joint in robot.joints: self.assertEqual(joint.tag, 'joint') def test_actuators(self, actuation, with_pedestal): robot = sawyer.Sawyer(actuation=actuation, with_pedestal=with_pedestal) self.assertLen(robot.actuators, consts.NUM_DOFS) for actuator in robot.actuators: if actuation == consts.Actuation.INTEGRATED_VELOCITY: self.assertEqual(actuator.tag, 'general') def test_mjcf_model(self, actuation, with_pedestal): robot = sawyer.Sawyer(actuation=actuation, with_pedestal=with_pedestal) self.assertIsInstance(robot.mjcf_model, mjcf.RootElement) def test_wrist_site(self, actuation, with_pedestal): robot = sawyer.Sawyer(actuation=actuation, with_pedestal=with_pedestal) self.assertIsInstance(robot.wrist_site, types.MjcfElement) self.assertEqual(robot.wrist_site.tag, 'site') def test_joint_torque_sensors(self, actuation, with_pedestal): robot = sawyer.Sawyer(actuation=actuation, with_pedestal=with_pedestal) self.assertLen(robot.joint_torque_sensors, 7) for sensor in robot.joint_torque_sensors: self.assertEqual(sensor.tag, 'torque') def test_set_joint_angles(self, actuation, with_pedestal): robot = sawyer.Sawyer(actuation=actuation, with_pedestal=with_pedestal) physics = mjcf.Physics.from_mjcf_model(robot.mjcf_model) robot.set_joint_angles(physics, _JOINT_ANGLES) physics_joints_qpos = physics.bind(robot.joints).qpos[:] np.testing.assert_array_equal(physics_joints_qpos, _JOINT_ANGLES) if actuation == consts.Actuation.INTEGRATED_VELOCITY: physics_actuator_act = physics.bind(robot.actuators).act[:] np.testing.assert_array_equal(physics_actuator_act, physics_joints_qpos) def test_after_substep(self, actuation, with_pedestal): robot1 = sawyer.Sawyer(actuation=actuation, with_pedestal=with_pedestal) robot2 = sawyer.Sawyer(actuation=actuation, with_pedestal=with_pedestal) arena = composer.Arena() arena.attach(robot1) frame = arena.attach(robot2) frame.pos = (1, 0, 0) physics = mjcf.Physics.from_mjcf_model(arena.mjcf_model) act_limits = consts.JOINT_LIMITS actuators1 = physics.bind(robot1.actuators) actuators2 = physics.bind(robot2.actuators) invalid_range_values = [10., 10., 10., 10., 10., 10., 10.] actuators1.act = invalid_range_values valid_range_values = [3., 2., 0., 1.7, -1.0, 0.1, -3.2] actuators2.act = valid_range_values robot1.after_substep(physics, None) robot2.after_substep(physics, None) # For robot1, actuator state should be clipped. np.testing.assert_array_equal(actuators1.act, act_limits['max']) # Whilst for robot2, actuator state should not have changed. np.testing.assert_array_equal(actuators2.act, valid_range_values) def test_collision_geom_group(self, actuation, with_pedestal): robot = sawyer.Sawyer(actuation=actuation, with_pedestal=with_pedestal) self.assertNotEmpty(robot.collision_geom_group) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/models/robots/robot_arms/sawyer_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sawyer robot arm.""" import dataclasses import re from typing import List, Tuple from dm_control import mjcf from dm_robotics.moma.models import types from dm_robotics.moma.models import utils as models_utils from dm_robotics.moma.models.robots.robot_arms import robot_arm from dm_robotics.moma.models.robots.robot_arms import sawyer_constants as consts import numpy as np @dataclasses.dataclass(frozen=True) class _ActuatorParams: # Gain parameters for MuJoCo actuator. gainprm: Tuple[float] # Bias parameters for MuJoCo actuator. biasprm: Tuple[float, float, float] _SAWYER_ACTUATOR_PARAMS = { consts.Actuation.INTEGRATED_VELOCITY: { 'large_joint': _ActuatorParams((500.0,), (0.0, -500.0, -50.0)), 'medium_joint': _ActuatorParams((500.0,), (0.0, -500.0, -50.0)), 'small_joint': _ActuatorParams((500.0,), (0.0, -500.0, -50.0)), } } # The size of each sawyer joint, from the base (j0) to the wrist (j6). _JOINT_SIZES = ('large_joint', 'large_joint', 'medium_joint', 'medium_joint', 'small_joint', 'small_joint', 'small_joint') _INTEGRATED_VELOCITY_DEFAULT_DCLASS = { 'large_joint': { 'joint': { 'frictionloss': 0.3, 'armature': 1, 'damping': 0.1, } }, 'medium_joint': { 'joint': { 'frictionloss': 0.3, 'armature': 1, 'damping': 0.1, } }, 'small_joint': { 'joint': { 'frictionloss': 0.1, 'armature': 1, 'damping': 0.1, } }, } _ARM_BASE_LINK_COLLISION_KWARGS = [{ 'name': 'arm_base_link_CollisionGeom', 'type': 'cylinder', 'fromto': '0 0 -0.005 0 0 0.08', 'size': '0.11' }] _L0_COLLISION_KWARGS = [{ 'name': 'l0_CollisionGeom_1', 'type': 'capsule', 'fromto': '0 0 0.02 0 0 0.25', 'size': '0.08', }, { 'name': 'l0_CollisionGeom_2', 'type': 'capsule', 'fromto': '0.08 -0.01 0.23 0.08 0.04 0.23', 'size': '0.09', }, { 'name': 'l0_CollisionGeom_3', 'type': 'capsule', 'fromto': '0.03 -0.02 0.13 0.03 -0.02 0.18', 'size': '0.07', }] _HEAD_COLLISION_KWARGS = [{ 'name': 'head_CollisionGeom_1', 'type': 'capsule', 'fromto': '0 0 0.02 0 0 0.21', 'size': '0.05', }, { 'name': 'head_CollisionGeom_2', 'type': 'box', 'pos': '0.02 0 0.11', 'size': '0.02 0.13 0.09', }] _L1_COLLISION_KWARGS = [{ 'name': 'l1_CollisionGeom_1', 'type': 'capsule', 'fromto': '0 0 0.03 0 0 0.13', 'size': '0.074', }, { 'name': 'l1_CollisionGeom_2', 'type': 'capsule', 'fromto': '0 -0.1 0.13 0 -0.065 0.13', 'size': '0.075', }] _L2_COLLISION_KWARGS = [{ 'name': 'l2_CollisionGeom', 'type': 'capsule', 'fromto': '0 0 0.02 0 0 .26', 'size': '0.07', }] _L3_COLLISION_KWARGS = [{ 'name': 'l3_CollisionGeom_1', 'type': 'capsule', 'fromto': '0 0 -0.14 0 0 -0.02', 'size': '0.06', }, { 'name': 'l3_CollisionGeom_2', 'type': 'capsule', 'fromto': '0 -0.1 -0.12 0 -0.05 -0.12', 'size': '0.06', }] _L4_COLLISION_KWARGS = [{ 'name': 'l4_CollisionGeom', 'type': 'capsule', 'fromto': '0 0 0.03 0 0 .28', 'size': '0.06', }] _L5_COLLISION_KWARGS = [{ 'name': 'l5_CollisionGeom_1', 'type': 'capsule', 'fromto': '0 0 0.04 0 0 0.08', 'size': '0.07', }, { 'name': 'l5_CollisionGeom_2', 'type': 'capsule', 'fromto': '0 0 0.1 0 -0.05 0.1', 'size': '0.07', }] _L6_COLLISION_KWARGS = [{ 'name': 'l6_CollisionGeom', 'type': 'capsule', 'fromto': '0 -0.005 -0.002 0 0.035 -0.002', 'size': '0.05', }] # Dictionary mapping body names to a list of their collision geoms _COLLISION_GEOMS_DICT = { 'arm_base_link': _ARM_BASE_LINK_COLLISION_KWARGS, 'l0': _L0_COLLISION_KWARGS, 'head': _HEAD_COLLISION_KWARGS, 'l1': _L1_COLLISION_KWARGS, 'l2': _L2_COLLISION_KWARGS, 'l3': _L3_COLLISION_KWARGS, 'l4': _L4_COLLISION_KWARGS, 'l5': _L5_COLLISION_KWARGS, 'l6': _L6_COLLISION_KWARGS, } class Sawyer(robot_arm.RobotArm): """A class representing a Sawyer robot arm.""" # Define member variables that are created in the _build function. This is to # comply with pytype correctly. _joints: List[types.MjcfElement] _actuators: List[types.MjcfElement] _mjcf_root: mjcf.RootElement _actuation: consts.Actuation _joint_torque_sensors: List[types.MjcfElement] _sawyer_root: mjcf.RootElement def _build( self, name: str = 'sawyer', actuation: consts.Actuation = consts.Actuation.INTEGRATED_VELOCITY, with_pedestal: bool = False, use_rotated_gripper: bool = True, ) -> None: """Initializes Sawyer. Args: name: The name of this robot. Used as a prefix in the MJCF name attributes. actuation: Instance of `sawyer_constants.Actuation` specifying which actuation mode to use. with_pedestal: If true, mount the sawyer robot on its pedestal. use_rotated_gripper: If True, mounts the gripper in a rotated position to match the real placement of the gripper on the physical Sawyer. Only set to False for backwards compatibility. """ self._sawyer_root = mjcf.from_path(consts.SAWYER_XML) if with_pedestal: pedestal_root = mjcf.from_path(consts.SAWYER_PEDESTAL_XML) pedestal_root.find('site', 'sawyer_attachment').attach(self._sawyer_root) self._mjcf_root = pedestal_root else: self._mjcf_root = self._sawyer_root self._actuation = actuation self._mjcf_root.model = name self._add_mjcf_elements(use_rotated_gripper) self._add_actuators() self._add_collision_geoms() @property def collision_geom_group(self): collision_geom_group = [ geom.full_identifier for geom in self._collision_geoms ] return collision_geom_group @property def collision_geom_group_basket_v4(self): """Collision geom group to use with the v4 RGB basket. The v4 basket is higher than the previous ones. This resulted in the collisions geoms of the robot being in collision with the basket collision geoms before the robot started moving. This made moving the robot impossible as the QP velocity controller was trying to avoid collisions that were already there. This geom group solves this problem. This group should be used with the collision geoms of the basket struct. Note that the default `collision_geom_group` should still be used with the collision group of the cameras of the basket. """ # We ignore the collision geoms located at the base of the robot ignored_geoms = [geom['name'] for geom in _L0_COLLISION_KWARGS] ignored_geoms.append(_L1_COLLISION_KWARGS[0]['name']) collision_geom_group = [] for geom in self._collision_geoms: if geom.name not in ignored_geoms: collision_geom_group.append(geom.full_identifier) return collision_geom_group def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState): """Function called at the beginning of every episode.""" del random_state # Unused. # Apply gravity compensation body_elements = self.mjcf_model.find_all('body') gravity = np.hstack([physics.model.opt.gravity, [0, 0, 0]]) physics_bodies = physics.bind(body_elements) if physics_bodies is None: raise ValueError('Calling physics.bind with bodies returns None.') physics_bodies.xfrc_applied[:] = -gravity * physics_bodies.mass[..., None] @property def joints(self) -> List[types.MjcfElement]: """List of joint elements belonging to the arm.""" if not self._joints: raise AttributeError('Robot joints is None.') return self._joints @property def actuators(self) -> List[types.MjcfElement]: """List of actuator elements belonging to the arm.""" if not self._actuators: raise AttributeError('Robot actuators is None.') return self._actuators @property def mjcf_model(self) -> mjcf.RootElement: """Returns the `mjcf.RootElement` object corresponding to this robot arm.""" if not self._mjcf_root: raise AttributeError('Robot mjcf_root is None.') return self._mjcf_root @property def name(self) -> str: """Name of the robot arm.""" return self.mjcf_model.model @property def wrist_site(self) -> types.MjcfElement: """Get the MuJoCo site of the wrist. Returns: MuJoCo site """ return self._wrist_site @property def joint_torque_sensors(self) -> List[types.MjcfElement]: """Get MuJoCo sensor of the joint torques.""" return self._joint_torque_sensors @property def attachment_site(self): """Override wrist site for attachment, but NOT the one for observations.""" return self._attachment_site def set_joint_angles(self, physics: mjcf.Physics, joint_angles: np.ndarray) -> None: """Sets the joints of the robot to a given configuration. This function allows to change the joint configuration of the sawyer arm and sets the controller to prevent the impedance controller from moving back to the previous configuration. Args: physics: A `mujoco.Physics` instance. joint_angles: The desired joints configuration for the robot arm. """ physics_joints = models_utils.binding(physics, self._joints) physics_actuators = models_utils.binding(physics, self._actuators) physics_joints.qpos[:] = joint_angles physics_joints.qvel[:] = np.zeros_like(joint_angles) if self._actuation == consts.Actuation.INTEGRATED_VELOCITY: physics_actuators.act[:] = physics_joints.qpos[:] # After setting the joints we need to synchronize the physics state. physics.forward() def after_substep(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: """A callback which is executed after a simulation step. This function is necessary when using the integrated velocity mujoco actuator. Mujoco will limit the incoming velocity but the hidden state of the integrated velocity actuators must be clipped to the actuation range. Args: physics: An instance of `mjcf.Physics`. random_state: An instance of `np.random.RandomState`. """ del random_state # Unused. # Clip the actuator.act with the actuator limits. if self._actuation == consts.Actuation.INTEGRATED_VELOCITY: physics_actuators = models_utils.binding(physics, self._actuators) physics_actuators.act[:] = np.clip( physics_actuators.act[:], a_min=consts.JOINT_LIMITS['min'], a_max=consts.JOINT_LIMITS['max']) def _add_mjcf_elements(self, use_rotated_gripper: bool): """Defines the arms MJCF joints and sensors.""" self._joints = [ self._sawyer_root.find('joint', j) for j in consts.JOINT_NAMES ] self._joint_torque_sensors = [ sensor for sensor in self._sawyer_root.find_all('sensor') if sensor.tag == 'torque' and re.match(r'^j\d_site$', sensor.site.name) ] self._wrist_site = self._sawyer_root.find('site', consts.WRIST_SITE_NAME) if use_rotated_gripper: # Change the attachment site so it is aligned with the real sawyer. This # will allow having the gripper oriented in the same way in both sim and # real. hand_body = self._sawyer_root.find('body', 'hand') hand_body.add( 'site', type='sphere', name='real_aligned_tcp', pos=(0, 0, 0), quat=consts.ROTATION_QUATERNION_MINUS_90DEG_AROUND_Z) self._attachment_site = self._sawyer_root.find( 'site', 'real_aligned_tcp') else: self._attachment_site = self._wrist_site def _add_collision_geoms(self): """Add collision geoms.""" # Note that the MJCF model being passed is sawyer_root. self._collision_geoms = models_utils.attach_collision_geoms( self._sawyer_root, _COLLISION_GEOMS_DICT) def _add_actuators(self): """Adds the Mujoco actuators to the robot arm.""" if self._actuation not in consts.Actuation: raise ValueError((f'Actuation {self._actuation} is not a valid actuation.' 'Please specify one of ' f'{list(consts.Actuation.__members__.values())}')) if self._actuation == consts.Actuation.INTEGRATED_VELOCITY: self._add_integrated_velocity_actuators() def _add_integrated_velocity_actuators(self) -> None: """Adds integrated velocity actuators to the mjcf model. This function adds integrated velocity actuators and default class attributes to the mjcf model according to the values in `sawyer_constants`, `_SAWYER_ACTUATOR_PARAMS` and `_INTEGRATED_VELOCITY_DEFAULT_DCLASS`. `self._actuators` is created to contain the list of actuators created. """ # Add default class attributes. for name, defaults in _INTEGRATED_VELOCITY_DEFAULT_DCLASS.items(): default_dclass = self._sawyer_root.default.add('default', dclass=name) for tag, attributes in defaults.items(): element = getattr(default_dclass, tag) for attr_name, attr_val in attributes.items(): setattr(element, attr_name, attr_val) # Construct list of ctrlrange tuples from act limits and actuation mode. ctrl_ranges = list( zip(consts.ACTUATION_LIMITS[self._actuation]['min'], consts.ACTUATION_LIMITS[self._actuation]['max'])) # Construct list of forcerange tuples from effort limits. force_ranges = list(zip(consts.EFFORT_LIMITS['min'], consts.EFFORT_LIMITS['max'])) def add_actuator(i: int) -> types.MjcfElement: """Add an actuator.""" params = _SAWYER_ACTUATOR_PARAMS[self._actuation][_JOINT_SIZES[i]] actuator = self._sawyer_root.actuator.add( 'general', name=f'j{i}', ctrllimited=True, forcelimited=True, ctrlrange=ctrl_ranges[i], forcerange=force_ranges[i], dyntype='integrator', biastype='affine', gainprm=params.gainprm, biasprm=params.biasprm) actuator.joint = self._joints[i] return actuator self._actuators = [add_actuator(i) for i in range(consts.NUM_DOFS)]
dm_robotics-main
py/moma/models/robots/robot_arms/sawyer.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Effector for MuJoCo actuators.""" from typing import List, Optional, Sequence, Tuple from dm_control import mjcf # type: ignore from dm_env import specs from dm_robotics.agentflow import spec_utils from dm_robotics.moma import effector from dm_robotics.moma.models import types import numpy as np class MujocoEffector(effector.Effector): """A generic effector for multiple MuJoCo actuators.""" def __init__(self, actuators: Sequence[types.MjcfElement], prefix: str = '', action_range_override: Optional[List[Tuple[float, float]]] = None): self._actuators = actuators self._prefix = prefix self._action_range_override = action_range_override self._action_spec = None def action_spec(self, physics: mjcf.Physics) -> specs.BoundedArray: if self._action_spec is None: self._action_spec = create_action_spec(physics, self._actuators, self._prefix, self._action_range_override) return self._action_spec def set_control(self, physics: mjcf.Physics, command: np.ndarray) -> None: spec_utils.validate(self.action_spec(physics), command) physics.bind(self._actuators).ctrl = command @property def prefix(self) -> str: return self._prefix def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: pass def create_action_spec( physics: mjcf.Physics, actuators: Sequence[types.MjcfElement], prefix: str = '', action_range_override: Optional[List[Tuple[float, float]]] = None ) -> specs.BoundedArray: """Creates an action range for the given actuators. The control range (ctrlrange) of the actuators determines the action range unless `action_range_override` is supplied. The action range name is the tab-separated names of the actuators, each prefixed by `prefix` Args: physics: Used to get the ctrlrange of the actuators. actuators: The MuJoCo actuators get get an action spec for. prefix: A name prefix to prepend to each actuator name. action_range_override: Optional override (min, max) sequence to use instead of the actuator ctrlrange. Returns: An action spec for the actuators. """ num_actuators = len(actuators) actuator_names = [f'{prefix}{i}' for i in range(num_actuators)] if action_range_override is not None: action_min, action_max = _action_range_from_override( actuators, action_range_override) else: action_min, action_max = _action_range_from_actuators(physics, actuators) return specs.BoundedArray( shape=(num_actuators,), dtype=np.float32, minimum=action_min, maximum=action_max, name='\t'.join(actuator_names)) def _action_range_from_override( actuators: Sequence[types.MjcfElement], override_range: List[Tuple[float, float]]) -> Tuple[np.ndarray, np.ndarray]: """Returns the action range min, max using the values from override_range.""" num_actions = len(actuators) assert (len(override_range) == 1 or len(override_range) == num_actions) if len(override_range) == 1: range_min = np.array([override_range[0][0]] * num_actions, dtype=np.float32) range_max = np.array([override_range[0][1]] * num_actions, dtype=np.float32) else: range_min = np.array([r[0] for r in override_range], dtype=np.float32) range_max = np.array([r[1] for r in override_range], dtype=np.float32) return range_min, range_max def _action_range_from_actuators( physics: mjcf.Physics, actuators: Sequence[types.MjcfElement]) -> Tuple[np.ndarray, np.ndarray]: """Returns the action range min, max for the actuators.""" num_actions = len(actuators) control_range = physics.bind(actuators).ctrlrange is_limited = physics.bind(actuators).ctrllimited.astype(bool) minima = np.full(num_actions, fill_value=-np.inf, dtype=np.float32) maxima = np.full(num_actions, fill_value=np.inf, dtype=np.float32) minima[is_limited], maxima[is_limited] = control_range[is_limited].T return minima, maxima
dm_robotics-main
py/moma/effectors/mujoco_actuation.py
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test utilities for MoMa effectors.""" from dm_control import mjcf from dm_env import specs from dm_robotics.geometry import geometry from dm_robotics.moma import effector import numpy as np _MjcfElement = mjcf.element._ElementImpl # pylint: disable=protected-access # Joint positions that put the robot TCP pointing down somewhere in front of # the basket. SAFE_SAWYER_JOINTS_POS = np.array( [-0.0835859, -0.82730523, -0.24968541, 1.75960196, 0.27188317, 0.67231963, 1.26143456]) class SpyEffector(effector.Effector): """An effector that allows retrieving the most recent action.""" def __init__(self, dofs: int): self._previous_action = np.zeros(dofs) def initialize_episode(self, physics, random_state) -> None: pass def action_spec(self, physics) -> specs.BoundedArray: return specs.BoundedArray( self._previous_action.shape, self._previous_action.dtype, minimum=-1.0, maximum=1.0) def set_control(self, physics, command: np.ndarray) -> None: self._previous_action = command[:] @property def prefix(self) -> str: return 'spy' @property def previous_action(self) -> np.ndarray: return self._previous_action class SpyEffectorWithControlFrame(SpyEffector): """A spy effector with a control frame property.""" def __init__(self, element: _MjcfElement, dofs: int): self._control_frame = geometry.HybridPoseStamped( pose=None, frame=element, quaternion_override=geometry.PoseStamped(None, None)) super().__init__(dofs) @property def control_frame(self) -> geometry.Frame: return self._control_frame
dm_robotics-main
py/moma/effectors/test_utils.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Cartesian effector that controls linear XYZ and rotation around Z motions.""" import copy from typing import Callable, Optional, Sequence from dm_control import mjcf from dm_env import specs from dm_robotics.geometry import geometry from dm_robotics.geometry import mujoco_physics from dm_robotics.moma import effector from dm_robotics.moma.effectors import constrained_actions_effectors from dm_robotics.transformations import transformations import numpy as np _MjcfElement = mjcf.element._ElementImpl # pylint: disable=protected-access # Orientation corresponding to the endeffector pointing downwards. DOWNFACING_EE_QUAT_WXYZ = np.array([0.0, 0.0, 1.0, 0.0]) class _OrientationController(): """Proportional controller for maintaining the desired orientation.""" def __init__(self, rotation_gain: float, align_z_orientation: bool = False): """Constructor. Args: rotation_gain: Proportional gain used on the orientation error to compute the desired angular velocity. align_z_orientation: If true, the z rotation is constrained. If false, the z rotation is left as a DOF and will not be constrained. """ self._p = rotation_gain self._align_z = align_z_orientation def step( self, current_quat: np.ndarray, desired_quat: np.ndarray ) -> np.ndarray: """Computes angular velocity to orient with a target quat.""" error_quat = transformations.quat_diff_active( source_quat=current_quat, target_quat=desired_quat) if not self._align_z: # Ignore the z component of the error because the effector controls that. error_euler = transformations.quat_to_euler(error_quat) z_correction = transformations.euler_to_quat( np.array([0, 0, error_euler[2]])) # Compute a new target quat whose Z orientation is already aligned with # the current frame. new_desired_quat = transformations.quat_mul(desired_quat, z_correction) # Recompute the error with this new aligned target quat. error_quat = transformations.quat_diff_active( current_quat, new_desired_quat) # Normalize the error. error_quat = error_quat / np.linalg.norm(error_quat) return self._p * transformations.quat_to_axisangle(error_quat) class Cartesian4dVelocityEffector(effector.Effector): """Effector for XYZ translational vel and Z angular vel. The X and Y angular velocities are also controlled internally in order to maintain the desired XY orientation, but those components are not exposed via the action spec. Also, we can change the orientation that is maintained by the robot by changing the `target_alignement` parameter. By default the robot is facing downards. """ def __init__(self, effector_6d: effector.Effector, element: _MjcfElement, effector_prefix: str, control_frame: Optional[geometry.Frame] = None, rotation_gain: float = 0.8, target_alignment: np.ndarray = DOWNFACING_EE_QUAT_WXYZ): """Initializes a QP-based 4D Cartesian velocity effector. Args: effector_6d: Cartesian 6D velocity effector controlling the linear and angular velocities of `element`. The action spec of this effector should have a shape of 6 elements corresponding to the 6D velocity. The effector should have a property `control_frame` that returns the geometry.Frame in which the command should be expressed. element: the `mjcf.Element` being controlled. The 4D Cartesian velocity commands are expressed about the element's origin in the world orientation, unless overridden by `control_frame`. Only site elements are supported. effector_prefix: Prefix to the actuator names in the action spec. control_frame: `geometry.Frame` in which to interpet the Cartesian 4D velocity command. If `None`, assumes that the control command is expressed about the element's origin in the world orientation. Note that this is different than expressing the Cartesian 6D velocity about the element's own origin and orientation. Note that you will have to update the `target_alignment` quaternion if the frame does not have a downward z axis. rotation_gain: Gain applied to the rotational feedback control used to maintain a downward-facing orientation. A value too low of this parameter will result in the robot not being able to maintain the desired orientation. A value too high will lead to oscillations. target_alignment: Unit quat [w, i, j, k] denoting the desired alignment of the element's frame, represented in the world frame. Defaults to facing downwards. """ self._effector_6d = effector_6d self._element = element self._effector_prefix = effector_prefix self._target_quat = target_alignment self._orientation_ctrl = _OrientationController(rotation_gain) # The control frame is either provided by the user or defaults to the one # centered at the element with the world orientation. self._control_frame = control_frame or geometry.HybridPoseStamped( pose=None, frame=self._element, quaternion_override=geometry.PoseStamped(None, None)) # We use the target frame to compute a "stabilizing angular velocity" such # that the z axis of the target frame aligns with the z axis of the # element's frame. self._target_frame = geometry.HybridPoseStamped( pose=None, frame=self._element, quaternion_override=geometry.PoseStamped( pose=geometry.Pose(position=None, quaternion=target_alignment))) self._element_frame = geometry.PoseStamped(pose=None, frame=element) def after_compile(self, mjcf_model: mjcf.RootElement, physics: mjcf.Physics) -> None: self._effector_6d.after_compile(mjcf_model, physics) def initialize_episode(self, physics, random_state) -> None: self._effector_6d.initialize_episode( physics=physics, random_state=random_state) def action_spec(self, physics: mjcf.Physics) -> specs.BoundedArray: action_spec_6d = self._effector_6d.action_spec(physics=physics) # We ensure that the effector_6d is indeed 6d. if action_spec_6d.shape != (6,): raise ValueError('The effector passed to cartesian_4d_velocity_effector` ' 'should have an action spec of shape 6. Provided spec: ' f'{action_spec_6d.shape}') actuator_names = [(self.prefix + str(i)) for i in range(4)] return specs.BoundedArray( shape=(4,), dtype=action_spec_6d.dtype, minimum=action_spec_6d.minimum[[0, 1, 2, 5]], maximum=action_spec_6d.maximum[[0, 1, 2, 5]], name='\t'.join(actuator_names)) def set_control(self, physics: mjcf.Physics, command: np.ndarray) -> None: """Sets a 4 DoF Cartesian velocity command at the current timestep. Args: physics: The physics object with the updated environment state at the current timestep. command: Array of size 4 describing the desired Cartesian target vel [lin_x, lin_y, lin_z, rot_z] expressed in the control frame. """ if command.size != 4: raise ValueError('set_control: command must be an np.ndarray of size 4. ' f'Got {command.size}.') # Turn the input into a 6D velocity expressed in the control frame. twist = np.zeros(6) twist[0:3] = command[0:3] twist[5] = command[3] twist_stamped = geometry.TwistStamped(twist, self._control_frame) # We then project the velocity to the target frame. twist_target_frame = copy.copy(twist_stamped.to_frame( self._target_frame, physics=mujoco_physics.wrap(physics)).twist.full) # We compute the angular velocity that aligns the element's frame with # the target frame. stabilizing_vel = self._compute_stabilizing_ang_vel(physics) # We only use the x and y components of the stabilizing velocity and keep # the z rotation component of the command. twist_target_frame[3:5] = stabilizing_vel[0:2] twist_stamped_target_frame = geometry.TwistStamped( twist_target_frame, self._target_frame) # Transform the command to the frame expected by the underlying 6D effector. try: twist = twist_stamped_target_frame.to_frame( self._effector_6d.control_frame, # pytype: disable=attribute-error mujoco_physics.wrap(physics)).twist.full except AttributeError as error: raise AttributeError( 'The 6D effector does not have a `control_frame` attribute.' ) from error self._effector_6d.set_control(physics=physics, command=twist) @property def prefix(self) -> str: return self._effector_prefix @property def control_frame(self) -> geometry.Frame: return self._control_frame def _compute_stabilizing_ang_vel(self, physics: mjcf.Physics) -> np.ndarray: """Returns the angular velocity to orient element frame with target quat. The returned velocity is expressed in the target frame. Args: physics: An instance of physics. """ # Express the quaternion of both the element and the target in the target # frame. This ensures that the velocity returned by the orientation # controller will align the z axis of the element frame with the z axis of # the target frame. element_quat_target_frame = self._element_frame.to_frame( self._target_frame, mujoco_physics.wrap(physics)).pose.quaternion # The target quaternion is expressed in the target frame (the result is the # unit quaternion) target_quat_target_frame = self._target_frame.pose.quaternion return self._orientation_ctrl.step( current_quat=element_quat_target_frame, desired_quat=target_quat_target_frame) def limit_to_workspace( cartesian_effector: Cartesian4dVelocityEffector, element: _MjcfElement, min_workspace_limits: np.ndarray, max_workspace_limits: np.ndarray, wrist_joint: Optional[_MjcfElement] = None, wrist_limits: Optional[Sequence[float]] = None, reverse_wrist_range: bool = False, pose_getter: Optional[Callable[[mjcf.Physics], np.ndarray]] = None, ) -> effector.Effector: """Returns an effector that restricts the 4D actions to a workspace. If wrist limits are provided, this effector will also restrict the Z rotation action to those limits. Args: cartesian_effector: 4D cartesian effector. element: `mjcf.Element` that defines the Cartesian frame about which the Cartesian velocity is defined. min_workspace_limits: Lower bound of the Cartesian workspace. Must be 3D. max_workspace_limits: Upper bound of the Cartesian workspace. Must be 3D. wrist_joint: Optional wrist joint of the arm being controlled by the effectors. If provided along with `wrist_limits`, then the Z rotation component of the action will be zero'd out when the wrist is beyond the limits. You can typically get the wrist joint with `arm.joints[-1]`. wrist_limits: Optional 2D list/tuple (min wrist limit, max wrist limit). If provided along with `wrist_joint`, the Z rotation component of the action will be set to 0 when the wrist is beyond these limits. reverse_wrist_range: For some arms, a positive Z rotation action actually decreases the wrist joint position. For these arms, set this param to True. pose_getter: Optional function that returns the pose we want to constrain to the workspace. If `None`, defaults to the `xpos` of the `element`. """ if len(min_workspace_limits) != 3 or len(max_workspace_limits) != 3: raise ValueError('The workspace limits must be 3D (X, Y, Z). Provided ' f'min: {min_workspace_limits} and max: ' f'{max_workspace_limits}') pose_getter = pose_getter or (lambda phys: phys.bind(element).xpos) def state_getter(physics): pos = pose_getter(physics) if wrist_joint is not None and wrist_limits is not None: wrist_state = physics.bind(wrist_joint).qpos if reverse_wrist_range: wrist_state = -wrist_state else: # Even when no wrist limits are provided, we need to supply a 4D state to # match the action spec of the cartesian effector. wrist_state = [0.0] return np.concatenate((pos, wrist_state)) if wrist_joint is not None and wrist_limits is not None: if reverse_wrist_range: wrist_limits = [-wrist_limits[1], -wrist_limits[0]] min_limits = np.concatenate((min_workspace_limits, [wrist_limits[0]])) max_limits = np.concatenate((max_workspace_limits, [wrist_limits[1]])) else: # Provide unused wrist limits. They will be compared to a constant 0.0. min_limits = np.concatenate((min_workspace_limits, [-1.])) max_limits = np.concatenate((max_workspace_limits, [1.])) return constrained_actions_effectors.ConstrainedActionEffector( delegate=cartesian_effector, min_limits=min_limits, max_limits=max_limits, state_getter=state_getter)
dm_robotics-main
py/moma/effectors/cartesian_4d_velocity_effector.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Cartesian 6D velocity (linear and angular) effector.""" import dataclasses from typing import Callable, Optional, Sequence, Tuple from absl import logging from dm_control import mjcf from dm_control import mujoco from dm_control.mujoco.wrapper.mjbindings.enums import mjtJoint from dm_env import specs from dm_robotics.controllers import cartesian_6d_to_joint_velocity_mapper from dm_robotics.geometry import geometry from dm_robotics.geometry import mujoco_physics from dm_robotics.moma import effector from dm_robotics.moma.effectors import constrained_actions_effectors from dm_robotics.transformations import transformations as tr import numpy as np _MjcfElement = mjcf.element._ElementImpl # pylint: disable=protected-access _CartesianVelocityMapper = (cartesian_6d_to_joint_velocity_mapper.Mapper) _CartesianVelocityMapperParams = ( cartesian_6d_to_joint_velocity_mapper.Parameters) def _get_joint_ids(mj_model: mujoco.wrapper.MjModel, joints: Sequence[_MjcfElement]): """Returns the (unsorted) IDs for a list of joints. Joints must be 1 DoF.""" joint_ids = [] for joint in joints: joint_id = mj_model.name2id(joint.full_identifier, 'joint') joint_type = mj_model.jnt_type[joint_id] if not (joint_type == mjtJoint.mjJNT_HINGE or joint_type == mjtJoint.mjJNT_SLIDE): raise ValueError( 'Only 1 DoF joints are supported at the moment. Joint with name ' f'[{joint.full_identifier}] is not a 1 DoF joint.') joint_ids.append(joint_id) return joint_ids def _get_element_type(element: _MjcfElement): """Returns the MuJoCo enum corresponding to the element type.""" if element.tag == 'body': return mujoco.wrapper.mjbindings.enums.mjtObj.mjOBJ_BODY elif element.tag == 'geom': return mujoco.wrapper.mjbindings.enums.mjtObj.mjOBJ_GEOM elif element.tag == 'site': return mujoco.wrapper.mjbindings.enums.mjtObj.mjOBJ_SITE else: raise ValueError('Element must be a MuJoCo body, geom, or site. Got ' f'[{element.tag}].') def _scale_cartesian_6d_velocity(cartesian_6d_vel: np.ndarray, max_lin_vel: float, max_rot_vel: float): """Scales down the linear and angular magnitudes of the cartesian_6d_vel.""" lin_vel = cartesian_6d_vel[:3] rot_vel = cartesian_6d_vel[3:] lin_vel_norm = np.linalg.norm(lin_vel) rot_vel_norm = np.linalg.norm(rot_vel) if lin_vel_norm > max_lin_vel: lin_vel = lin_vel * max_lin_vel / lin_vel_norm if rot_vel_norm > max_rot_vel: rot_vel = rot_vel * max_rot_vel / rot_vel_norm return np.concatenate((lin_vel, rot_vel)) @dataclasses.dataclass class ModelParams: """Helper class for the model parameters of Cartesian6dVelocityEffector. Attributes: element: the `mjcf.Element` being controlled. Cartesian velocity commands are expressed about the element's origin in the world orientation, unless overridden by `control_frame`. Only elements with tags `body`, `geom`, and `site` are supported. joints: sequence of `mjcf.Element` joint entities of the joints being controlled. Every element must correspond to a valid MuJoCo joint in `mjcf_model`. Only 1 DoF joints are supported. Velocity limits, acceleration limits, and nullspace references must be in the same order as this sequence. control_frame: `geometry.Frame` in which to interpet the Cartesian 6D velocity command. If `None`, assumes that the control command is expressed about the element's origin in the world orientation. Note that this is different than expressing the Cartesian 6D velocity about the element's own origin and orientation. """ element: _MjcfElement joints: Sequence[_MjcfElement] control_frame: Optional[geometry.Frame] = None def set_qp_params(self, mjcf_model: mjcf.RootElement, qp_params: _CartesianVelocityMapperParams): xml_string = mjcf_model.to_xml_string() assets = mjcf_model.get_assets() qp_params.model = mujoco.wrapper.MjModel.from_xml_string( xml_string, assets=assets) qp_params.joint_ids = _get_joint_ids(qp_params.model, self.joints) qp_params.object_type = _get_element_type(self.element) qp_params.object_name = self.element.full_identifier @dataclasses.dataclass class ControlParams: """Helper class for the control parameters of Cartesian6dVelocityEffector. Attributes: control_timestep_seconds: expected amount of time that the computed joint velocities will be held by the effector. If unsure, higher values are more conservative. max_lin_vel: (optional) linear velocity maximum magnitude. max_rot_vel: (optional) rotational velocity maximum magnitude. enable_joint_position_limits: (optional) whether to enable active joint limit avoidance. Joint limits are deduced from the mjcf_model passed to the after_compose function. joint_position_limit_velocity_scale: (optional) value (0,1] that defines how fast each joint is allowed to move towards the joint limits in each iteration. Values lower than 1 are safer but may make the joints move slowly. 0.95 is usually enough since it is not affected by Jacobian linearization. Ignored if `enable_joint_position_limits` is false. minimum_distance_from_joint_position_limit: (optional) offset in meters (slide joints) or radians (hinge joints) to be added to the limits. Positive values decrease the range of motion, negative values increase it (i.e. negative values allow penetration). Ignored if `enable_joint_position_limits` is false. joint_velocity_limits: (optional) array of maximum allowed magnitudes of joint velocities for each joint, in m/s (slide joints) or rad/s (hinge joints). Must be ordered according to the `joints` parameter passed to the Cartesian6dVelocityEffector during construction. If not specified, joint velocity magnitudes will not be limited. Tune this if you see the robot trace non-linear Cartesian paths for a constant Cartesian velocity command. joint_acceleration_limits: (optional) array of maximum allowed magnitudes of joint acceleration for each controllable joint, in m/s^2 (slide joints) or rad/s^2 (hinge joints). Must be ordered according to the `joints` parameter passed to the Cartesian6dVelocityEffector during construction. If limits are specified, the user must ensure that the `physics` object used by the Cartesian6dVelocityEffector has accurate joint velocity information at every timestep. If None, the joint acceleration will not be limited. Note that collision avoidance and joint position limits, if enabled, take precedence over these limits. This means that the joint acceleration limits may be violated if it is necessary to come to an immediate full-stop in order to avoid collisions. regularization_weight: (optional) scalar regularizer for damping the Jacobian solver. nullspace_joint_position_reference: preferred joint positions, if unspecified then the mid point of the joint ranges is used. Must be ordered according to the `joints` parameter passed to the Cartesian6dVelocityEffector during construction. nullspace_gain: (optional) a gain (0, 1] for the secondary control objective. Scaled by a factor of `1/control_timestep_seconds` internally. Nullspace control will be disabled if the gain is None. max_cartesian_velocity_control_iterations: maximum number of iterations that the internal LSQP solver is allowed to spend on the Cartesian velocity optimization problem (first hierarchy). If the internal solver is unable to find a feasible solution to the first hierarchy (i.e. without nullspace) within the specified number of iterations, it will set the joint effector command to zero. max_nullspace_control_iterations: maximum number of iterations that the internal LSQP solver is allowed to spend on the nullspace optimization problem (second hierarchy). If the internal solver is unable to find a feasible solution to the second hierarchy within the specified number of iterations, it will set the joint effector command to the solution of the first hierarchy. Ignored if nullspace control is disabled. """ control_timestep_seconds: float max_lin_vel: float = 0.5 max_rot_vel: float = 0.5 enable_joint_position_limits: bool = True joint_position_limit_velocity_scale: float = 0.95 minimum_distance_from_joint_position_limit: float = 0.01 joint_velocity_limits: Optional[np.ndarray] = None joint_acceleration_limits: Optional[np.ndarray] = None regularization_weight: float = 0.01 nullspace_joint_position_reference: Optional[np.ndarray] = None nullspace_gain: Optional[float] = 0.025 max_cartesian_velocity_control_iterations: int = 300 max_nullspace_control_iterations: int = 300 def set_qp_params(self, qp_params: _CartesianVelocityMapperParams): """Configures `qp_params` with the ControlParams fields. Args: qp_params: QP parameters structure on which to set the parameters. The `model` and `joint_ids` must have been set. """ joint_argsort = np.argsort(qp_params.joint_ids) qp_params.integration_timestep = self.control_timestep_seconds # Set joint limit avoidance if enabled. if self.enable_joint_position_limits: qp_params.enable_joint_position_limits = True qp_params.joint_position_limit_velocity_scale = ( self.joint_position_limit_velocity_scale) qp_params.minimum_distance_from_joint_position_limit = ( self.minimum_distance_from_joint_position_limit) else: qp_params.enable_joint_position_limits = False # Set velocity limits, if enabled. # Note that we have to pass them in joint-ID ascending order to the mapper. if self.joint_velocity_limits is not None: qp_params.enable_joint_velocity_limits = True qp_params.joint_velocity_magnitude_limits = ( self.joint_velocity_limits[joint_argsort].tolist()) else: qp_params.enable_joint_velocity_limits = False # Set acceleration limits, if enabled. # Note that we have to pass them in joint-ID ascending order to the mapper. if self.joint_acceleration_limits is not None: qp_params.enable_joint_acceleration_limits = True qp_params.remove_joint_acceleration_limits_if_in_conflict = True qp_params.joint_acceleration_magnitude_limits = ( self.joint_acceleration_limits[joint_argsort].tolist()) else: qp_params.enable_joint_acceleration_limits = False # We always check the solution validity, and return a zero-vector if no # valid solution was found. qp_params.check_solution_validity = True # Set Cartesian control iterations. qp_params.max_cartesian_velocity_control_iterations = ( self.max_cartesian_velocity_control_iterations) # Set regularization weight to prevent high joint velocities near singular # configurations. qp_params.regularization_weight = self.regularization_weight # We always set our tolerance to 1.0e-3, as any value smaller than that is # unlikely to make a difference. qp_params.solution_tolerance = 1.0e-3 # Set nullspace control if gain is valid. If reference is None, set to # middle of joint range. If nullspace fails, we simply return the # minimum-norm least-squares solution to the Cartesian problem. # Note that the nullspace reference is not sorted in ascending order yet, as # the nullspace bias needs to be sorted after computing the velocities. if self.nullspace_gain is not None and self.nullspace_gain > 0.0: qp_params.enable_nullspace_control = True qp_params.return_error_on_nullspace_failure = False qp_params.nullspace_projection_slack = 1.0e-4 if self.nullspace_joint_position_reference is None: self.nullspace_joint_position_reference = 0.5 * np.sum( qp_params.model.jnt_range[qp_params.joint_ids, :], axis=1) qp_params.max_nullspace_control_iterations = ( self.max_nullspace_control_iterations) else: qp_params.enable_nullspace_control = False @dataclasses.dataclass class CollisionParams: """Helper class for the collision parameters of Cartesian6dVelocityEffector. Attributes: collision_pairs: (optional) a sequence of collision pairs in which to perform active collision avoidance. A collision pair is defined as a tuple of two geom groups. A geom group is a sequence of geom names. For each collision pair, the controller will attempt to avoid collisions between every geom in the first pair with every geom in the second pair. Self collision is achieved by adding a collision pair with the same geom group in both tuple positions. collision_avoidance_normal_velocity_scale: (optional) value between (0, 1] that defines how fast each geom is allowed to move towards another in each iteration. Values lower than 1 are safer but may make the geoms move slower towards each other. In the literature, a common starting value is 0.85. Ignored if collision_pairs is None. minimum_distance_from_collisions: (optional) defines the minimum distance that the solver will attempt to leave between any two geoms. A negative distance would allow the geoms to penetrate by the specified amount. collision_detection_distance: (optional) defines the distance between two geoms at which the active collision avoidance behaviour will start. A large value will cause collisions to be detected early, but may incur high computational costs. A negative value will cause the geoms to be detected only after they penetrate by the specified amount. """ collision_pairs: Optional[Sequence[Tuple[Sequence[str], Sequence[str]]]] = None collision_avoidance_normal_velocity_scale: float = 0.85 minimum_distance_from_collisions: float = 0.05 collision_detection_distance: float = 0.5 def set_qp_params(self, qp_params: _CartesianVelocityMapperParams): """Configures `qp_params` with the CollisionParams fields.""" if self.collision_pairs: qp_params.enable_collision_avoidance = True qp_params.collision_avoidance_normal_velocity_scale = ( self.collision_avoidance_normal_velocity_scale) qp_params.minimum_distance_from_collisions = ( self.minimum_distance_from_collisions) qp_params.collision_detection_distance = ( qp_params.collision_detection_distance) qp_params.collision_pairs = self.collision_pairs else: qp_params.enable_collision_avoidance = False class Cartesian6dVelocityEffector(effector.Effector): """A Cartesian 6D velocity effector interface for a robot arm.""" def __init__(self, robot_name: str, joint_velocity_effector: effector.Effector, model_params: ModelParams, control_params: ControlParams, collision_params: Optional[CollisionParams] = None, log_nullspace_failure_warnings: bool = False, use_adaptive_qp_step_size: bool = False): """Initializes a QP-based 6D Cartesian velocity effector. Args: robot_name: name of the robot the Cartesian effector controls. joint_velocity_effector: `Effector` on the joint velocities being controlled to achieve the target Cartesian velocity. This class takes ownership of this effector, i.e. it will call `initialize_episode` automatically. model_params: parameters that describe the object being controlled. control_params: parameters that describe how the element should be controlled. collision_params: parameters that describe the active collision avoidance behaviour, if any. log_nullspace_failure_warnings: if true, a warning will be logged if the internal LSQP solver is unable to solve the nullspace optimization problem (second hierarchy). Ignored if nullspace control is disabled. use_adaptive_qp_step_size: if true, the internal LSQP solver will use an adaptive step size when solving the resultant QP problem. Note that setting this to true can greatly speed up the computation time, but the solution will no longer be numerically deterministic. """ self._effector_prefix = f'{robot_name}_twist' self._joint_velocity_effector = joint_velocity_effector self._joints = model_params.joints self._model_params = model_params self._control_params = control_params self._collision_params = collision_params self._control_frame = model_params.control_frame self._log_nullspace_failure_warnings = log_nullspace_failure_warnings self._use_adaptive_step_size = use_adaptive_qp_step_size # These are created in after_compose, once the mjcf_model is finalized. self._qp_mapper = None self._qp_frame = None self._joints_argsort = None def after_compile(self, mjcf_model: mjcf.RootElement, physics: mjcf.Physics) -> None: self._joint_velocity_effector.after_compile(mjcf_model, physics) # Construct the QP-based mapper. qp_params = _CartesianVelocityMapperParams() self._model_params.set_qp_params(mjcf_model, qp_params) self._control_params.set_qp_params(qp_params) if self._collision_params: self._collision_params.set_qp_params(qp_params) qp_params.use_adaptive_step_size = self._use_adaptive_step_size qp_params.log_nullspace_failure_warnings = ( self._log_nullspace_failure_warnings) self._qp_mapper = _CartesianVelocityMapper(qp_params) # Array of indices that would sort the joints in ascending order. # This is necessary because the mapper's inputs and outputs are always in # joint-ID ascending order, but the effector control should be passed # in the same order as the joints. self._joints_argsort = np.argsort(qp_params.joint_ids) # The mapper always expects the Cartesian velocity target to be expressed in # the element's origin in the world's orientation. self._qp_frame = geometry.HybridPoseStamped( pose=None, frame=self._model_params.element, quaternion_override=geometry.PoseStamped(None, None)) def initialize_episode(self, physics, random_state) -> None: # Initialize the joint velocity effector. self._joint_velocity_effector.initialize_episode(physics, random_state) def action_spec(self, physics: mjcf.Physics) -> specs.BoundedArray: lin = abs(self._control_params.max_lin_vel) rot = abs(self._control_params.max_rot_vel) max_6d_vel = np.asarray([lin, lin, lin, rot, rot, rot]) actuator_names = [(self.prefix + str(i)) for i in range(6)] return specs.BoundedArray( shape=(6,), dtype=np.float32, minimum=-1.0 * max_6d_vel, maximum=max_6d_vel, name='\t'.join(actuator_names)) def set_control(self, physics: mjcf.Physics, command: np.ndarray) -> None: """Sets a 6 DoF Cartesian velocity command at the current timestep. Args: physics: `mjcf.Physics` object with the updated environment state at the current timestep. command: array of size 6 describing the desired 6 DoF Cartesian target [(lin_vel), (ang_vel)]. """ if command.size != 6: raise ValueError('set_control: command must be an np.ndarray of size 6. ' f'Got {command.size}.') cartesian_6d_target = np.copy(command) # If `control_frame` is None, we assume its frame to be the same as the # QP, and thus no transformation is needed. if self._control_frame is not None: # Transform the command from the target frame to the QP frame. stamped_command = geometry.TwistStamped(cartesian_6d_target, self._control_frame) cartesian_6d_target = stamped_command.get_relative_twist( self._qp_frame, mujoco_physics.wrap(physics)).full # Scale the Cartesian 6D velocity target if outside of Cartesian velocity # limits. cartesian_6d_target = _scale_cartesian_6d_velocity( cartesian_6d_target, self._control_params.max_lin_vel, self._control_params.max_rot_vel) # Compute the joint velocities and set the control on underlying velocity # effector. self._joint_velocity_effector.set_control( physics, self._compute_joint_velocities( physics=physics, cartesian_6d_target=cartesian_6d_target)) @property def prefix(self) -> str: return self._effector_prefix @property def control_frame(self) -> geometry.Frame: """Returns the frame in which actions are expected.""" return self._control_frame or self._qp_frame def _compute_joint_velocities(self, physics: mjcf.Physics, cartesian_6d_target: np.ndarray) -> np.ndarray: """Maps a Cartesian 6D target velocity to joint velocities. Args: physics: `mjcf.Physics` object with the updated environment state at the current timestep. cartesian_6d_target: array of size 6 describing the desired 6 DoF Cartesian target [(lin_vel), (ang_vel)]. Must be expressed about the element's origin in the world orientation. Returns: Computed joint velocities in the same order as the `joints` sequence passed during construction. """ joints_binding = physics.bind(self._joints) if joints_binding is None: raise ValueError( '_compute_joint_velocities: could not bind the joint elements passed ' 'on construction to the physics object.') joint_velocities = np.empty(len(self._joints), dtype=np.float32) # Compute nullspace bias if gain is positive. qdot_nullspace = None if (self._control_params.nullspace_gain is not None and self._control_params.nullspace_gain > 0.0 and self._control_params.nullspace_joint_position_reference is not None): qdot_nullspace = self._control_params.nullspace_gain * ( self._control_params.nullspace_joint_position_reference - joints_binding.qpos) / self._control_params.control_timestep_seconds # Reorder qdot_nullspace such that the nullspace bias is in ascending # order relative to the joint IDs. qdot_nullspace = qdot_nullspace[self._joints_argsort] # Compute joint velocities. The Python bindings throw an exception whenever # the mapper fails to find a solution, in which case we set the joint # velocities to zero. # We need to catch a general exception because the StatusOr->Exception # conversion can result in a wide variety of different exceptions. # The only special case is when the user calls CTRL-C, in which case we # re-raise the KeyboardInterrupt exception arising from SIGINT. try: # Note that we need to make sure that the joint velocities are in the same # order as the joints sequence, which may be different from that the QP # returns, i.e. in ascending order. joint_velocities[self._joints_argsort] = np.array( self._qp_mapper.compute_joint_velocities(physics.data, cartesian_6d_target.tolist(), qdot_nullspace), dtype=np.float32) except KeyboardInterrupt: logging.warning('_compute_joint_velocities: Computation interrupted!') raise except Exception as e: # pylint: disable=broad-except joint_velocities.fill(0.0) logging.warning( ('_compute_joint_velocities: Failed to compute joint velocities. ' 'Setting joint velocities to zero. Error: [%s]'), str(e)) return joint_velocities class ConstrainedCartesian6dVelocityEffector( constrained_actions_effectors .ConstrainedActionEffector[Cartesian6dVelocityEffector]): """Effector wrapper that limits certain Cartesian DOFs based on their state. Any command DOFs whose corresponding state surpasses the provided limits will be set to 0. """ def __init__(self, delegate: Cartesian6dVelocityEffector, min_limits: np.ndarray, max_limits: np.ndarray, state_getter: Callable[[mjcf.Physics], np.ndarray]): """Constructor for ConstrainedCartesian6dVelocityEffector. Args: delegate: Unconstrained 6D velocity effector. min_limits: 6D lower limits expressed in the world frame. max_limits: 6D upper limits expressed in the world frame. state_getter: Callable returning a state that will be compared to the limits. The state getter should operate in the world frame because the limits are expressed in that frame. The twist executed by this effector will still happen in the delegate's control frame. """ super().__init__( delegate=delegate, min_limits=min_limits, max_limits=max_limits, state_getter=state_getter) self._delegate = delegate # Lazily load the control frame with world orientation because the delegate # might not have it set correctly yet. self._control_frame_with_world_orientation = None def set_control(self, physics: mjcf.Physics, command: np.ndarray) -> None: # Convert the input twist to the world-oriented frame. twist_control_frame = geometry.TwistStamped( twist=command, frame=self._delegate.control_frame) if not self._control_frame_with_world_orientation: self._control_frame_with_world_orientation = geometry.HybridPoseStamped( pose=None, frame=self._delegate.control_frame, quaternion_override=geometry.PoseStamped(None, None)) twist_world_orientation = twist_control_frame.to_frame( frame=self._control_frame_with_world_orientation, physics=mujoco_physics.wrap(physics)) # Constrain the action to the Cartesian workspace limits. constrained_twist_world_orientation = self._get_contstrained_action( physics, np.array(twist_world_orientation.twist.full)) # Convert the twist back to the control frame. constrained_twist_control_frame = geometry.TwistStamped( twist=constrained_twist_world_orientation, frame=self._control_frame_with_world_orientation).to_frame( self._delegate.control_frame, physics=mujoco_physics.wrap(physics)) self._delegate.set_control(physics, constrained_twist_control_frame.twist.full) def limit_to_workspace( cartesian_effector: Cartesian6dVelocityEffector, element: _MjcfElement, min_workspace_limits: np.ndarray, max_workspace_limits: np.ndarray, ) -> effector.Effector: """Returns an effector that restricts the 6D actions to a workspace. Constraining the rotation of the end effector is currently not supported. Args: cartesian_effector: 6D cartesian effector. element: `mjcf.Element` that defines the Cartesian frame about which the Cartesian velocity is defined. min_workspace_limits: Lower bound of the Cartesian workspace. Must be 3D or 6D (position only or position and Euler orientation) and expressed in the world frame. max_workspace_limits: Upper bound of the Cartesian workspace. Must be 3D or 6D (position only or position and Euler orientation) and expressed in the world frame. """ if len(min_workspace_limits) != len(max_workspace_limits): raise ValueError('The workspace limits must have the same size. Provided ' f'min: {min_workspace_limits} and max: ' f'{max_workspace_limits}') if len(min_workspace_limits) != 3 and len(min_workspace_limits) != 6: raise ValueError('The workspace limits must be 3D or 6D. Provided ' f'min: {min_workspace_limits} and max: ' f'{max_workspace_limits}') if len(min_workspace_limits) == 6: # To handle orientation limits, we need to find the Euler distance from the # control element to a "neutral orientation" which we define as the middle # of the workspace limits provided. neutral_orientation_euler = ((min_workspace_limits + max_workspace_limits) / 2.)[3:6] neutral_orientation_quat = tr.euler_to_quat(neutral_orientation_euler) neutral_orientation_frame = geometry.HybridPoseStamped( pose=None, frame=element, quaternion_override=geometry.PoseStamped( pose=geometry.Pose( position=None, quaternion=neutral_orientation_quat))) def state_getter(physics): current_element_frame = geometry.PoseStamped(pose=None, frame=element) current_element_in_world_frame = current_element_frame.to_world( physics=mujoco_physics.wrap(physics)) if len(min_workspace_limits) == 6: neutral_orientation_quat = neutral_orientation_frame.to_world( physics=mujoco_physics.wrap(physics)).pose.quaternion current_orientation_quat = current_element_in_world_frame.pose.quaternion error_quat = tr.quat_diff_active( source_quat=neutral_orientation_quat, target_quat=current_orientation_quat) error_euler = tr.quat_to_euler(error_quat) # The "state" returned by this function doesn't need to be a Cartesian or # Euler state. It simply needs to be something we can compare to the # limits and actions to make sure an action is ok. The Euler error is a # good proxy for this. orientation_state = error_euler else: # When we don't have orientation limits, we can ignore this part of the # state. orientation_state = [0.0] * 3 return np.concatenate( (current_element_in_world_frame.pose.position, orientation_state)) if len(min_workspace_limits) == 6: # The orientation from the state-getter is already expressed relative to the # "neutral frame" (the average of the min and max limits), so we can remove # the average from here. neutral_state = np.zeros(6) neutral_state[3:6] = neutral_orientation_euler min_limits = min_workspace_limits - neutral_state max_limits = max_workspace_limits - neutral_state else: # Add dummy limits for the orientation. The state_getter() above will always # return all 0's for the orientation part of the state. 0 is in [-1, 1], so # combined with these limits, that means the angular part of the input twist # will simply pass through. No workspace limits will be applied. # The added limits need to match the state from state_getter(), which needs # to match the shape of the input action. min_limits = np.concatenate((min_workspace_limits, [-1.] * 3)) max_limits = np.concatenate((max_workspace_limits, [1.] * 3)) return ConstrainedCartesian6dVelocityEffector( delegate=cartesian_effector, min_limits=min_limits, max_limits=max_limits, state_getter=state_getter)
dm_robotics-main
py/moma/effectors/cartesian_6d_velocity_effector.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Default effector for grippers in sim.""" from dm_control import mjcf # type: ignore from dm_env import specs from dm_robotics.moma import effector from dm_robotics.moma.effectors import mujoco_actuation from dm_robotics.moma.models.end_effectors.robot_hands import robot_hand import numpy as np class DefaultGripperEffector(effector.Effector): """An effector interface for MoMa grippers.""" def __init__(self, gripper: robot_hand.RobotHand, robot_name: str): self._gripper = gripper self._effector_prefix = '{}_gripper'.format(robot_name) self._mujoco_effector = mujoco_actuation.MujocoEffector( self._gripper.actuators, self._effector_prefix) def action_spec(self, physics: mjcf.Physics) -> specs.BoundedArray: return self._mujoco_effector.action_spec(physics) def set_control(self, physics: mjcf.Physics, command: np.ndarray) -> None: self._mujoco_effector.set_control(physics, command) def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: pass @property def prefix(self) -> str: return self._effector_prefix
dm_robotics-main
py/moma/effectors/default_gripper_effector.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 constrained_actions_effectors.py.""" from absl.testing import absltest from absl.testing import parameterized from dm_control import mjcf from dm_robotics.moma.effectors import constrained_actions_effectors from dm_robotics.moma.effectors import test_utils from dm_robotics.moma.models.robots.robot_arms import sawyer import numpy as np class ConstrainedActionsEffectorsTest(parameterized.TestCase): def test_joint_position_limits(self): fake_joint_effector = test_utils.SpyEffector(dofs=7) min_joint_limits = -0.1 * np.ones(7) max_joint_limits = 0.1 * np.ones(7) arm = sawyer.Sawyer(with_pedestal=False) physics = mjcf.Physics.from_mjcf_model(arm.mjcf_model) effector_with_limits = constrained_actions_effectors.LimitJointPositions( joint_effector=fake_joint_effector, min_joint_limits=min_joint_limits, max_joint_limits=max_joint_limits, arm=arm) # Set the arm to a valid position and actuate the joints. valid_joint_pos = [0., 0., 0., 0., 0., 0., 0.] physics.bind(arm.joints).qpos = valid_joint_pos expected_action = np.ones(7) effector_with_limits.set_control(physics, expected_action) np.testing.assert_allclose(fake_joint_effector.previous_action, expected_action) # Set the arm below the min limits. The limiter should only clip negative # actions. Positive actions are unchanged. below_limits_joint_pos = -0.2 * np.ones(7) physics.bind(arm.joints).qpos = below_limits_joint_pos input_action = np.asarray([-1., -1., -1., -1., 1., 1., 1.]) expected_action = np.asarray([0., 0., 0., 0., 1., 1., 1.]) effector_with_limits.set_control(physics, input_action) np.testing.assert_allclose(fake_joint_effector.previous_action, expected_action) # Set the arm above the min limits. The limiter should only clip positive # actions. Negative actions are unchanged. above_limits_joint_pos = 0.2 * np.ones(7) physics.bind(arm.joints).qpos = above_limits_joint_pos input_action = np.asarray([-1., -1., -1., -1., 1., 1., 1.]) expected_action = np.asarray([-1., -1., -1., -1., 0., 0., 0.]) effector_with_limits.set_control(physics, input_action) np.testing.assert_allclose(fake_joint_effector.previous_action, expected_action) def test_state_and_command_have_different_shapes(self): # Imagine a joint torque effector that you want to limit based on both # the current position AND velocity. fake_joint_effector = test_utils.SpyEffector(dofs=7) min_joint_pos_limits = -0.2 * np.ones(7) max_joint_pos_limits = 0.2 * np.ones(7) min_joint_vel_limits = -0.1 * np.ones(7) max_joint_vel_limits = 0.1 * np.ones(7) arm = sawyer.Sawyer(with_pedestal=False) physics = mjcf.Physics.from_mjcf_model(arm.mjcf_model) # The "state" in this case consists of both the joint position AND velocity. def state_getter(p): return np.stack((p.bind(arm.joints).qpos, p.bind(arm.joints).qvel), axis=1) # The limits should have the same shape and include both pos and vel. min_limits = np.stack((min_joint_pos_limits, min_joint_vel_limits), axis=1) max_limits = np.stack((max_joint_pos_limits, max_joint_vel_limits), axis=1) # And our state checkers need to handle the (pos, vel) states. min_checker = lambda st, lim, cmd: np.any(st < lim, axis=1) & (cmd < 0.) max_checker = lambda st, lim, cmd: np.any(st > lim, axis=1) & (cmd > 0.) constrained_effector = ( constrained_actions_effectors.ConstrainedActionEffector( fake_joint_effector, min_limits, max_limits, state_getter, min_checker, max_checker)) # Set the arm to a valid position and vel and actuate the joints. valid_joint_pos = [0., 0., 0., 0., 0., 0., 0.] valid_joint_vel = [0., 0., 0., 0., 0., 0., 0.] physics.bind(arm.joints).qpos = valid_joint_pos physics.bind(arm.joints).qvel = valid_joint_vel expected_action = np.ones(7) constrained_effector.set_control(physics, expected_action) np.testing.assert_allclose(fake_joint_effector.previous_action, expected_action) # Set some joints below the min limits. The limiter should only clip # negative actions. Positive actions are unchanged. joints_pos = [-0.3, -0.3, -0.3, -0.3, 0.0, 0.0, 0.0] joints_vel = [-0.2, -0.2, 0.0, 0.0, -0.2, -0.2, 0.0] physics.bind(arm.joints).qpos = joints_pos physics.bind(arm.joints).qvel = joints_vel input_action = np.asarray([-1., 1., -1., 1., -1., 1., -1.]) expected_action = np.asarray([0., 1., 0., 1., 0., 1., -1.]) constrained_effector.set_control(physics, input_action) np.testing.assert_allclose(fake_joint_effector.previous_action, expected_action) # Set some joints above the max limits. The limiter should only clip # positive actions. Negative actions are unchanged. joints_pos = [0.3, 0.3, 0.3, 0.3, 0.0, 0.0, 0.0] joints_vel = [0.2, 0.2, 0.0, 0.0, 0.2, 0.2, 0.0] physics.bind(arm.joints).qpos = joints_pos physics.bind(arm.joints).qvel = joints_vel input_action = np.asarray([1., -1., 1., -1., 1., -1., 1.]) expected_action = np.asarray([0., -1., 0., -1., 0., -1., 1.]) constrained_effector.set_control(physics, input_action) np.testing.assert_allclose(fake_joint_effector.previous_action, expected_action) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/effectors/constrained_actions_effectors_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 cartesian_4d_velocity_effector.py.""" import copy from absl.testing import absltest from absl.testing import parameterized from dm_control import mjcf from dm_robotics.geometry import geometry from dm_robotics.geometry import mujoco_physics from dm_robotics.moma.effectors import cartesian_4d_velocity_effector from dm_robotics.moma.effectors import test_utils from dm_robotics.moma.models.robots.robot_arms import sawyer import numpy as np class Cartesian4DVelocityEffectorTest(parameterized.TestCase): def test_zero_xy_rot_vel_pointing_down(self): # When the arm is pointing straight down, the default effector shouldn't # apply any X or Y rotations. arm = sawyer.Sawyer(with_pedestal=False) physics = mjcf.Physics.from_mjcf_model(arm.mjcf_model) effector_6d = test_utils.SpyEffectorWithControlFrame(arm.wrist_site, dofs=6) effector_4d = cartesian_4d_velocity_effector.Cartesian4dVelocityEffector( effector_6d, element=arm.wrist_site, effector_prefix='sawyer_4d') arm.set_joint_angles( physics, joint_angles=test_utils.SAFE_SAWYER_JOINTS_POS) physics.step() # propagate the changes to the rest of the physics. # Send an XYZ + Z rot command. We shouldn't see any XY rotation components. effector_4d.set_control(physics, command=np.ones(4) * 0.1) np.testing.assert_allclose(effector_6d.previous_action, [0.1, 0.1, 0.1, 0.0, 0.0, 0.1], atol=1e-3, rtol=0.0) def test_nonzero_xy_rot_vel_not_pointing_down(self): # When the arm is NOT pointing straight down, the default effector should # apply X and Y rotations to push it back to the desired quat. arm = sawyer.Sawyer(with_pedestal=False) physics = mjcf.Physics.from_mjcf_model(arm.mjcf_model) effector_6d = test_utils.SpyEffectorWithControlFrame(arm.wrist_site, dofs=6) effector_4d = cartesian_4d_velocity_effector.Cartesian4dVelocityEffector( effector_6d, element=arm.wrist_site, effector_prefix='sawyer_4d') # random offset to all joints. joint_angles = test_utils.SAFE_SAWYER_JOINTS_POS + 0.1 arm.set_joint_angles(physics, joint_angles=joint_angles) physics.step() # propagate the changes to the rest of the physics. # Send an XYZ + Z rot command. We SHOULD see XY rotation components. effector_4d.set_control(physics, command=np.ones(4) * 0.1) xy_rot_components = effector_6d.previous_action[3:5] self.assertFalse(np.any(np.isclose(xy_rot_components, np.zeros(2)))) def test_limiting_to_workspace(self): arm = sawyer.Sawyer(with_pedestal=False) physics = mjcf.Physics.from_mjcf_model(arm.mjcf_model) effector_6d = test_utils.SpyEffectorWithControlFrame(arm.wrist_site, dofs=6) effector_4d = cartesian_4d_velocity_effector.Cartesian4dVelocityEffector( effector_6d, element=arm.wrist_site, effector_prefix='sawyer_4d') arm.set_joint_angles( physics, joint_angles=test_utils.SAFE_SAWYER_JOINTS_POS) physics.step() # propagate the changes to the rest of the physics. # The arm is pointing down in front of the base. Create a workspace # that encompasses it, and check that all commands are valid. min_workspace_limits = np.array([0.0, -0.5, 0.0]) max_workspace_limits = np.array([0.9, 0.5, 0.5]) effector_with_limits = cartesian_4d_velocity_effector.limit_to_workspace( effector_4d, arm.wrist_site, min_workspace_limits, max_workspace_limits) effector_with_limits.set_control(physics, command=np.ones(4) * 0.1) np.testing.assert_allclose(effector_6d.previous_action, [0.1, 0.1, 0.1, 0.0, 0.0, 0.1], atol=1e-3, rtol=0.0) # The arm is pointing down in front of the base. Create a workspace # where the X position is in bounds, but Y and Z are out of bounds. min_workspace_limits = np.array([0.0, -0.9, 0.5]) max_workspace_limits = np.array([0.9, -0.5, 0.9]) effector_with_limits = cartesian_4d_velocity_effector.limit_to_workspace( effector_4d, arm.wrist_site, min_workspace_limits, max_workspace_limits) # The action should only affect DOFs that are out of bounds and are moving # away from where they should. effector_with_limits.set_control(physics, command=np.ones(4) * 0.1) np.testing.assert_allclose(effector_6d.previous_action, [0.1, 0.0, 0.1, 0.0, 0.0, 0.1], atol=1e-3, rtol=0.0) def test_limiting_wrist_rotation(self): arm = sawyer.Sawyer(with_pedestal=False) physics = mjcf.Physics.from_mjcf_model(arm.mjcf_model) effector_6d = test_utils.SpyEffectorWithControlFrame(arm.wrist_site, dofs=6) effector_4d = cartesian_4d_velocity_effector.Cartesian4dVelocityEffector( effector_6d, element=arm.wrist_site, effector_prefix='sawyer_4d') arm.set_joint_angles( physics, joint_angles=test_utils.SAFE_SAWYER_JOINTS_POS) physics.step() # propagate the changes to the rest of the physics. # The arm is pointing down in front of the base. Create a workspace # that encompasses it. min_workspace_limits = np.array([0.0, -0.5, 0.0]) max_workspace_limits = np.array([0.9, 0.5, 0.5]) # Provide wrist limits which are outside where the wrist is currently. wrist_limits = np.array([ test_utils.SAFE_SAWYER_JOINTS_POS[-1] + 0.1, test_utils.SAFE_SAWYER_JOINTS_POS[-1] + 0.2 ]) effector_with_limits = cartesian_4d_velocity_effector.limit_to_workspace( effector_4d, arm.wrist_site, min_workspace_limits, max_workspace_limits, wrist_joint=arm.joints[-1], wrist_limits=wrist_limits, reverse_wrist_range=True) # For the Sawyer, pos wrist -> neg Z rot. effector_with_limits.set_control(physics, command=np.ones(4) * 0.1) np.testing.assert_allclose(effector_6d.previous_action, [0.1, 0.1, 0.1, 0.0, 0.0, 0.0], atol=1e-3, rtol=0.0) def test_changing_control_frame(self): arm = sawyer.Sawyer(with_pedestal=False) physics = mjcf.Physics.from_mjcf_model(arm.mjcf_model) effector_6d = test_utils.SpyEffectorWithControlFrame(arm.wrist_site, dofs=6) arm.set_joint_angles( physics, joint_angles=test_utils.SAFE_SAWYER_JOINTS_POS) physics.step() # propagate the changes to the rest of the physics # The frame the we want to align the z axis of the arm wrist site to. target_frame = self._target_frame = geometry.HybridPoseStamped( pose=None, frame=arm.wrist_site, quaternion_override=geometry.PoseStamped( pose=geometry.Pose( position=None, quaternion=( cartesian_4d_velocity_effector.DOWNFACING_EE_QUAT_WXYZ)))) # The frame in which the 6d effector expects to receive the velocity # command. world_orientation_frame = geometry.HybridPoseStamped( pose=None, frame=arm.wrist_site, quaternion_override=geometry.PoseStamped(None, None)) # Run the test 10 times with random poses. np.random.seed(42) for _ in range(10): # Build the effector with a random control frame. control_frame = geometry.PoseStamped( pose=geometry.Pose.from_poseuler(np.random.rand(6)), frame=None) cartesian_effector = ( cartesian_4d_velocity_effector.Cartesian4dVelocityEffector( effector_6d, element=arm.wrist_site, control_frame=control_frame, effector_prefix='sawyer_4d')) cartesian_effector.after_compile(arm.mjcf_model, physics) # Create a cartesian command, this command is expressed in the # control frame. cartesian_command = np.array([0.3, 0.1, -0.2, 0.0, 0.0, 0.5], dtype=np.float32) # Send the command to the effector. cartesian_effector.set_control( physics=physics, command=np.append( cartesian_command[0:3], cartesian_command[5])) # Create the twist stamped command stamped_command_control_frame = geometry.TwistStamped( cartesian_command, control_frame) # Get the twist in target frame and remove the x and y rotations. # The robot is already pointing downwards, and is therefore aligned with # the target frame. This means that we do not expect to have any rotation # along the x or y axis of the target frame. stamped_command_target_frame = stamped_command_control_frame.to_frame( target_frame, mujoco_physics.wrap(physics)) target_frame_command = copy.copy(stamped_command_target_frame.twist.full) target_frame_command[3:5] = np.zeros(2) stamped_command_target_frame = stamped_command_target_frame.with_twist( target_frame_command) # Change the command to the world orientation frame. stamped_command_world_orientation_frame = ( stamped_command_target_frame.to_frame( world_orientation_frame, mujoco_physics.wrap(physics))) np.testing.assert_allclose( effector_6d.previous_action, stamped_command_world_orientation_frame.twist.full, atol=1e-3) if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/effectors/cartesian_4d_velocity_effector_test.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Effector that sends only the min or max command to a delegate effector.""" from typing import Optional from dm_control import mjcf from dm_robotics.moma import effector import numpy as np class MinMaxEffector(effector.Effector): """Effector to send minimum or maximum command values to a base effector. This effector will ensure that only the min and max commands are sent to the effector. This is useful for example when controlling a gripper and we want to either have a fully open or fully closed actuation mode. The effector will take the input command and send: - The minimum command for all input values <= midrange - The maximum command for all input values > midrange. Example: min_action: [1., 1., 1,] max_action: [3., 3., 3.] input_command: [1.2, 2., 2.3] output_command: [1., 1., 3.] """ def __init__( self, base_effector: effector.Effector, min_action: Optional[np.ndarray] = None, max_action: Optional[np.ndarray] = None): """Constructor. Args: base_effector: Effector to wrap. min_action: Array containing the minimum actions. max_action: Array containing the maximum actions. """ self._effector = base_effector self._min_act = min_action self._max_act = max_action self._action_spec = None def action_spec(self, physics): if self._action_spec is None: self._action_spec = self._effector.action_spec(physics) # We get the minimum actions for each DOF. If the user provided no value, # we use the one from the environment. if self._min_act is None: self._min_act = self._action_spec.minimum if self._min_act.size == 1: self._min_act = np.full( self._action_spec.shape, self._min_act, self._action_spec.dtype) if self._min_act.shape != self._action_spec.shape: raise ValueError('The provided minimum action does not have the same ' 'shape as the action expected by the base effector ' f'expected shape {self._action_spec.shape} but ' f'{self._min_act} was provided') if self._max_act is None: self._max_act = self._action_spec.maximum if self._max_act.size == 1: self._max_act = np.full( self._action_spec.shape, self._max_act, self._action_spec.dtype) if self._max_act.shape != self._action_spec.shape: raise ValueError('The provided maximum action does not have the same ' 'shape as the action expected by the base effector ' f'expected shape {self._action_spec.shape} but ' f'{self._max_act} was provided') return self._action_spec def set_control(self, physics, command): if self._action_spec is None: self.action_spec(physics) new_cmd = np.zeros( shape=self._action_spec.shape, dtype=self._action_spec.dtype) mid_point = (self._action_spec.minimum + self._action_spec.maximum) / 2 min_idxs = command <= mid_point max_idxs = command > mid_point new_cmd[min_idxs] = self._min_act[min_idxs] new_cmd[max_idxs] = self._max_act[max_idxs] self._effector.set_control(physics, new_cmd) def after_compile(self, mjcf_model: mjcf.RootElement, physics: mjcf.Physics) -> None: self._effector.after_compile(mjcf_model, physics) def initialize_episode(self, physics: mjcf.Physics, random_state: np.random.RandomState) -> None: self._effector.initialize_episode(physics, random_state) def close(self): self._effector.close() @property def prefix(self) -> str: return self._effector.prefix
dm_robotics-main
py/moma/effectors/min_max_effector.py
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 cartesian_6d_velocity_effector.""" from unittest import mock from absl.testing import absltest from absl.testing import parameterized from dm_control import mjcf from dm_robotics.geometry import geometry from dm_robotics.geometry import mujoco_physics from dm_robotics.moma.effectors import arm_effector from dm_robotics.moma.effectors import cartesian_6d_velocity_effector from dm_robotics.moma.effectors import test_utils from dm_robotics.moma.models.robots.robot_arms import sawyer import numpy as np @parameterized.named_parameters( ('use_adaptive_step_size', True), ('do_not_use_adaptive_step_size', False), ) class Cartesian6dVelocityEffectorTest(parameterized.TestCase): def test_setting_control(self, use_adaptive_qp_step_size): arm = sawyer.Sawyer(with_pedestal=False) joints = arm.joints element = arm.wrist_site physics = mjcf.Physics.from_mjcf_model(arm.mjcf_model) sawyer_effector = arm_effector.ArmEffector( arm=arm, action_range_override=None, robot_name='sawyer') cartesian_effector = cartesian_6d_velocity_effector.Cartesian6dVelocityEffector( 'robot0', sawyer_effector, cartesian_6d_velocity_effector.ModelParams(element, joints), cartesian_6d_velocity_effector.ControlParams( control_timestep_seconds=1.0, nullspace_gain=0.0), use_adaptive_qp_step_size=use_adaptive_qp_step_size) cartesian_effector.after_compile(arm.mjcf_model, physics) # Set a Cartesian command that can be tracked at the initial Sawyer # configuration, and step physics. cartesian_command = np.array([0.0, 0.0, 0.0, 0.0, 0.5, 0.0], dtype=np.float32) # Let the actuators to catch-up to the requested velocity, after which the # resultant Cartesian velocity should be within expected tolerances. for _ in range(300): # Apply gravity compensation at every timestep; the velocity actuators # do not work well under gravity. _compensate_gravity(physics, arm.mjcf_model) cartesian_effector.set_control(physics, cartesian_command) physics.step() for _ in range(5): _compensate_gravity(physics, arm.mjcf_model) cartesian_effector.set_control(physics, cartesian_command) physics.step() twist = physics.data.object_velocity( element.full_identifier, 'site', local_frame=False) np.testing.assert_allclose(twist[0], cartesian_command[:3], atol=5e-2) np.testing.assert_allclose(twist[1], cartesian_command[3:], atol=5e-2) def test_control_frame(self, use_adaptive_qp_step_size): arm = sawyer.Sawyer(with_pedestal=False) joints = arm.joints element = arm.wrist_site physics = mjcf.Physics.from_mjcf_model(arm.mjcf_model) sawyer_effector = arm_effector.ArmEffector( arm=arm, action_range_override=None, robot_name='sawyer') # Run the test 10 times with random poses. np.random.seed(42) for _ in range(10): control_frame = geometry.PoseStamped( pose=geometry.Pose.from_poseuler(np.random.rand(6)), frame=element) cartesian_effector = cartesian_6d_velocity_effector.Cartesian6dVelocityEffector( 'robot0', sawyer_effector, cartesian_6d_velocity_effector.ModelParams(element, joints, control_frame), cartesian_6d_velocity_effector.ControlParams( control_timestep_seconds=1.0, max_lin_vel=10.0, max_rot_vel=10.0, nullspace_gain=0.0), use_adaptive_qp_step_size=use_adaptive_qp_step_size) cartesian_effector.after_compile(arm.mjcf_model, physics) # Create a cartesian command stamped on the control frame, and compute the # expected 6D target that is passed to the mapper. cartesian_command = np.array([0.3, 0.1, -0.2, 0.4, 0.2, 0.5], dtype=np.float32) stamped_command = geometry.TwistStamped(cartesian_command, control_frame) qp_frame = geometry.HybridPoseStamped( pose=None, frame=element, quaternion_override=geometry.PoseStamped(None, None)) cartesian_6d_target = stamped_command.get_relative_twist( qp_frame, mujoco_physics.wrap(physics)).full # Wrap the `_compute_joint_velocities` function and ensure that it is # called with a Cartesian 6D velocity expressed about the element's # origin in world-orientation. with mock.patch.object( cartesian_6d_velocity_effector.Cartesian6dVelocityEffector, '_compute_joint_velocities', wraps=cartesian_effector._compute_joint_velocities) as mock_fn: cartesian_effector.set_control(physics, cartesian_command) # We test the input Cartesian 6D target with a very low tolerance # instead of equality, as internally the transformation may be done # differently and result in numerically similar but different values. self.assertEqual(1, mock_fn.call_count) args_kwargs = mock_fn.call_args[1] self.assertEqual(args_kwargs['physics'], physics) np.testing.assert_allclose( args_kwargs['cartesian_6d_target'], cartesian_6d_target, atol=1.0e-7) def test_joint_velocity_limits(self, use_adaptive_qp_step_size): arm = sawyer.Sawyer(with_pedestal=False) joints = arm.joints element = arm.wrist_site physics = mjcf.Physics.from_mjcf_model(arm.mjcf_model) sawyer_effector = arm_effector.ArmEffector( arm=arm, action_range_override=None, robot_name='sawyer') joint_vel_limits = np.ones(7) * 1e-2 cartesian_effector = ( cartesian_6d_velocity_effector.Cartesian6dVelocityEffector( 'robot0', sawyer_effector, cartesian_6d_velocity_effector.ModelParams(element, joints), cartesian_6d_velocity_effector.ControlParams( control_timestep_seconds=1.0, nullspace_gain=0.0, max_lin_vel=1e3, max_rot_vel=1e3, joint_velocity_limits=joint_vel_limits), use_adaptive_qp_step_size=use_adaptive_qp_step_size)) cartesian_effector.after_compile(arm.mjcf_model, physics) # Set a very large Cartesian command, and ensure that joint velocity limits # are never violated. cartesian_command = np.ones(6) * 1e3 for _ in range(1000): _compensate_gravity(physics, arm.mjcf_model) cartesian_effector.set_control(physics, cartesian_command) joint_vel_ctrls = np.absolute(physics.bind(arm.actuators).ctrl) self.assertTrue(np.less_equal(joint_vel_ctrls, joint_vel_limits).all()) physics.step() def test_limiting_to_workspace(self, use_adaptive_qp_step_size): arm = sawyer.Sawyer(with_pedestal=False) joints = arm.joints element = arm.wrist_site physics = mjcf.Physics.from_mjcf_model(arm.mjcf_model) effector_6d = test_utils.SpyEffectorWithControlFrame(element, dofs=6) sawyer_effector = arm_effector.ArmEffector( arm=arm, action_range_override=None, robot_name='sawyer') joint_vel_limits = np.ones(7) * 1e-2 cartesian_effector = ( cartesian_6d_velocity_effector.Cartesian6dVelocityEffector( 'robot0', sawyer_effector, cartesian_6d_velocity_effector.ModelParams(element, joints), cartesian_6d_velocity_effector.ControlParams( control_timestep_seconds=1.0, nullspace_gain=0.0, max_lin_vel=1e3, max_rot_vel=1e3, joint_velocity_limits=joint_vel_limits), use_adaptive_qp_step_size=use_adaptive_qp_step_size)) cartesian_effector.after_compile(arm.mjcf_model, physics) arm.set_joint_angles( physics, joint_angles=test_utils.SAFE_SAWYER_JOINTS_POS) # Propagate the changes to the rest of the physics. physics.step() # The arm is pointing down in front of the base. Create a # workspace that encompasses it, and check that all commands are # valid. min_workspace_limits = np.array([0.0, -0.5, 0.0]) max_workspace_limits = np.array([0.9, 0.5, 0.5]) effector_with_limits = ( cartesian_6d_velocity_effector.limit_to_workspace( effector_6d, arm.wrist_site, min_workspace_limits, max_workspace_limits)) effector_with_limits.set_control(physics, command=np.ones(6) * 0.1) np.testing.assert_allclose( effector_6d.previous_action, [0.1, 0.1, 0.1, 0.1, 0.1, 0.1], atol=1e-3, rtol=0.0) # The arm is pointing down in front of the base. Create a # workspace where the X position is in bounds, but Y and Z are out # of bounds. min_workspace_limits = np.array([0.0, -0.9, 0.5]) max_workspace_limits = np.array([0.9, -0.5, 0.9]) effector_with_limits = ( cartesian_6d_velocity_effector.limit_to_workspace( effector_6d, arm.wrist_site, min_workspace_limits, max_workspace_limits)) # The action should only affect DOFs that are out of bounds and # are moving away from where they should. effector_with_limits.set_control(physics, command=np.ones(6) * 0.1) np.testing.assert_allclose( effector_6d.previous_action, [0.1, 0.0, 0.1, 0.1, 0.1, 0.1], atol=1e-3, rtol=0.0) def test_limiting_orientation_to_workspace(self, use_adaptive_qp_step_size): arm = sawyer.Sawyer(with_pedestal=False) joints = arm.joints element = arm.wrist_site physics = mjcf.Physics.from_mjcf_model(arm.mjcf_model) effector_6d = test_utils.SpyEffectorWithControlFrame(element, dofs=6) sawyer_effector = arm_effector.ArmEffector( arm=arm, action_range_override=None, robot_name='sawyer') joint_vel_limits = np.ones(7) * 1e-2 cartesian_effector = ( cartesian_6d_velocity_effector.Cartesian6dVelocityEffector( 'robot0', sawyer_effector, cartesian_6d_velocity_effector.ModelParams(element, joints), cartesian_6d_velocity_effector.ControlParams( control_timestep_seconds=1.0, nullspace_gain=0.0, max_lin_vel=1e3, max_rot_vel=1e3, joint_velocity_limits=joint_vel_limits), use_adaptive_qp_step_size=use_adaptive_qp_step_size)) cartesian_effector.after_compile(arm.mjcf_model, physics) arm.set_joint_angles( physics, joint_angles=test_utils.SAFE_SAWYER_JOINTS_POS) # Propagate the changes to the rest of the physics. physics.step() # The arm is pointing down in front of the base. Create a # workspace that encompasses it, and check that all commands are # valid. min_workspace_limits = np.array([0.0, -0.5, 0.0, 0.0, -np.pi, -np.pi]) max_workspace_limits = np.array([0.9, 0.5, 0.5, 2 * np.pi, np.pi, np.pi]) effector_with_limits = ( cartesian_6d_velocity_effector.limit_to_workspace( effector_6d, arm.wrist_site, min_workspace_limits, max_workspace_limits)) effector_with_limits.set_control(physics, command=np.ones(6) * 0.1) np.testing.assert_allclose( effector_6d.previous_action, np.ones(6) * 0.1, atol=1e-3, rtol=0.0) # The arm is pointing down in front of the base (x_rot = np.pi). Create a # workspace where the Y and Z orientations are in bounds, but X is out of # bounds. arm.set_joint_angles( physics, joint_angles=test_utils.SAFE_SAWYER_JOINTS_POS) # Propagate the changes to the rest of the physics. physics.step() min_workspace_limits = np.array([0., -0.5, 0., -np.pi / 2, -np.pi, -np.pi]) max_workspace_limits = np.array([0.9, 0.5, 0.5, 0.0, np.pi, np.pi]) effector_with_limits = ( cartesian_6d_velocity_effector.limit_to_workspace( effector_6d, arm.wrist_site, min_workspace_limits, max_workspace_limits)) # The action should only affect DOFs that are out of bounds and # are moving away from where they should. effector_with_limits.set_control(physics, command=np.ones(6) * 0.1) np.testing.assert_allclose( effector_6d.previous_action, [0.1, 0.1, 0.1, 0., 0.1, 0.1], atol=1e-3, rtol=0.0) def test_collision_avoidance(self, use_adaptive_qp_step_size): # Add a sphere above the sawyer that it would collide with if it moves up. arm = sawyer.Sawyer(with_pedestal=False) obstacle = arm.mjcf_model.worldbody.add( 'geom', type='sphere', pos='0.7 0 0.8', size='0.3') move_up_cmd = np.array([0.0, 0.0, 0.5, 0.0, 0.0, 0.0], dtype=np.float32) # Make an effector without collision avoidance, and initialize a physics # object to be used with this effector. unsafe_physics = mjcf.Physics.from_mjcf_model(arm.mjcf_model) unsafe_effector = _create_cartesian_effector( unsafe_physics.model.opt.timestep, arm, None, use_adaptive_qp_step_size, physics=unsafe_physics) # Make an effector with collision avoidance, and initialize a physics object # to be used with this effector. collision_pairs = _self_collision(arm) + _collisions_between(arm, obstacle) collision_params = cartesian_6d_velocity_effector.CollisionParams( collision_pairs) safe_physics = mjcf.Physics.from_mjcf_model(arm.mjcf_model) safe_effector = _create_cartesian_effector(safe_physics.model.opt.timestep, arm, collision_params, use_adaptive_qp_step_size, safe_physics) # Assert the no-collision avoidance setup collides. # This should happen between iterations 250 & 300. collided_per_step = _get_collisions_over_n_steps(300, unsafe_physics, unsafe_effector, move_up_cmd, arm) self.assertTrue(all(collided_per_step[250:])) # Assert the collision avoidance setup never collides for the same command. collided_per_step = _get_collisions_over_n_steps(1000, safe_physics, safe_effector, move_up_cmd, arm) self.assertFalse(any(collided_per_step)) def _compensate_gravity(physics, mjcf_model): """Adds fake forces to bodies in physics to compensate gravity.""" gravity = np.hstack([physics.model.opt.gravity, [0, 0, 0]]) bodies = physics.bind(mjcf_model.find_all('body')) bodies.xfrc_applied = -gravity * bodies.mass[..., None] def _step_and_check_collisions(physics, mjcf_model, cartesian_effector, cartesian_command): """Steps the physics with grav comp. Returns True if in collision.""" _compensate_gravity(physics, mjcf_model) cartesian_effector.set_control(physics, cartesian_command) physics.step() for contact in physics.data.contact: if contact.dist < 0.0: return True return False def _get_collisions_over_n_steps(n, physics, effector, command, arm): """Returns the result of `_step_and_check_collisions` over `n` steps.""" collided_per_step = [] for _ in range(n): collided_per_step.append( _step_and_check_collisions(physics, arm.mjcf_model, effector, command)) return collided_per_step def _self_collision(entity): return [(entity.collision_geom_group, entity.collision_geom_group)] def _collisions_between(lhs, rhs: mjcf.Element): return [(lhs.collision_geom_group, [rhs.full_identifier])] def _create_cartesian_effector(timestep, arm, collision_params, use_adaptive_qp_step_size, physics): joint_effector = arm_effector.ArmEffector( arm=arm, action_range_override=None, robot_name='sawyer') cartesian_effector = cartesian_6d_velocity_effector.Cartesian6dVelocityEffector( 'robot0', joint_effector, cartesian_6d_velocity_effector.ModelParams(arm.wrist_site, arm.joints), cartesian_6d_velocity_effector.ControlParams( control_timestep_seconds=timestep, nullspace_gain=0.0), collision_params, use_adaptive_qp_step_size=use_adaptive_qp_step_size) cartesian_effector.after_compile(arm.mjcf_model, physics) return cartesian_effector if __name__ == '__main__': absltest.main()
dm_robotics-main
py/moma/effectors/cartesian_6d_velocity_effector_test.py