Ravenveil commited on
Commit
c59719b
·
verified ·
1 Parent(s): 8154c82

backup 04_physworld 2026-11-08 10:11:26 (part 16)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +8 -0
  2. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/__pycache__/mock_environment.cpython-311.pyc +0 -0
  3. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/__pycache__/simulate.cpython-311.pyc +0 -0
  4. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/__pycache__/streaming_mean.cpython-311.pyc +0 -0
  5. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/__pycache__/wrappers.cpython-311.pyc +0 -0
  6. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/attr_dict.py +53 -0
  7. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/batch_env.py +119 -0
  8. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/count_weights.py +50 -0
  9. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/in_graph_batch_env.py +177 -0
  10. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/in_graph_env.py +160 -0
  11. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/loop.py +235 -0
  12. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/mock_algorithm.py +50 -0
  13. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/mock_environment.py +85 -0
  14. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/simulate.py +141 -0
  15. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/streaming_mean.py +67 -0
  16. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/wrappers.py +558 -0
  17. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/train_ppo.py +155 -0
  18. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/utility.py +185 -0
  19. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/visualize_ppo.py +138 -0
  20. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__init__.py +9 -0
  21. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/__init__.cpython-311.pyc +0 -0
  22. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/enjoy_kuka_diverse_object_grasping.cpython-311.pyc +0 -0
  23. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/enjoy_kuka_grasping.cpython-311.pyc +0 -0
  24. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/enjoy_pybullet_cartpole.cpython-311.pyc +0 -0
  25. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/enjoy_pybullet_racecar.cpython-311.pyc +0 -0
  26. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/enjoy_pybullet_zed_racecar.cpython-311.pyc +0 -0
  27. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/train_kuka_cam_grasping.cpython-311.pyc +0 -0
  28. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/train_kuka_grasping.cpython-311.pyc +0 -0
  29. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/train_pybullet_cartpole.cpython-311.pyc +0 -0
  30. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/train_pybullet_racecar.cpython-311.pyc +0 -0
  31. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/train_pybullet_zed_racecar.cpython-311.pyc +0 -0
  32. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/enjoy_kuka_diverse_object_grasping.py +60 -0
  33. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/enjoy_kuka_grasping.py +32 -0
  34. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/enjoy_pybullet_cartpole.py +38 -0
  35. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/enjoy_pybullet_racecar.py +32 -0
  36. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/enjoy_pybullet_zed_racecar.py +32 -0
  37. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/train_kuka_cam_grasping.py +45 -0
  38. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/train_kuka_grasping.py +43 -0
  39. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/train_pybullet_cartpole.py +37 -0
  40. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/train_pybullet_racecar.py +41 -0
  41. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/train_pybullet_zed_racecar.py +43 -0
  42. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__init__.py +9 -0
  43. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__pycache__/__init__.cpython-311.pyc +0 -0
  44. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__pycache__/cartpole_bullet.cpython-311.pyc +0 -0
  45. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__pycache__/env_randomizer_base.cpython-311.pyc +0 -0
  46. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__pycache__/kuka.cpython-311.pyc +0 -0
  47. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__pycache__/kukaCamGymEnv.cpython-311.pyc +0 -0
  48. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__pycache__/kukaGymEnv.cpython-311.pyc +0 -0
  49. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__pycache__/kuka_diverse_object_gym_env.cpython-311.pyc +0 -0
  50. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__pycache__/minitaur.cpython-311.pyc +0 -0
.gitattributes CHANGED
@@ -3615,3 +3615,11 @@ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_data/xarm/xa
3615
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_data/xarm/xarm_gripper/meshes/left_inner_knuckle.STL filter=lfs diff=lfs merge=lfs -text
3616
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_data/xarm/xarm_gripper/meshes/right_finger.STL filter=lfs diff=lfs merge=lfs -text
3617
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_data/xarm/xarm_gripper/meshes/right_inner_knuckle.STL filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
3615
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_data/xarm/xarm_gripper/meshes/left_inner_knuckle.STL filter=lfs diff=lfs merge=lfs -text
3616
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_data/xarm/xarm_gripper/meshes/right_finger.STL filter=lfs diff=lfs merge=lfs -text
3617
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_data/xarm/xarm_gripper/meshes/right_inner_knuckle.STL filter=lfs diff=lfs merge=lfs -text
3618
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/examples/__pycache__/enjoy_TF_AntBulletEnv_v0_2017may.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3619
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/examples/__pycache__/enjoy_TF_HalfCheetahBulletEnv_v0_2017may.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3620
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/examples/__pycache__/enjoy_TF_HumanoidBulletEnv_v0_2017may.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3621
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/examples/__pycache__/enjoy_TF_HumanoidFlagrunHarderBulletEnv_v1_2017jul.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3622
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/rtree/__pycache__/index.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3623
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/rtree.libs/libspatialindex-e5350069.so filter=lfs diff=lfs merge=lfs -text
3624
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_cyutility.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3625
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/_lib/_uarray/_uarray.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/__pycache__/mock_environment.cpython-311.pyc ADDED
Binary file (4.6 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/__pycache__/simulate.cpython-311.pyc ADDED
Binary file (11.9 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/__pycache__/streaming_mean.cpython-311.pyc ADDED
Binary file (4.37 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/__pycache__/wrappers.cpython-311.pyc ADDED
Binary file (29.1 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/attr_dict.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The TensorFlow Agents Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Wrap a dictionary to access keys as attributes."""
15
+
16
+ from __future__ import absolute_import
17
+ from __future__ import division
18
+ from __future__ import print_function
19
+
20
+ import contextlib
21
+
22
+
23
+ class AttrDict(dict):
24
+ """Wrap a dictionary to access keys as attributes."""
25
+
26
+ def __init__(self, *args, **kwargs):
27
+ super(AttrDict, self).__init__(*args, **kwargs)
28
+ super(AttrDict, self).__setattr__('_mutable', False)
29
+
30
+ def __getattr__(self, key):
31
+ # Do not provide None for unimplemented magic attributes.
32
+ if key.startswith('__'):
33
+ raise AttributeError
34
+ return self.get(key, None)
35
+
36
+ def __setattr__(self, key, value):
37
+ if not self._mutable:
38
+ message = "Cannot set attribute '{}'.".format(key)
39
+ message += " Use 'with obj.unlocked:' scope to set attributes."
40
+ raise RuntimeError(message)
41
+ if key.startswith('__'):
42
+ raise AttributeError("Cannot set magic attribute '{}'".format(key))
43
+ self[key] = value
44
+
45
+ @property
46
+ @contextlib.contextmanager
47
+ def unlocked(self):
48
+ super(AttrDict, self).__setattr__('_mutable', True)
49
+ yield
50
+ super(AttrDict, self).__setattr__('_mutable', False)
51
+
52
+ def copy(self):
53
+ return type(self)(super(AttrDict, self).copy())
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/batch_env.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The TensorFlow Agents Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Combine multiple environments to step them in batch."""
15
+
16
+ from __future__ import absolute_import
17
+ from __future__ import division
18
+ from __future__ import print_function
19
+
20
+ import numpy as np
21
+
22
+
23
+ class BatchEnv(object):
24
+ """Combine multiple environments to step them in batch."""
25
+
26
+ def __init__(self, envs, blocking):
27
+ """Combine multiple environments to step them in batch.
28
+
29
+ To step environments in parallel, environments must support a
30
+ `blocking=False` argument to their step and reset functions that makes them
31
+ return callables instead to receive the result at a later time.
32
+
33
+ Args:
34
+ envs: List of environments.
35
+ blocking: Step environments after another rather than in parallel.
36
+
37
+ Raises:
38
+ ValueError: Environments have different observation or action spaces.
39
+ """
40
+ self._envs = envs
41
+ self._blocking = blocking
42
+ observ_space = self._envs[0].observation_space
43
+ if not all(env.observation_space == observ_space for env in self._envs):
44
+ raise ValueError('All environments must use the same observation space.')
45
+ action_space = self._envs[0].action_space
46
+ if not all(env.action_space == action_space for env in self._envs):
47
+ raise ValueError('All environments must use the same observation space.')
48
+
49
+ def __len__(self):
50
+ """Number of combined environments."""
51
+ return len(self._envs)
52
+
53
+ def __getitem__(self, index):
54
+ """Access an underlying environment by index."""
55
+ return self._envs[index]
56
+
57
+ def __getattr__(self, name):
58
+ """Forward unimplemented attributes to one of the original environments.
59
+
60
+ Args:
61
+ name: Attribute that was accessed.
62
+
63
+ Returns:
64
+ Value behind the attribute name one of the wrapped environments.
65
+ """
66
+ return getattr(self._envs[0], name)
67
+
68
+ def step(self, actions):
69
+ """Forward a batch of actions to the wrapped environments.
70
+
71
+ Args:
72
+ actions: Batched action to apply to the environment.
73
+
74
+ Raises:
75
+ ValueError: Invalid actions.
76
+
77
+ Returns:
78
+ Batch of observations, rewards, and done flags.
79
+ """
80
+ for index, (env, action) in enumerate(zip(self._envs, actions)):
81
+ if not env.action_space.contains(action):
82
+ message = 'Invalid action at index {}: {}'
83
+ raise ValueError(message.format(index, action))
84
+ if self._blocking:
85
+ transitions = [env.step(action) for env, action in zip(self._envs, actions)]
86
+ else:
87
+ transitions = [env.step(action, blocking=False) for env, action in zip(self._envs, actions)]
88
+ transitions = [transition() for transition in transitions]
89
+ observs, rewards, dones, infos = zip(*transitions)
90
+ observ = np.stack(observs)
91
+ reward = np.stack(rewards)
92
+ done = np.stack(dones)
93
+ info = tuple(infos)
94
+ return observ, reward, done, info
95
+
96
+ def reset(self, indices=None):
97
+ """Reset the environment and convert the resulting observation.
98
+
99
+ Args:
100
+ indices: The batch indices of environments to reset; defaults to all.
101
+
102
+ Returns:
103
+ Batch of observations.
104
+ """
105
+ if indices is None:
106
+ indices = np.arange(len(self._envs))
107
+ if self._blocking:
108
+ observs = [self._envs[index].reset() for index in indices]
109
+ else:
110
+ observs = [self._envs[index].reset(blocking=False) for index in indices]
111
+ observs = [observ() for observ in observs]
112
+ observ = np.stack(observs)
113
+ return observ
114
+
115
+ def close(self):
116
+ """Send close messages to the external process and join them."""
117
+ for env in self._envs:
118
+ if hasattr(env, 'close'):
119
+ env.close()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/count_weights.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The TensorFlow Agents Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Count learnable parameters."""
15
+
16
+ from __future__ import absolute_import
17
+ from __future__ import division
18
+ from __future__ import print_function
19
+
20
+ import re
21
+
22
+ import numpy as np
23
+ try:
24
+ import tensorflow.compat.v1 as tf
25
+ except Exception:
26
+ import tensorflow as tf
27
+
28
+
29
+ def count_weights(scope=None, exclude=None, graph=None):
30
+ """Count learnable parameters.
31
+
32
+ Args:
33
+ scope: Resrict the count to a variable scope.
34
+ exclude: Regex to match variable names to exclude.
35
+ graph: Operate on a graph other than the current default graph.
36
+
37
+ Returns:
38
+ Number of learnable parameters as integer.
39
+ """
40
+ if scope:
41
+ scope = scope if scope.endswith('/') else scope + '/'
42
+ graph = graph or tf.get_default_graph()
43
+ vars_ = graph.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
44
+ if scope:
45
+ vars_ = [var for var in vars_ if var.name.startswith(scope)]
46
+ if exclude:
47
+ exclude = re.compile(exclude)
48
+ vars_ = [var for var in vars_ if not exclude.match(var.name)]
49
+ shapes = [var.get_shape().as_list() for var in vars_]
50
+ return int(sum(np.prod(shape) for shape in shapes))
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/in_graph_batch_env.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The TensorFlow Agents Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Batch of environments inside the TensorFlow graph."""
15
+
16
+ from __future__ import absolute_import
17
+ from __future__ import division
18
+ from __future__ import print_function
19
+
20
+ import gym
21
+ try:
22
+ import tensorflow.compat.v1 as tf
23
+ except Exception:
24
+ import tensorflow as tf
25
+
26
+
27
+ class InGraphBatchEnv(object):
28
+ """Batch of environments inside the TensorFlow graph.
29
+
30
+ The batch of environments will be stepped and reset inside of the graph using
31
+ a tf.py_func(). The current batch of observations, actions, rewards, and done
32
+ flags are held in according variables.
33
+ """
34
+
35
+ def __init__(self, batch_env):
36
+ """Batch of environments inside the TensorFlow graph.
37
+
38
+ Args:
39
+ batch_env: Batch environment.
40
+ """
41
+ self._batch_env = batch_env
42
+ observ_shape = self._parse_shape(self._batch_env.observation_space)
43
+ observ_dtype = self._parse_dtype(self._batch_env.observation_space)
44
+ action_shape = self._parse_shape(self._batch_env.action_space)
45
+ action_dtype = self._parse_dtype(self._batch_env.action_space)
46
+ with tf.variable_scope('env_temporary'):
47
+ self._observ = tf.Variable(tf.zeros((len(self._batch_env),) + observ_shape, observ_dtype),
48
+ name='observ',
49
+ trainable=False)
50
+ self._action = tf.Variable(tf.zeros((len(self._batch_env),) + action_shape, action_dtype),
51
+ name='action',
52
+ trainable=False)
53
+ self._reward = tf.Variable(tf.zeros((len(self._batch_env),), tf.float32),
54
+ name='reward',
55
+ trainable=False)
56
+ self._done = tf.Variable(tf.cast(tf.ones((len(self._batch_env),)), tf.bool),
57
+ name='done',
58
+ trainable=False)
59
+
60
+ def __getattr__(self, name):
61
+ """Forward unimplemented attributes to one of the original environments.
62
+
63
+ Args:
64
+ name: Attribute that was accessed.
65
+
66
+ Returns:
67
+ Value behind the attribute name in one of the original environments.
68
+ """
69
+ return getattr(self._batch_env, name)
70
+
71
+ def __len__(self):
72
+ """Number of combined environments."""
73
+ return len(self._batch_env)
74
+
75
+ def __getitem__(self, index):
76
+ """Access an underlying environment by index."""
77
+ return self._batch_env[index]
78
+
79
+ def simulate(self, action):
80
+ """Step the batch of environments.
81
+
82
+ The results of the step can be accessed from the variables defined below.
83
+
84
+ Args:
85
+ action: Tensor holding the batch of actions to apply.
86
+
87
+ Returns:
88
+ Operation.
89
+ """
90
+ with tf.name_scope('environment/simulate'):
91
+ if action.dtype in (tf.float16, tf.float32, tf.float64):
92
+ action = tf.check_numerics(action, 'action')
93
+ observ_dtype = self._parse_dtype(self._batch_env.observation_space)
94
+ observ, reward, done = tf.py_func(lambda a: self._batch_env.step(a)[:3], [action],
95
+ [observ_dtype, tf.float32, tf.bool],
96
+ name='step')
97
+ observ = tf.check_numerics(observ, 'observ')
98
+ reward = tf.check_numerics(reward, 'reward')
99
+ return tf.group(self._observ.assign(observ), self._action.assign(action),
100
+ self._reward.assign(reward), self._done.assign(done))
101
+
102
+ def reset(self, indices=None):
103
+ """Reset the batch of environments.
104
+
105
+ Args:
106
+ indices: The batch indices of the environments to reset; defaults to all.
107
+
108
+ Returns:
109
+ Batch tensor of the new observations.
110
+ """
111
+ if indices is None:
112
+ indices = tf.range(len(self._batch_env))
113
+ observ_dtype = self._parse_dtype(self._batch_env.observation_space)
114
+ observ = tf.py_func(self._batch_env.reset, [indices], observ_dtype, name='reset')
115
+ observ = tf.check_numerics(observ, 'observ')
116
+ reward = tf.zeros_like(indices, tf.float32)
117
+ done = tf.zeros_like(indices, tf.bool)
118
+ with tf.control_dependencies([
119
+ tf.scatter_update(self._observ, indices, observ),
120
+ tf.scatter_update(self._reward, indices, reward),
121
+ tf.scatter_update(self._done, indices, done)
122
+ ]):
123
+ return tf.identity(observ)
124
+
125
+ @property
126
+ def observ(self):
127
+ """Access the variable holding the current observation."""
128
+ return self._observ
129
+
130
+ @property
131
+ def action(self):
132
+ """Access the variable holding the last recieved action."""
133
+ return self._action
134
+
135
+ @property
136
+ def reward(self):
137
+ """Access the variable holding the current reward."""
138
+ return self._reward
139
+
140
+ @property
141
+ def done(self):
142
+ """Access the variable indicating whether the episode is done."""
143
+ return self._done
144
+
145
+ def close(self):
146
+ """Send close messages to the external process and join them."""
147
+ self._batch_env.close()
148
+
149
+ def _parse_shape(self, space):
150
+ """Get a tensor shape from a OpenAI Gym space.
151
+
152
+ Args:
153
+ space: Gym space.
154
+
155
+ Returns:
156
+ Shape tuple.
157
+ """
158
+ if isinstance(space, gym.spaces.Discrete):
159
+ return ()
160
+ if isinstance(space, gym.spaces.Box):
161
+ return space.shape
162
+ raise NotImplementedError()
163
+
164
+ def _parse_dtype(self, space):
165
+ """Get a tensor dtype from a OpenAI Gym space.
166
+
167
+ Args:
168
+ space: Gym space.
169
+
170
+ Returns:
171
+ TensorFlow data type.
172
+ """
173
+ if isinstance(space, gym.spaces.Discrete):
174
+ return tf.int32
175
+ if isinstance(space, gym.spaces.Box):
176
+ return tf.float32
177
+ raise NotImplementedError()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/in_graph_env.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The TensorFlow Agents Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Put an OpenAI Gym environment into the TensorFlow graph."""
15
+
16
+ from __future__ import absolute_import
17
+ from __future__ import division
18
+ from __future__ import print_function
19
+
20
+ import gym
21
+ try:
22
+ import tensorflow.compat.v1 as tf
23
+ except Exception:
24
+ import tensorflow as tf
25
+
26
+
27
+ class InGraphEnv(object):
28
+ """Put an OpenAI Gym environment into the TensorFlow graph.
29
+
30
+ The environment will be stepped and reset inside of the graph using
31
+ tf.py_func(). The current observation, action, reward, and done flag are held
32
+ in according variables.
33
+ """
34
+
35
+ def __init__(self, env):
36
+ """Put an OpenAI Gym environment into the TensorFlow graph.
37
+
38
+ Args:
39
+ env: OpenAI Gym environment.
40
+ """
41
+ self._env = env
42
+ observ_shape = self._parse_shape(self._env.observation_space)
43
+ observ_dtype = self._parse_dtype(self._env.observation_space)
44
+ action_shape = self._parse_shape(self._env.action_space)
45
+ action_dtype = self._parse_dtype(self._env.action_space)
46
+ with tf.name_scope('environment'):
47
+ self._observ = tf.Variable(tf.zeros(observ_shape, observ_dtype),
48
+ name='observ',
49
+ trainable=False)
50
+ self._action = tf.Variable(tf.zeros(action_shape, action_dtype),
51
+ name='action',
52
+ trainable=False)
53
+ self._reward = tf.Variable(0.0, dtype=tf.float32, name='reward', trainable=False)
54
+ self._done = tf.Variable(True, dtype=tf.bool, name='done', trainable=False)
55
+ self._step = tf.Variable(0, dtype=tf.int32, name='step', trainable=False)
56
+
57
+ def __getattr__(self, name):
58
+ """Forward unimplemented attributes to the original environment.
59
+
60
+ Args:
61
+ name: Attribute that was accessed.
62
+
63
+ Returns:
64
+ Value behind the attribute name in the wrapped environment.
65
+ """
66
+ return getattr(self._env, name)
67
+
68
+ def simulate(self, action):
69
+ """Step the environment.
70
+
71
+ The result of the step can be accessed from the variables defined below.
72
+
73
+ Args:
74
+ action: Tensor holding the action to apply.
75
+
76
+ Returns:
77
+ Operation.
78
+ """
79
+ with tf.name_scope('environment/simulate'):
80
+ if action.dtype in (tf.float16, tf.float32, tf.float64):
81
+ action = tf.check_numerics(action, 'action')
82
+ observ_dtype = self._parse_dtype(self._env.observation_space)
83
+ observ, reward, done = tf.py_func(lambda a: self._env.step(a)[:3], [action],
84
+ [observ_dtype, tf.float32, tf.bool],
85
+ name='step')
86
+ observ = tf.check_numerics(observ, 'observ')
87
+ reward = tf.check_numerics(reward, 'reward')
88
+ return tf.group(self._observ.assign(observ), self._action.assign(action),
89
+ self._reward.assign(reward), self._done.assign(done),
90
+ self._step.assign_add(1))
91
+
92
+ def reset(self):
93
+ """Reset the environment.
94
+
95
+ Returns:
96
+ Tensor of the current observation.
97
+ """
98
+ observ_dtype = self._parse_dtype(self._env.observation_space)
99
+ observ = tf.py_func(self._env.reset, [], observ_dtype, name='reset')
100
+ observ = tf.check_numerics(observ, 'observ')
101
+ with tf.control_dependencies(
102
+ [self._observ.assign(observ),
103
+ self._reward.assign(0),
104
+ self._done.assign(False)]):
105
+ return tf.identity(observ)
106
+
107
+ @property
108
+ def observ(self):
109
+ """Access the variable holding the current observation."""
110
+ return self._observ
111
+
112
+ @property
113
+ def action(self):
114
+ """Access the variable holding the last recieved action."""
115
+ return self._action
116
+
117
+ @property
118
+ def reward(self):
119
+ """Access the variable holding the current reward."""
120
+ return self._reward
121
+
122
+ @property
123
+ def done(self):
124
+ """Access the variable indicating whether the episode is done."""
125
+ return self._done
126
+
127
+ @property
128
+ def step(self):
129
+ """Access the variable containg total steps of this environment."""
130
+ return self._step
131
+
132
+ def _parse_shape(self, space):
133
+ """Get a tensor shape from a OpenAI Gym space.
134
+
135
+ Args:
136
+ space: Gym space.
137
+
138
+ Returns:
139
+ Shape tuple.
140
+ """
141
+ if isinstance(space, gym.spaces.Discrete):
142
+ return ()
143
+ if isinstance(space, gym.spaces.Box):
144
+ return space.shape
145
+ raise NotImplementedError()
146
+
147
+ def _parse_dtype(self, space):
148
+ """Get a tensor dtype from a OpenAI Gym space.
149
+
150
+ Args:
151
+ space: Gym space.
152
+
153
+ Returns:
154
+ TensorFlow data type.
155
+ """
156
+ if isinstance(space, gym.spaces.Discrete):
157
+ return tf.int32
158
+ if isinstance(space, gym.spaces.Box):
159
+ return tf.float32
160
+ raise NotImplementedError()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/loop.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The TensorFlow Agents Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Execute operations in a loop and coordinate logging and checkpoints."""
15
+
16
+ from __future__ import absolute_import
17
+ from __future__ import division
18
+ from __future__ import print_function
19
+
20
+ import collections
21
+ import os
22
+
23
+ try:
24
+ import tensorflow.compat.v1 as tf
25
+ except Exception:
26
+ import tensorflow as tf
27
+
28
+ from . import streaming_mean
29
+
30
+ _Phase = collections.namedtuple(
31
+ 'Phase', 'name, writer, op, batch, steps, feed, report_every, log_every,'
32
+ 'checkpoint_every')
33
+
34
+
35
+ class Loop(object):
36
+ """Execute operations in a loop and coordinate logging and checkpoints.
37
+
38
+ Supports multiple phases, that define their own operations to run, and
39
+ intervals for reporting scores, logging summaries, and storing checkpoints.
40
+ All class state is stored in-graph to properly recover from checkpoints.
41
+ """
42
+
43
+ def __init__(self, logdir, step=None, log=None, report=None, reset=None):
44
+ """Execute operations in a loop and coordinate logging and checkpoints.
45
+
46
+ The step, log, report, and report arguments will get created if not
47
+ provided. Reset is used to indicate switching to a new phase, so that the
48
+ model can start a new computation in case its computation is split over
49
+ multiple training steps.
50
+
51
+ Args:
52
+ logdir: Will contain checkpoints and summaries for each phase.
53
+ step: Variable of the global step (optional).
54
+ log: Tensor indicating to the model to compute summary tensors.
55
+ report: Tensor indicating to the loop to report the current mean score.
56
+ reset: Tensor indicating to the model to start a new computation.
57
+ """
58
+ self._logdir = logdir
59
+ self._step = (tf.Variable(0, False, name='global_step') if step is None else step)
60
+ self._log = tf.placeholder(tf.bool) if log is None else log
61
+ self._report = tf.placeholder(tf.bool) if report is None else report
62
+ self._reset = tf.placeholder(tf.bool) if reset is None else reset
63
+ self._phases = []
64
+
65
+ def add_phase(self,
66
+ name,
67
+ done,
68
+ score,
69
+ summary,
70
+ steps,
71
+ report_every=None,
72
+ log_every=None,
73
+ checkpoint_every=None,
74
+ feed=None):
75
+ """Add a phase to the loop protocol.
76
+
77
+ If the model breaks long computation into multiple steps, the done tensor
78
+ indicates whether the current score should be added to the mean counter.
79
+ For example, in reinforcement learning we only have a valid score at the
80
+ end of the episode.
81
+
82
+ Score and done tensors can either be scalars or vectors, to support
83
+ single and batched computations.
84
+
85
+ Args:
86
+ name: Name for the phase, used for the summary writer.
87
+ done: Tensor indicating whether current score can be used.
88
+ score: Tensor holding the current, possibly intermediate, score.
89
+ summary: Tensor holding summary string to write if not an empty string.
90
+ steps: Duration of the phase in steps.
91
+ report_every: Yield mean score every this number of steps.
92
+ log_every: Request summaries via `log` tensor every this number of steps.
93
+ checkpoint_every: Write checkpoint every this number of steps.
94
+ feed: Additional feed dictionary for the session run call.
95
+
96
+ Raises:
97
+ ValueError: Unknown rank for done or score tensors.
98
+ """
99
+ done = tf.convert_to_tensor(done, tf.bool)
100
+ score = tf.convert_to_tensor(score, tf.float32)
101
+ summary = tf.convert_to_tensor(summary, tf.string)
102
+ feed = feed or {}
103
+ if done.shape.ndims is None or score.shape.ndims is None:
104
+ raise ValueError("Rank of 'done' and 'score' tensors must be known.")
105
+ writer = self._logdir and tf.summary.FileWriter(
106
+ os.path.join(self._logdir, name), tf.get_default_graph(), flush_secs=60)
107
+ op = self._define_step(done, score, summary)
108
+ batch = 1 if score.shape.ndims == 0 else score.shape[0].value
109
+ self._phases.append(
110
+ _Phase(name, writer, op, batch, int(steps), feed, report_every, log_every,
111
+ checkpoint_every))
112
+
113
+ def run(self, sess, saver, max_step=None):
114
+ """Run the loop schedule for a specified number of steps.
115
+
116
+ Call the operation of the current phase until the global step reaches the
117
+ specified maximum step. Phases are repeated over and over in the order they
118
+ were added.
119
+
120
+ Args:
121
+ sess: Session to use to run the phase operation.
122
+ saver: Saver used for checkpointing.
123
+ max_step: Run the operations until the step reaches this limit.
124
+
125
+ Yields:
126
+ Reported mean scores.
127
+ """
128
+ global_step = sess.run(self._step)
129
+ steps_made = 1
130
+ while True:
131
+ if max_step and global_step >= max_step:
132
+ break
133
+ phase, epoch, steps_in = self._find_current_phase(global_step)
134
+ phase_step = epoch * phase.steps + steps_in
135
+ if steps_in % phase.steps < steps_made:
136
+ message = '\n' + ('-' * 50) + '\n'
137
+ message += 'Phase {} (phase step {}, global step {}).'
138
+ tf.logging.info(message.format(phase.name, phase_step, global_step))
139
+ # Populate book keeping tensors.
140
+ phase.feed[self._reset] = (steps_in < steps_made)
141
+ phase.feed[self._log] = (phase.writer and
142
+ self._is_every_steps(phase_step, phase.batch, phase.log_every))
143
+ phase.feed[self._report] = (self._is_every_steps(phase_step, phase.batch,
144
+ phase.report_every))
145
+ summary, mean_score, global_step, steps_made = sess.run(phase.op, phase.feed)
146
+ if self._is_every_steps(phase_step, phase.batch, phase.checkpoint_every):
147
+ self._store_checkpoint(sess, saver, global_step)
148
+ if self._is_every_steps(phase_step, phase.batch, phase.report_every):
149
+ yield mean_score
150
+ if summary and phase.writer:
151
+ # We want smaller phases to catch up at the beginnig of each epoch so
152
+ # that their graphs are aligned.
153
+ longest_phase = max(phase.steps for phase in self._phases)
154
+ summary_step = epoch * longest_phase + steps_in
155
+ phase.writer.add_summary(summary, summary_step)
156
+
157
+ def _is_every_steps(self, phase_step, batch, every):
158
+ """Determine whether a periodic event should happen at this step.
159
+
160
+ Args:
161
+ phase_step: The incrementing step.
162
+ batch: The number of steps progressed at once.
163
+ every: The interval of the periode.
164
+
165
+ Returns:
166
+ Boolean of whether the event should happen.
167
+ """
168
+ if not every:
169
+ return False
170
+ covered_steps = range(phase_step, phase_step + batch)
171
+ return any((step + 1) % every == 0 for step in covered_steps)
172
+
173
+ def _find_current_phase(self, global_step):
174
+ """Determine the current phase based on the global step.
175
+
176
+ This ensures continuing the correct phase after restoring checkoints.
177
+
178
+ Args:
179
+ global_step: The global number of steps performed across all phases.
180
+
181
+ Returns:
182
+ Tuple of phase object, epoch number, and phase steps within the epoch.
183
+ """
184
+ epoch_size = sum(phase.steps for phase in self._phases)
185
+ epoch = int(global_step // epoch_size)
186
+ steps_in = global_step % epoch_size
187
+ for phase in self._phases:
188
+ if steps_in < phase.steps:
189
+ return phase, epoch, steps_in
190
+ steps_in -= phase.steps
191
+
192
+ def _define_step(self, done, score, summary):
193
+ """Combine operations of a phase.
194
+
195
+ Keeps track of the mean score and when to report it.
196
+
197
+ Args:
198
+ done: Tensor indicating whether current score can be used.
199
+ score: Tensor holding the current, possibly intermediate, score.
200
+ summary: Tensor holding summary string to write if not an empty string.
201
+
202
+ Returns:
203
+ Tuple of summary tensor, mean score, and new global step. The mean score
204
+ is zero for non reporting steps.
205
+ """
206
+ if done.shape.ndims == 0:
207
+ done = done[None]
208
+ if score.shape.ndims == 0:
209
+ score = score[None]
210
+ score_mean = streaming_mean.StreamingMean((), tf.float32)
211
+ with tf.control_dependencies([done, score, summary]):
212
+ done_score = tf.gather(score, tf.where(done)[:, 0])
213
+ submit_score = tf.cond(tf.reduce_any(done), lambda: score_mean.submit(done_score), tf.no_op)
214
+ with tf.control_dependencies([submit_score]):
215
+ mean_score = tf.cond(self._report, score_mean.clear, float)
216
+ steps_made = tf.shape(score)[0]
217
+ next_step = self._step.assign_add(steps_made)
218
+ with tf.control_dependencies([mean_score, next_step]):
219
+ return tf.identity(summary), mean_score, next_step, steps_made
220
+
221
+ def _store_checkpoint(self, sess, saver, global_step):
222
+ """Store a checkpoint if a log directory was provided to the constructor.
223
+
224
+ The directory will be created if needed.
225
+
226
+ Args:
227
+ sess: Session containing variables to store.
228
+ saver: Saver used for checkpointing.
229
+ global_step: Step number of the checkpoint name.
230
+ """
231
+ if not self._logdir or not saver:
232
+ return
233
+ tf.gfile.MakeDirs(self._logdir)
234
+ filename = os.path.join(self._logdir, 'model.ckpt')
235
+ saver.save(sess, filename, global_step)
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/mock_algorithm.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The TensorFlow Agents Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Mock algorithm for testing reinforcement learning code."""
15
+
16
+ from __future__ import absolute_import
17
+ from __future__ import division
18
+ from __future__ import print_function
19
+ try:
20
+ import tensorflow.compat.v1 as tf
21
+ except Exception:
22
+ import tensorflow as tf
23
+
24
+
25
+ class MockAlgorithm(object):
26
+ """Produce random actions and empty summaries."""
27
+
28
+ def __init__(self, envs):
29
+ """Produce random actions and empty summaries.
30
+
31
+ Args:
32
+ envs: List of in-graph environments.
33
+ """
34
+ self._envs = envs
35
+
36
+ def begin_episode(self, unused_agent_indices):
37
+ return tf.constant('')
38
+
39
+ def perform(self, agent_indices, unused_observ):
40
+ shape = (tf.shape(agent_indices)[0],) + self._envs[0].action_space.shape
41
+ low = self._envs[0].action_space.low
42
+ high = self._envs[0].action_space.high
43
+ action = tf.random_uniform(shape) * (high - low) + low
44
+ return action, tf.constant('')
45
+
46
+ def experience(self, unused_agent_indices, *unused_transition):
47
+ return tf.constant('')
48
+
49
+ def end_episode(self, unused_agent_indices):
50
+ return tf.constant('')
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/mock_environment.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The TensorFlow Agents Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Mock environment for testing reinforcement learning code."""
15
+
16
+ from __future__ import absolute_import
17
+ from __future__ import division
18
+ from __future__ import print_function
19
+
20
+ import gym
21
+ import gym.spaces
22
+ import numpy as np
23
+
24
+
25
+ class MockEnvironment(object):
26
+ """Generate random agent input and keep track of statistics."""
27
+
28
+ def __init__(self, observ_shape, action_shape, min_duration, max_duration):
29
+ """Generate random agent input and keep track of statistics.
30
+
31
+ Args:
32
+ observ_shape: Shape for the random observations.
33
+ action_shape: Shape for the action space.
34
+ min_duration: Minimum number of steps per episode.
35
+ max_duration: Maximum number of steps per episode.
36
+
37
+ Attributes:
38
+ steps: List of actual simulated lengths for all episodes.
39
+ durations: List of decided lengths for all episodes.
40
+ """
41
+ self._observ_shape = observ_shape
42
+ self._action_shape = action_shape
43
+ self._min_duration = min_duration
44
+ self._max_duration = max_duration
45
+ self._random = np.random.RandomState(0)
46
+ self.steps = []
47
+ self.durations = []
48
+
49
+ @property
50
+ def observation_space(self):
51
+ low = np.zeros(self._observ_shape)
52
+ high = np.ones(self._observ_shape)
53
+ return gym.spaces.Box(low, high)
54
+
55
+ @property
56
+ def action_space(self):
57
+ low = np.zeros(self._action_shape)
58
+ high = np.ones(self._action_shape)
59
+ return gym.spaces.Box(low, high)
60
+
61
+ @property
62
+ def unwrapped(self):
63
+ return self
64
+
65
+ def step(self, action):
66
+ assert self.action_space.contains(action)
67
+ assert self.steps[-1] < self.durations[-1]
68
+ self.steps[-1] += 1
69
+ observ = self._current_observation()
70
+ reward = self._current_reward()
71
+ done = self.steps[-1] >= self.durations[-1]
72
+ info = {}
73
+ return observ, reward, done, info
74
+
75
+ def reset(self):
76
+ duration = self._random.randint(self._min_duration, self._max_duration + 1)
77
+ self.steps.append(0)
78
+ self.durations.append(duration)
79
+ return self._current_observation()
80
+
81
+ def _current_observation(self):
82
+ return self._random.uniform(0, 1, self._observ_shape)
83
+
84
+ def _current_reward(self):
85
+ return self._random.uniform(-1, 1)
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/simulate.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The TensorFlow Agents Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """In-graph simulation step of a vectorized algorithm with environments."""
15
+
16
+ from __future__ import absolute_import
17
+ from __future__ import division
18
+ from __future__ import print_function
19
+
20
+ try:
21
+ import tensorflow.compat.v1 as tf
22
+ except Exception:
23
+ import tensorflow as tf
24
+
25
+ from . import streaming_mean
26
+
27
+
28
+ def simulate(batch_env, algo, log=True, reset=False):
29
+ """Simulation step of a vecrotized algorithm with in-graph environments.
30
+
31
+ Integrates the operations implemented by the algorithm and the environments
32
+ into a combined operation.
33
+
34
+ Args:
35
+ batch_env: In-graph batch environment.
36
+ algo: Algorithm instance implementing required operations.
37
+ log: Tensor indicating whether to compute and return summaries.
38
+ reset: Tensor causing all environments to reset.
39
+
40
+ Returns:
41
+ Tuple of tensors containing done flags for the current episodes, possibly
42
+ intermediate scores for the episodes, and a summary tensor.
43
+ """
44
+
45
+ def _define_begin_episode(agent_indices):
46
+ """Reset environments, intermediate scores and durations for new episodes.
47
+
48
+ Args:
49
+ agent_indices: Tensor containing batch indices starting an episode.
50
+
51
+ Returns:
52
+ Summary tensor.
53
+ """
54
+ assert agent_indices.shape.ndims == 1
55
+ zero_scores = tf.zeros_like(agent_indices, tf.float32)
56
+ zero_durations = tf.zeros_like(agent_indices)
57
+ reset_ops = [
58
+ batch_env.reset(agent_indices),
59
+ tf.scatter_update(score, agent_indices, zero_scores),
60
+ tf.scatter_update(length, agent_indices, zero_durations)
61
+ ]
62
+ with tf.control_dependencies(reset_ops):
63
+ return algo.begin_episode(agent_indices)
64
+
65
+ def _define_step():
66
+ """Request actions from the algorithm and apply them to the environments.
67
+
68
+ Increments the lengths of all episodes and increases their scores by the
69
+ current reward. After stepping the environments, provides the full
70
+ transition tuple to the algorithm.
71
+
72
+ Returns:
73
+ Summary tensor.
74
+ """
75
+ prevob = batch_env.observ + 0 # Ensure a copy of the variable value.
76
+ agent_indices = tf.range(len(batch_env))
77
+ action, step_summary = algo.perform(agent_indices, prevob)
78
+ action.set_shape(batch_env.action.shape)
79
+ with tf.control_dependencies([batch_env.simulate(action)]):
80
+ add_score = score.assign_add(batch_env.reward)
81
+ inc_length = length.assign_add(tf.ones(len(batch_env), tf.int32))
82
+ with tf.control_dependencies([add_score, inc_length]):
83
+ agent_indices = tf.range(len(batch_env))
84
+ experience_summary = algo.experience(agent_indices, prevob, batch_env.action,
85
+ batch_env.reward, batch_env.done, batch_env.observ)
86
+ return tf.summary.merge([step_summary, experience_summary])
87
+
88
+ def _define_end_episode(agent_indices):
89
+ """Notify the algorithm of ending episodes.
90
+
91
+ Also updates the mean score and length counters used for summaries.
92
+
93
+ Args:
94
+ agent_indices: Tensor holding batch indices that end their episodes.
95
+
96
+ Returns:
97
+ Summary tensor.
98
+ """
99
+ assert agent_indices.shape.ndims == 1
100
+ submit_score = mean_score.submit(tf.gather(score, agent_indices))
101
+ submit_length = mean_length.submit(tf.cast(tf.gather(length, agent_indices), tf.float32))
102
+ with tf.control_dependencies([submit_score, submit_length]):
103
+ return algo.end_episode(agent_indices)
104
+
105
+ def _define_summaries():
106
+ """Reset the average score and duration, and return them as summary.
107
+
108
+ Returns:
109
+ Summary string.
110
+ """
111
+ score_summary = tf.cond(tf.logical_and(log, tf.cast(
112
+ mean_score.count, tf.bool)), lambda: tf.summary.scalar('mean_score', mean_score.clear()),
113
+ str)
114
+ length_summary = tf.cond(tf.logical_and(
115
+ log, tf.cast(mean_length.count,
116
+ tf.bool)), lambda: tf.summary.scalar('mean_length', mean_length.clear()), str)
117
+ return tf.summary.merge([score_summary, length_summary])
118
+
119
+ with tf.name_scope('simulate'):
120
+ log = tf.convert_to_tensor(log)
121
+ reset = tf.convert_to_tensor(reset)
122
+ with tf.variable_scope('simulate_temporary'):
123
+ score = tf.Variable(tf.zeros(len(batch_env), dtype=tf.float32), False, name='score')
124
+ length = tf.Variable(tf.zeros(len(batch_env), dtype=tf.int32), False, name='length')
125
+ mean_score = streaming_mean.StreamingMean((), tf.float32)
126
+ mean_length = streaming_mean.StreamingMean((), tf.float32)
127
+ agent_indices = tf.cond(reset, lambda: tf.range(len(batch_env)), lambda: tf.cast(
128
+ tf.where(batch_env.done)[:, 0], tf.int32))
129
+ begin_episode = tf.cond(tf.cast(tf.shape(agent_indices)[0],
130
+ tf.bool), lambda: _define_begin_episode(agent_indices), str)
131
+ with tf.control_dependencies([begin_episode]):
132
+ step = _define_step()
133
+ with tf.control_dependencies([step]):
134
+ agent_indices = tf.cast(tf.where(batch_env.done)[:, 0], tf.int32)
135
+ end_episode = tf.cond(tf.cast(tf.shape(agent_indices)[0],
136
+ tf.bool), lambda: _define_end_episode(agent_indices), str)
137
+ with tf.control_dependencies([end_episode]):
138
+ summary = tf.summary.merge([_define_summaries(), begin_episode, step, end_episode])
139
+ with tf.control_dependencies([summary]):
140
+ done, score = tf.identity(batch_env.done), tf.identity(score)
141
+ return done, score, summary
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/streaming_mean.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The TensorFlow Agents Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Compute a streaming estimation of the mean of submitted tensors."""
15
+
16
+ from __future__ import absolute_import
17
+ from __future__ import division
18
+ from __future__ import print_function
19
+ try:
20
+ import tensorflow.compat.v1 as tf
21
+ except Exception:
22
+ import tensorflow as tf
23
+
24
+
25
+ class StreamingMean(object):
26
+ """Compute a streaming estimation of the mean of submitted tensors."""
27
+
28
+ def __init__(self, shape, dtype):
29
+ """Specify the shape and dtype of the mean to be estimated.
30
+
31
+ Note that a float mean to zero submitted elements is NaN, while computing
32
+ the integer mean of zero elements raises a division by zero error.
33
+
34
+ Args:
35
+ shape: Shape of the mean to compute.
36
+ dtype: Data type of the mean to compute.
37
+ """
38
+ self._dtype = dtype
39
+ self._sum = tf.Variable(lambda: tf.zeros(shape, dtype), False)
40
+ self._count = tf.Variable(lambda: 0, trainable=False)
41
+
42
+ @property
43
+ def value(self):
44
+ """The current value of the mean."""
45
+ return self._sum / tf.cast(self._count, self._dtype)
46
+
47
+ @property
48
+ def count(self):
49
+ """The number of submitted samples."""
50
+ return self._count
51
+
52
+ def submit(self, value):
53
+ """Submit a single or batch tensor to refine the streaming mean."""
54
+ # Add a batch dimension if necessary.
55
+ if value.shape.ndims == self._sum.shape.ndims:
56
+ value = value[None, ...]
57
+ return tf.group(self._sum.assign_add(tf.reduce_sum(value, 0)),
58
+ self._count.assign_add(tf.shape(value)[0]))
59
+
60
+ def clear(self):
61
+ """Return the mean estimate and reset the streaming statistics."""
62
+ value = self._sum / tf.cast(self._count, self._dtype)
63
+ with tf.control_dependencies([value]):
64
+ reset_value = self._sum.assign(tf.zeros_like(self._sum))
65
+ reset_count = self._count.assign(0)
66
+ with tf.control_dependencies([reset_value, reset_count]):
67
+ return tf.identity(value)
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/tools/wrappers.py ADDED
@@ -0,0 +1,558 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The TensorFlow Agents Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Wrappers for OpenAI Gym environments."""
15
+
16
+ from __future__ import absolute_import
17
+ from __future__ import division
18
+ from __future__ import print_function
19
+
20
+ import atexit
21
+ import multiprocessing
22
+ import sys
23
+ import traceback
24
+
25
+ import gym
26
+ import gym.spaces
27
+ import numpy as np
28
+ try:
29
+ import tensorflow.compat.v1 as tf
30
+ except Exception:
31
+ import tensorflow as tf
32
+
33
+
34
+ class AutoReset(object):
35
+ """Automatically reset environment when the episode is done."""
36
+
37
+ def __init__(self, env):
38
+ self._env = env
39
+ self._done = True
40
+
41
+ def __getattr__(self, name):
42
+ return getattr(self._env, name)
43
+
44
+ def step(self, action):
45
+ if self._done:
46
+ observ, reward, done, info = self._env.reset(), 0.0, False, {}
47
+ else:
48
+ observ, reward, done, info = self._env.step(action)
49
+ self._done = done
50
+ return observ, reward, done, info
51
+
52
+ def reset(self):
53
+ self._done = False
54
+ return self._env.reset()
55
+
56
+
57
+ class ActionRepeat(object):
58
+ """Repeat the agent action multiple steps."""
59
+
60
+ def __init__(self, env, amount):
61
+ self._env = env
62
+ self._amount = amount
63
+
64
+ def __getattr__(self, name):
65
+ return getattr(self._env, name)
66
+
67
+ def step(self, action):
68
+ done = False
69
+ total_reward = 0
70
+ current_step = 0
71
+ while current_step < self._amount and not done:
72
+ observ, reward, done, info = self._env.step(action)
73
+ total_reward += reward
74
+ current_step += 1
75
+ return observ, total_reward, done, info
76
+
77
+
78
+ class RandomStart(object):
79
+ """Perform random number of random actions at the start of the episode."""
80
+
81
+ def __init__(self, env, max_steps):
82
+ self._env = env
83
+ self._max_steps = max_steps
84
+
85
+ def __getattr__(self, name):
86
+ return getattr(self._env, name)
87
+
88
+ def reset(self):
89
+ observ = self._env.reset()
90
+ random_steps = np.random.randint(0, self._max_steps)
91
+ for _ in range(random_steps):
92
+ action = self._env.action_space.sample()
93
+ observ, unused_reward, done, unused_info = self._env.step(action)
94
+ if done:
95
+ tf.logging.warning('Episode ended during random start.')
96
+ return self.reset()
97
+ return observ
98
+
99
+
100
+ class FrameHistory(object):
101
+ """Augment the observation with past observations."""
102
+
103
+ def __init__(self, env, past_indices, flatten):
104
+ """Augment the observation with past observations.
105
+
106
+ Implemented as a Numpy ring buffer holding the necessary past observations.
107
+
108
+ Args:
109
+ env: OpenAI Gym environment to wrap.
110
+ past_indices: List of non-negative integers indicating the time offsets
111
+ from the current time step of observations to include.
112
+ flatten: Concatenate the past observations rather than stacking them.
113
+
114
+ Raises:
115
+ KeyError: The current observation is not included in the indices.
116
+ """
117
+ if 0 not in past_indices:
118
+ raise KeyError('Past indices should include 0 for the current frame.')
119
+ self._env = env
120
+ self._past_indices = past_indices
121
+ self._step = 0
122
+ self._buffer = None
123
+ self._capacity = max(past_indices)
124
+ self._flatten = flatten
125
+
126
+ def __getattr__(self, name):
127
+ return getattr(self._env, name)
128
+
129
+ @property
130
+ def observation_space(self):
131
+ low = self._env.observation_space.low
132
+ high = self._env.observation_space.high
133
+ low = np.repeat(low[None, ...], len(self._past_indices), 0)
134
+ high = np.repeat(high[None, ...], len(self._past_indices), 0)
135
+ if self._flatten:
136
+ low = np.reshape(low, (-1,) + low.shape[2:])
137
+ high = np.reshape(high, (-1,) + high.shape[2:])
138
+ return gym.spaces.Box(low, high)
139
+
140
+ def step(self, action):
141
+ observ, reward, done, info = self._env.step(action)
142
+ self._step += 1
143
+ self._buffer[self._step % self._capacity] = observ
144
+ observ = self._select_frames()
145
+ return observ, reward, done, info
146
+
147
+ def reset(self):
148
+ observ = self._env.reset()
149
+ self._buffer = np.repeat(observ[None, ...], self._capacity, 0)
150
+ self._step = 0
151
+ return self._select_frames()
152
+
153
+ def _select_frames(self):
154
+ indices = [(self._step - index) % self._capacity for index in self._past_indices]
155
+ observ = self._buffer[indices]
156
+ if self._flatten:
157
+ observ = np.reshape(observ, (-1,) + observ.shape[2:])
158
+ return observ
159
+
160
+
161
+ class FrameDelta(object):
162
+ """Convert the observation to a difference from the previous observation."""
163
+
164
+ def __init__(self, env):
165
+ self._env = env
166
+ self._last = None
167
+
168
+ def __getattr__(self, name):
169
+ return getattr(self._env, name)
170
+
171
+ @property
172
+ def observation_space(self):
173
+ low = self._env.observation_space.low
174
+ high = self._env.observation_space.high
175
+ low, high = low - high, high - low
176
+ return gym.spaces.Box(low, high)
177
+
178
+ def step(self, action):
179
+ observ, reward, done, info = self._env.step(action)
180
+ delta = observ - self._last
181
+ self._last = observ
182
+ return delta, reward, done, info
183
+
184
+ def reset(self):
185
+ observ = self._env.reset()
186
+ self._last = observ
187
+ return observ
188
+
189
+
190
+ class RangeNormalize(object):
191
+ """Normalize the specialized observation and action ranges to [-1, 1]."""
192
+
193
+ def __init__(self, env, observ=None, action=None):
194
+ self._env = env
195
+ self._should_normalize_observ = (observ is not False and
196
+ self._is_finite(self._env.observation_space))
197
+ if observ is True and not self._should_normalize_observ:
198
+ raise ValueError('Cannot normalize infinite observation range.')
199
+ if observ is None and not self._should_normalize_observ:
200
+ tf.logging.info('Not normalizing infinite observation range.')
201
+ self._should_normalize_action = (action is not False and
202
+ self._is_finite(self._env.action_space))
203
+ if action is True and not self._should_normalize_action:
204
+ raise ValueError('Cannot normalize infinite action range.')
205
+ if action is None and not self._should_normalize_action:
206
+ tf.logging.info('Not normalizing infinite action range.')
207
+
208
+ def __getattr__(self, name):
209
+ return getattr(self._env, name)
210
+
211
+ @property
212
+ def observation_space(self):
213
+ space = self._env.observation_space
214
+ if not self._should_normalize_observ:
215
+ return space
216
+ return gym.spaces.Box(-np.ones(space.shape), np.ones(space.shape))
217
+
218
+ @property
219
+ def action_space(self):
220
+ space = self._env.action_space
221
+ if not self._should_normalize_action:
222
+ return space
223
+ return gym.spaces.Box(-np.ones(space.shape), np.ones(space.shape))
224
+
225
+ def step(self, action):
226
+ if self._should_normalize_action:
227
+ action = self._denormalize_action(action)
228
+ observ, reward, done, info = self._env.step(action)
229
+ if self._should_normalize_observ:
230
+ observ = self._normalize_observ(observ)
231
+ return observ, reward, done, info
232
+
233
+ def reset(self):
234
+ observ = self._env.reset()
235
+ if self._should_normalize_observ:
236
+ observ = self._normalize_observ(observ)
237
+ return observ
238
+
239
+ def _denormalize_action(self, action):
240
+ min_ = self._env.action_space.low
241
+ max_ = self._env.action_space.high
242
+ action = (action + 1) / 2 * (max_ - min_) + min_
243
+ return action
244
+
245
+ def _normalize_observ(self, observ):
246
+ min_ = self._env.observation_space.low
247
+ max_ = self._env.observation_space.high
248
+ observ = 2 * (observ - min_) / (max_ - min_) - 1
249
+ return observ
250
+
251
+ def _is_finite(self, space):
252
+ return np.isfinite(space.low).all() and np.isfinite(space.high).all()
253
+
254
+
255
+ class ClipAction(object):
256
+ """Clip out of range actions to the action space of the environment."""
257
+
258
+ def __init__(self, env):
259
+ self._env = env
260
+
261
+ def __getattr__(self, name):
262
+ return getattr(self._env, name)
263
+
264
+ @property
265
+ def action_space(self):
266
+ shape = self._env.action_space.shape
267
+ return gym.spaces.Box(-np.inf * np.ones(shape), np.inf * np.ones(shape))
268
+
269
+ def step(self, action):
270
+ action_space = self._env.action_space
271
+ action = np.clip(action, action_space.low, action_space.high)
272
+ return self._env.step(action)
273
+
274
+
275
+ class LimitDuration(object):
276
+ """End episodes after specified number of steps."""
277
+
278
+ def __init__(self, env, duration):
279
+ self._env = env
280
+ self._duration = duration
281
+ self._step = None
282
+
283
+ def __getattr__(self, name):
284
+ return getattr(self._env, name)
285
+
286
+ def step(self, action):
287
+ if self._step is None:
288
+ raise RuntimeError('Must reset environment.')
289
+ observ, reward, done, info = self._env.step(action)
290
+ self._step += 1
291
+ if self._step >= self._duration:
292
+ done = True
293
+ self._step = None
294
+ return observ, reward, done, info
295
+
296
+ def reset(self):
297
+ self._step = 0
298
+ return self._env.reset()
299
+
300
+
301
+ class ExternalProcess(object):
302
+ """Step environment in a separate process for lock free paralellism."""
303
+
304
+ # Message types for communication via the pipe.
305
+ _ACCESS = 1
306
+ _CALL = 2
307
+ _RESULT = 3
308
+ _EXCEPTION = 4
309
+ _CLOSE = 5
310
+
311
+ def __init__(self, constructor):
312
+ """Step environment in a separate process for lock free paralellism.
313
+
314
+ The environment will be created in the external process by calling the
315
+ specified callable. This can be an environment class, or a function
316
+ creating the environment and potentially wrapping it. The returned
317
+ environment should not access global variables.
318
+
319
+ Args:
320
+ constructor: Callable that creates and returns an OpenAI gym environment.
321
+
322
+ Attributes:
323
+ observation_space: The cached observation space of the environment.
324
+ action_space: The cached action space of the environment.
325
+ """
326
+ self._conn, conn = multiprocessing.Pipe()
327
+ self._process = multiprocessing.Process(target=self._worker, args=(constructor, conn))
328
+ atexit.register(self.close)
329
+ self._process.start()
330
+ self._observ_space = None
331
+ self._action_space = None
332
+
333
+ @property
334
+ def observation_space(self):
335
+ if not self._observ_space:
336
+ self._observ_space = self.__getattr__('observation_space')
337
+ return self._observ_space
338
+
339
+ @property
340
+ def action_space(self):
341
+ if not self._action_space:
342
+ self._action_space = self.__getattr__('action_space')
343
+ return self._action_space
344
+
345
+ def __getattr__(self, name):
346
+ """Request an attribute from the environment.
347
+
348
+ Note that this involves communication with the external process, so it can
349
+ be slow.
350
+
351
+ Args:
352
+ name: Attribute to access.
353
+
354
+ Returns:
355
+ Value of the attribute.
356
+ """
357
+ self._conn.send((self._ACCESS, name))
358
+ return self._receive()
359
+
360
+ def call(self, name, *args, **kwargs):
361
+ """Asynchronously call a method of the external environment.
362
+
363
+ Args:
364
+ name: Name of the method to call.
365
+ *args: Positional arguments to forward to the method.
366
+ **kwargs: Keyword arguments to forward to the method.
367
+
368
+ Returns:
369
+ Promise object that blocks and provides the return value when called.
370
+ """
371
+ payload = name, args, kwargs
372
+ self._conn.send((self._CALL, payload))
373
+ return self._receive
374
+
375
+ def close(self):
376
+ """Send a close message to the external process and join it."""
377
+ try:
378
+ self._conn.send((self._CLOSE, None))
379
+ self._conn.close()
380
+ except IOError:
381
+ # The connection was already closed.
382
+ pass
383
+ self._process.join()
384
+
385
+ def step(self, action, blocking=True):
386
+ """Step the environment.
387
+
388
+ Args:
389
+ action: The action to apply to the environment.
390
+ blocking: Whether to wait for the result.
391
+
392
+ Returns:
393
+ Transition tuple when blocking, otherwise callable that returns the
394
+ transition tuple.
395
+ """
396
+ promise = self.call('step', action)
397
+ if blocking:
398
+ return promise()
399
+ else:
400
+ return promise
401
+
402
+ def reset(self, blocking=True):
403
+ """Reset the environment.
404
+
405
+ Args:
406
+ blocking: Whether to wait for the result.
407
+
408
+ Returns:
409
+ New observation when blocking, otherwise callable that returns the new
410
+ observation.
411
+ """
412
+ promise = self.call('reset')
413
+ if blocking:
414
+ return promise()
415
+ else:
416
+ return promise
417
+
418
+ def _receive(self):
419
+ """Wait for a message from the worker process and return its payload.
420
+
421
+ Raises:
422
+ Exception: An exception was raised inside the worker process.
423
+ KeyError: The reveived message is of an unknown type.
424
+
425
+ Returns:
426
+ Payload object of the message.
427
+ """
428
+ message, payload = self._conn.recv()
429
+ # Re-raise exceptions in the main process.
430
+ if message == self._EXCEPTION:
431
+ stacktrace = payload
432
+ raise Exception(stacktrace)
433
+ if message == self._RESULT:
434
+ return payload
435
+ raise KeyError('Received message of unexpected type {}'.format(message))
436
+
437
+ def _worker(self, constructor, conn):
438
+ """The process waits for actions and sends back environment results.
439
+
440
+ Args:
441
+ constructor: Constructor for the OpenAI Gym environment.
442
+ conn: Connection for communication to the main process.
443
+ """
444
+ try:
445
+ env = constructor()
446
+ while True:
447
+ try:
448
+ # Only block for short times to have keyboard exceptions be raised.
449
+ if not conn.poll(0.1):
450
+ continue
451
+ message, payload = conn.recv()
452
+ except (EOFError, KeyboardInterrupt):
453
+ break
454
+ if message == self._ACCESS:
455
+ name = payload
456
+ result = getattr(env, name)
457
+ conn.send((self._RESULT, result))
458
+ continue
459
+ if message == self._CALL:
460
+ name, args, kwargs = payload
461
+ result = getattr(env, name)(*args, **kwargs)
462
+ conn.send((self._RESULT, result))
463
+ continue
464
+ if message == self._CLOSE:
465
+ assert payload is None
466
+ break
467
+ raise KeyError('Received message of unknown type {}'.format(message))
468
+ except Exception: # pylint: disable=broad-except
469
+ stacktrace = ''.join(traceback.format_exception(*sys.exc_info()))
470
+ tf.logging.error('Error in environment process: {}'.format(stacktrace))
471
+ conn.send((self._EXCEPTION, stacktrace))
472
+ conn.close()
473
+
474
+
475
+ class ConvertTo32Bit(object):
476
+ """Convert data types of an OpenAI Gym environment to 32 bit."""
477
+
478
+ def __init__(self, env):
479
+ """Convert data types of an OpenAI Gym environment to 32 bit.
480
+
481
+ Args:
482
+ env: OpenAI Gym environment.
483
+ """
484
+ self._env = env
485
+
486
+ def __getattr__(self, name):
487
+ """Forward unimplemented attributes to the original environment.
488
+
489
+ Args:
490
+ name: Attribute that was accessed.
491
+
492
+ Returns:
493
+ Value behind the attribute name in the wrapped environment.
494
+ """
495
+ return getattr(self._env, name)
496
+
497
+ def step(self, action):
498
+ """Forward action to the wrapped environment.
499
+
500
+ Args:
501
+ action: Action to apply to the environment.
502
+
503
+ Raises:
504
+ ValueError: Invalid action.
505
+
506
+ Returns:
507
+ Converted observation, converted reward, done flag, and info object.
508
+ """
509
+ observ, reward, done, info = self._env.step(action)
510
+ observ = self._convert_observ(observ)
511
+ reward = self._convert_reward(reward)
512
+ return observ, reward, done, info
513
+
514
+ def reset(self):
515
+ """Reset the environment and convert the resulting observation.
516
+
517
+ Returns:
518
+ Converted observation.
519
+ """
520
+ observ = self._env.reset()
521
+ observ = self._convert_observ(observ)
522
+ return observ
523
+
524
+ def _convert_observ(self, observ):
525
+ """Convert the observation to 32 bits.
526
+
527
+ Args:
528
+ observ: Numpy observation.
529
+
530
+ Raises:
531
+ ValueError: Observation contains infinite values.
532
+
533
+ Returns:
534
+ Numpy observation with 32-bit data type.
535
+ """
536
+ if not np.isfinite(observ).all():
537
+ raise ValueError('Infinite observation encountered.')
538
+ if observ.dtype == np.float64:
539
+ return observ.astype(np.float32)
540
+ if observ.dtype == np.int64:
541
+ return observ.astype(np.int32)
542
+ return observ
543
+
544
+ def _convert_reward(self, reward):
545
+ """Convert the reward to 32 bits.
546
+
547
+ Args:
548
+ reward: Numpy reward.
549
+
550
+ Raises:
551
+ ValueError: Rewards contain infinite values.
552
+
553
+ Returns:
554
+ Numpy reward with 32-bit data type.
555
+ """
556
+ if not np.isfinite(reward).all():
557
+ raise ValueError('Infinite reward encountered.')
558
+ return np.array(reward, dtype=np.float32)
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/train_ppo.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The TensorFlow Agents Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ r"""Script to train a batch reinforcement learning algorithm.
15
+
16
+ Command line:
17
+
18
+ python3 -m agents.scripts.train --logdir=/path/to/logdir --config=pendulum
19
+ """
20
+
21
+ from __future__ import absolute_import
22
+ from __future__ import division
23
+ from __future__ import print_function
24
+
25
+ import datetime
26
+ import os
27
+
28
+ import gym
29
+ try:
30
+ import tensorflow.compat.v1 as tf
31
+ except Exception:
32
+ import tensorflow as tf
33
+
34
+ from . import tools
35
+ from . import configs
36
+ from . import utility
37
+
38
+
39
+ def _create_environment(config):
40
+ """Constructor for an instance of the environment.
41
+
42
+ Args:
43
+ config: Object providing configurations via attributes.
44
+
45
+ Returns:
46
+ Wrapped OpenAI Gym environment.
47
+ """
48
+ if isinstance(config.env, str):
49
+ env = gym.make(config.env)
50
+ else:
51
+ env = config.env()
52
+ if config.max_length:
53
+ env = tools.wrappers.LimitDuration(env, config.max_length)
54
+ env = tools.wrappers.RangeNormalize(env)
55
+ env = tools.wrappers.ClipAction(env)
56
+ env = tools.wrappers.ConvertTo32Bit(env)
57
+ return env
58
+
59
+
60
+ def _define_loop(graph, logdir, train_steps, eval_steps):
61
+ """Create and configure a training loop with training and evaluation phases.
62
+
63
+ Args:
64
+ graph: Object providing graph elements via attributes.
65
+ logdir: Log directory for storing checkpoints and summaries.
66
+ train_steps: Number of training steps per epoch.
67
+ eval_steps: Number of evaluation steps per epoch.
68
+
69
+ Returns:
70
+ Loop object.
71
+ """
72
+ loop = tools.Loop(logdir, graph.step, graph.should_log, graph.do_report, graph.force_reset)
73
+ loop.add_phase('train',
74
+ graph.done,
75
+ graph.score,
76
+ graph.summary,
77
+ train_steps,
78
+ report_every=train_steps,
79
+ log_every=train_steps // 2,
80
+ checkpoint_every=None,
81
+ feed={graph.is_training: True})
82
+ loop.add_phase('eval',
83
+ graph.done,
84
+ graph.score,
85
+ graph.summary,
86
+ eval_steps,
87
+ report_every=eval_steps,
88
+ log_every=eval_steps // 2,
89
+ checkpoint_every=10 * eval_steps,
90
+ feed={graph.is_training: False})
91
+ return loop
92
+
93
+
94
+ def train(config, env_processes):
95
+ """Training and evaluation entry point yielding scores.
96
+
97
+ Resolves some configuration attributes, creates environments, graph, and
98
+ training loop. By default, assigns all operations to the CPU.
99
+
100
+ Args:
101
+ config: Object providing configurations via attributes.
102
+ env_processes: Whether to step environments in separate processes.
103
+
104
+ Yields:
105
+ Evaluation scores.
106
+ """
107
+ tf.reset_default_graph()
108
+ if config.update_every % config.num_agents:
109
+ tf.logging.warn('Number of agents should divide episodes per update.')
110
+ with tf.device('/cpu:0'):
111
+ batch_env = utility.define_batch_env(lambda: _create_environment(config), config.num_agents,
112
+ env_processes)
113
+ graph = utility.define_simulation_graph(batch_env, config.algorithm, config)
114
+ loop = _define_loop(graph, config.logdir, config.update_every * config.max_length,
115
+ config.eval_episodes * config.max_length)
116
+ total_steps = int(config.steps / config.update_every *
117
+ (config.update_every + config.eval_episodes))
118
+ # Exclude episode related variables since the Python state of environments is
119
+ # not checkpointed and thus new episodes start after resuming.
120
+ saver = utility.define_saver(exclude=(r'.*_temporary/.*',))
121
+ sess_config = tf.ConfigProto(allow_soft_placement=True)
122
+ sess_config.gpu_options.allow_growth = True
123
+ with tf.Session(config=sess_config) as sess:
124
+ utility.initialize_variables(sess, saver, config.logdir)
125
+ for score in loop.run(sess, saver, total_steps):
126
+ yield score
127
+ batch_env.close()
128
+
129
+
130
+ def main(_):
131
+ """Create or load configuration and launch the trainer."""
132
+ utility.set_up_logging()
133
+ if not FLAGS.config:
134
+ raise KeyError('You must specify a configuration.')
135
+ logdir = FLAGS.logdir and os.path.expanduser(
136
+ os.path.join(FLAGS.logdir, '{}-{}'.format(FLAGS.timestamp, FLAGS.config)))
137
+ try:
138
+ config = utility.load_config(logdir)
139
+ except IOError:
140
+ config = tools.AttrDict(getattr(configs, FLAGS.config)())
141
+ config = utility.save_config(config, logdir)
142
+ for score in train(config, FLAGS.env_processes):
143
+ tf.logging.info('Score {}.'.format(score))
144
+
145
+
146
+ if __name__ == '__main__':
147
+ FLAGS = tf.app.flags.FLAGS
148
+ tf.app.flags.DEFINE_string('logdir', None, 'Base directory to store logs.')
149
+ tf.app.flags.DEFINE_string('timestamp',
150
+ datetime.datetime.now().strftime('%Y%m%dT%H%M%S'),
151
+ 'Sub directory to store logs.')
152
+ tf.app.flags.DEFINE_string('config', None, 'Configuration to execute.')
153
+ tf.app.flags.DEFINE_boolean('env_processes', True,
154
+ 'Step environments in separate processes to circumvent the GIL.')
155
+ tf.app.run()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/utility.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The TensorFlow Agents Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Utilities for using reinforcement learning algorithms."""
15
+
16
+ from __future__ import absolute_import
17
+ from __future__ import division
18
+ from __future__ import print_function
19
+
20
+ import logging
21
+ import os
22
+ import re
23
+
24
+ import ruamel.yaml as yaml
25
+ try:
26
+ import tensorflow.compat.v1 as tf
27
+ except Exception:
28
+ import tensorflow as tf
29
+
30
+ from . import tools
31
+
32
+
33
+ def define_simulation_graph(batch_env, algo_cls, config):
34
+ """Define the algortihm and environment interaction.
35
+
36
+ Args:
37
+ batch_env: In-graph environments object.
38
+ algo_cls: Constructor of a batch algorithm.
39
+ config: Configuration object for the algorithm.
40
+
41
+ Returns:
42
+ Object providing graph elements via attributes.
43
+ """
44
+ # pylint: disable=unused-variable
45
+ step = tf.Variable(0, False, dtype=tf.int32, name='global_step')
46
+ is_training = tf.placeholder(tf.bool, name='is_training')
47
+ should_log = tf.placeholder(tf.bool, name='should_log')
48
+ do_report = tf.placeholder(tf.bool, name='do_report')
49
+ force_reset = tf.placeholder(tf.bool, name='force_reset')
50
+ algo = algo_cls(batch_env, step, is_training, should_log, config)
51
+ done, score, summary = tools.simulate(batch_env, algo, should_log, force_reset)
52
+ message = 'Graph contains {} trainable variables.'
53
+ tf.logging.info(message.format(tools.count_weights()))
54
+ # pylint: enable=unused-variable
55
+ return tools.AttrDict(locals())
56
+
57
+
58
+ def define_batch_env(constructor, num_agents, env_processes):
59
+ """Create environments and apply all desired wrappers.
60
+
61
+ Args:
62
+ constructor: Constructor of an OpenAI gym environment.
63
+ num_agents: Number of environments to combine in the batch.
64
+ env_processes: Whether to step environment in external processes.
65
+
66
+ Returns:
67
+ In-graph environments object.
68
+ """
69
+ with tf.variable_scope('environments'):
70
+ if env_processes:
71
+ envs = [tools.wrappers.ExternalProcess(constructor) for _ in range(num_agents)]
72
+ else:
73
+ envs = [constructor() for _ in range(num_agents)]
74
+ batch_env = tools.BatchEnv(envs, blocking=not env_processes)
75
+ batch_env = tools.InGraphBatchEnv(batch_env)
76
+ return batch_env
77
+
78
+
79
+ def define_saver(exclude=None):
80
+ """Create a saver for the variables we want to checkpoint.
81
+
82
+ Args:
83
+ exclude: List of regexes to match variable names to exclude.
84
+
85
+ Returns:
86
+ Saver object.
87
+ """
88
+ variables = []
89
+ exclude = exclude or []
90
+ exclude = [re.compile(regex) for regex in exclude]
91
+ for variable in tf.global_variables():
92
+ if any(regex.match(variable.name) for regex in exclude):
93
+ continue
94
+ variables.append(variable)
95
+ saver = tf.train.Saver(variables, keep_checkpoint_every_n_hours=5)
96
+ return saver
97
+
98
+
99
+ def initialize_variables(sess, saver, logdir, checkpoint=None, resume=None):
100
+ """Initialize or restore variables from a checkpoint if available.
101
+
102
+ Args:
103
+ sess: Session to initialize variables in.
104
+ saver: Saver to restore variables.
105
+ logdir: Directory to search for checkpoints.
106
+ checkpoint: Specify what checkpoint name to use; defaults to most recent.
107
+ resume: Whether to expect recovering a checkpoint or starting a new run.
108
+
109
+ Raises:
110
+ ValueError: If resume expected but no log directory specified.
111
+ RuntimeError: If no resume expected but a checkpoint was found.
112
+ """
113
+ sess.run(tf.group(tf.local_variables_initializer(), tf.global_variables_initializer()))
114
+ if resume and not (logdir or checkpoint):
115
+ raise ValueError('Need to specify logdir to resume a checkpoint.')
116
+ if logdir:
117
+ state = tf.train.get_checkpoint_state(logdir)
118
+ if checkpoint:
119
+ checkpoint = os.path.join(logdir, checkpoint)
120
+ if not checkpoint and state and state.model_checkpoint_path:
121
+ checkpoint = state.model_checkpoint_path
122
+ if checkpoint and resume is False:
123
+ message = 'Found unexpected checkpoint when starting a new run.'
124
+ raise RuntimeError(message)
125
+ if checkpoint:
126
+ saver.restore(sess, checkpoint)
127
+
128
+
129
+ def save_config(config, logdir=None):
130
+ """Save a new configuration by name.
131
+
132
+ If a logging directory is specified, is will be created and the configuration
133
+ will be stored there. Otherwise, a log message will be printed.
134
+
135
+ Args:
136
+ config: Configuration object.
137
+ logdir: Location for writing summaries and checkpoints if specified.
138
+
139
+ Returns:
140
+ Configuration object.
141
+ """
142
+ if logdir:
143
+ with config.unlocked:
144
+ config.logdir = logdir
145
+ message = 'Start a new run and write summaries and checkpoints to {}.'
146
+ tf.logging.info(message.format(config.logdir))
147
+ tf.gfile.MakeDirs(config.logdir)
148
+ config_path = os.path.join(config.logdir, 'config.yaml')
149
+ with tf.gfile.GFile(config_path, 'w') as file_:
150
+ yaml.dump(config, file_, default_flow_style=False)
151
+ else:
152
+ message = ('Start a new run without storing summaries and checkpoints since no '
153
+ 'logging directory was specified.')
154
+ tf.logging.info(message)
155
+ return config
156
+
157
+
158
+ def load_config(logdir):
159
+ """Load a configuration from the log directory.
160
+
161
+ Args:
162
+ logdir: The logging directory containing the configuration file.
163
+
164
+ Raises:
165
+ IOError: The logging directory does not contain a configuration file.
166
+
167
+ Returns:
168
+ Configuration object.
169
+ """
170
+ config_path = logdir and os.path.join(logdir, 'config.yaml')
171
+ if not config_path or not tf.gfile.Exists(config_path):
172
+ message = ('Cannot resume an existing run since the logging directory does not '
173
+ 'contain a configuration file.')
174
+ raise IOError(message)
175
+ with tf.gfile.FastGFile(config_path, 'r') as file_:
176
+ config = yaml.load(file_, Loader=yaml.Loader)
177
+ message = 'Resume run and write summaries and checkpoints to {}.'
178
+ tf.logging.info(message.format(config.logdir))
179
+ return config
180
+
181
+
182
+ def set_up_logging():
183
+ """Configure the TensorFlow logger."""
184
+ tf.logging.set_verbosity(tf.logging.INFO)
185
+ logging.getLogger('tensorflow').propagate = False
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/agents/visualize_ppo.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The TensorFlow Agents Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ r"""Script to render videos of the Proximal Policy Gradient algorithm.
15
+
16
+ Command line:
17
+
18
+ python3 -m agents.scripts.visualize \
19
+ --logdir=/path/to/logdir/<time>-<config> --outdir=/path/to/outdir/
20
+ """
21
+
22
+ from __future__ import absolute_import
23
+ from __future__ import division
24
+ from __future__ import print_function
25
+
26
+ import os
27
+
28
+ import gym
29
+ from gym import wrappers
30
+ try:
31
+ import tensorflow.compat.v1 as tf
32
+ except Exception:
33
+ import tensorflow as tf
34
+
35
+ from . import tools
36
+ from . import utility
37
+
38
+
39
+ def _create_environment(config, outdir):
40
+ """Constructor for an instance of the environment.
41
+
42
+ Args:
43
+ config: Object providing configurations via attributes.
44
+ outdir: Directory to store videos in.
45
+
46
+ Returns:
47
+ Wrapped OpenAI Gym environment.
48
+ """
49
+ if isinstance(config.env, str):
50
+ env = gym.make(config.env)
51
+ else:
52
+ env = config.env()
53
+ # Ensure that the environment has the specification attribute set as expected
54
+ # by the monitor wrapper.
55
+ if not hasattr(env, 'spec'):
56
+ setattr(env, 'spec', getattr(env, 'spec', None))
57
+ if config.max_length:
58
+ env = tools.wrappers.LimitDuration(env, config.max_length)
59
+ env = gym.wrappers.Monitor(env, outdir, lambda unused_episode_number: True)
60
+ env = tools.wrappers.RangeNormalize(env)
61
+ env = tools.wrappers.ClipAction(env)
62
+ env = tools.wrappers.ConvertTo32Bit(env)
63
+ return env
64
+
65
+
66
+ def _define_loop(graph, eval_steps):
67
+ """Create and configure an evaluation loop.
68
+
69
+ Args:
70
+ graph: Object providing graph elements via attributes.
71
+ eval_steps: Number of evaluation steps per epoch.
72
+
73
+ Returns:
74
+ Loop object.
75
+ """
76
+ loop = tools.Loop(None, graph.step, graph.should_log, graph.do_report, graph.force_reset)
77
+ loop.add_phase('eval',
78
+ graph.done,
79
+ graph.score,
80
+ graph.summary,
81
+ eval_steps,
82
+ report_every=eval_steps,
83
+ log_every=None,
84
+ checkpoint_every=None,
85
+ feed={graph.is_training: False})
86
+ return loop
87
+
88
+
89
+ def visualize(logdir, outdir, num_agents, num_episodes, checkpoint=None, env_processes=True):
90
+ """Recover checkpoint and render videos from it.
91
+
92
+ Args:
93
+ logdir: Logging directory of the trained algorithm.
94
+ outdir: Directory to store rendered videos in.
95
+ num_agents: Number of environments to simulate in parallel.
96
+ num_episodes: Total number of episodes to simulate.
97
+ checkpoint: Checkpoint name to load; defaults to most recent.
98
+ env_processes: Whether to step environments in separate processes.
99
+ """
100
+ config = utility.load_config(logdir)
101
+ with tf.device('/cpu:0'):
102
+ batch_env = utility.define_batch_env(lambda: _create_environment(config, outdir), num_agents,
103
+ env_processes)
104
+ graph = utility.define_simulation_graph(batch_env, config.algorithm, config)
105
+ total_steps = num_episodes * config.max_length
106
+ loop = _define_loop(graph, total_steps)
107
+ saver = utility.define_saver(exclude=(r'.*_temporary/.*', r'global_step'))
108
+ sess_config = tf.ConfigProto(allow_soft_placement=True)
109
+ sess_config.gpu_options.allow_growth = True
110
+ with tf.Session(config=sess_config) as sess:
111
+ utility.initialize_variables(sess, saver, config.logdir, checkpoint, resume=True)
112
+ for unused_score in loop.run(sess, saver, total_steps):
113
+ pass
114
+ batch_env.close()
115
+
116
+
117
+ def main(_):
118
+ """Load a trained algorithm and render videos."""
119
+ utility.set_up_logging()
120
+ if not FLAGS.logdir or not FLAGS.outdir:
121
+ raise KeyError('You must specify logging and outdirs directories.')
122
+ FLAGS.logdir = os.path.expanduser(FLAGS.logdir)
123
+ FLAGS.outdir = os.path.expanduser(FLAGS.outdir)
124
+ visualize(FLAGS.logdir, FLAGS.outdir, FLAGS.num_agents, FLAGS.num_episodes, FLAGS.checkpoint,
125
+ FLAGS.env_processes)
126
+
127
+
128
+ if __name__ == '__main__':
129
+ FLAGS = tf.app.flags.FLAGS
130
+ tf.app.flags.DEFINE_string('logdir', None, 'Directory to the checkpoint of a training run.')
131
+ tf.app.flags.DEFINE_string('outdir', None, 'Local directory for storing the monitoring outdir.')
132
+ tf.app.flags.DEFINE_string('checkpoint', None,
133
+ 'Checkpoint name to load; defaults to most recent.')
134
+ tf.app.flags.DEFINE_integer('num_agents', 1, 'How many environments to step in parallel.')
135
+ tf.app.flags.DEFINE_integer('num_episodes', 5, 'Minimum number of episodes to render.')
136
+ tf.app.flags.DEFINE_boolean('env_processes', True,
137
+ 'Step environments in separate processes to circumvent the GIL.')
138
+ tf.app.run()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from . import enjoy_kuka_grasping
2
+ from . import enjoy_pybullet_cartpole
3
+ from . import enjoy_pybullet_racecar
4
+ from . import enjoy_pybullet_zed_racecar
5
+ from . import train_kuka_cam_grasping
6
+ from . import train_kuka_grasping
7
+ from . import train_pybullet_cartpole
8
+ from . import train_pybullet_racecar
9
+ from . import train_pybullet_zed_racecar
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (817 Bytes). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/enjoy_kuka_diverse_object_grasping.cpython-311.pyc ADDED
Binary file (3.68 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/enjoy_kuka_grasping.cpython-311.pyc ADDED
Binary file (2.03 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/enjoy_pybullet_cartpole.cpython-311.pyc ADDED
Binary file (2.21 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/enjoy_pybullet_racecar.cpython-311.pyc ADDED
Binary file (2.04 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/enjoy_pybullet_zed_racecar.cpython-311.pyc ADDED
Binary file (2.04 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/train_kuka_cam_grasping.cpython-311.pyc ADDED
Binary file (2.39 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/train_kuka_grasping.cpython-311.pyc ADDED
Binary file (2.25 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/train_pybullet_cartpole.cpython-311.pyc ADDED
Binary file (2.19 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/train_pybullet_racecar.cpython-311.pyc ADDED
Binary file (2.26 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/__pycache__/train_pybullet_zed_racecar.cpython-311.pyc ADDED
Binary file (2.4 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/enjoy_kuka_diverse_object_grasping.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Runs a random policy for the random object KukaDiverseObjectEnv.
2
+ """
3
+
4
+ import os, inspect
5
+ import numpy as np
6
+
7
+ currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
8
+ parentdir = os.path.dirname(os.path.dirname(currentdir))
9
+ os.sys.path.insert(0, parentdir)
10
+
11
+ import gym
12
+ from pybullet_envs.bullet.kuka_diverse_object_gym_env import KukaDiverseObjectEnv
13
+ from gym import spaces
14
+
15
+
16
+ class ContinuousDownwardBiasPolicy(object):
17
+ """Policy which takes continuous actions, and is biased to move down.
18
+ """
19
+
20
+ def __init__(self, height_hack_prob=0.9):
21
+ """Initializes the DownwardBiasPolicy.
22
+
23
+ Args:
24
+ height_hack_prob: The probability of moving down at every move.
25
+ """
26
+ self._height_hack_prob = height_hack_prob
27
+ self._action_space = spaces.Box(low=-1, high=1, shape=(5,))
28
+
29
+ def sample_action(self, obs, explore_prob):
30
+ """Implements height hack and grasping threshold hack.
31
+ """
32
+ dx, dy, dz, da, close = self._action_space.sample()
33
+ if np.random.random() < self._height_hack_prob:
34
+ dz = -1
35
+ return [dx, dy, dz, da, 0]
36
+
37
+
38
+ def main():
39
+
40
+ env = KukaDiverseObjectEnv(renders=True, isDiscrete=False)
41
+ policy = ContinuousDownwardBiasPolicy()
42
+
43
+ while True:
44
+ obs, done = env.reset(), False
45
+ print("===================================")
46
+ print("obs")
47
+ print(obs)
48
+ episode_rew = 0
49
+ while not done:
50
+ env.render(mode='human')
51
+ act = policy.sample_action(obs, .1)
52
+ print("Action")
53
+ print(act)
54
+ obs, rew, done, _ = env.step([0, 0, 0, 0, 0])
55
+ episode_rew += rew
56
+ print("Episode reward", episode_rew)
57
+
58
+
59
+ if __name__ == '__main__':
60
+ main()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/enjoy_kuka_grasping.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #add parent dir to find package. Only needed for source code build, pip install doesn't need it.
2
+ import os, inspect
3
+ currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
4
+ parentdir = os.path.dirname(os.path.dirname(currentdir))
5
+ os.sys.path.insert(0, parentdir)
6
+
7
+ import gym
8
+ from pybullet_envs.bullet.kukaGymEnv import KukaGymEnv
9
+
10
+ from baselines import deepq
11
+
12
+
13
+ def main():
14
+
15
+ env = KukaGymEnv(renders=True, isDiscrete=True)
16
+ act = deepq.load("kuka_model.pkl")
17
+ print(act)
18
+ while True:
19
+ obs, done = env.reset(), False
20
+ print("===================================")
21
+ print("obs")
22
+ print(obs)
23
+ episode_rew = 0
24
+ while not done:
25
+ env.render()
26
+ obs, rew, done, _ = env.step(act(obs[None])[0])
27
+ episode_rew += rew
28
+ print("Episode reward", episode_rew)
29
+
30
+
31
+ if __name__ == '__main__':
32
+ main()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/enjoy_pybullet_cartpole.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #add parent dir to find package. Only needed for source code build, pip install doesn't need it.
2
+ import os, inspect
3
+ currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
4
+ parentdir = os.path.dirname(os.path.dirname(currentdir))
5
+ os.sys.path.insert(0, parentdir)
6
+
7
+ import gym
8
+ import time
9
+
10
+ from baselines import deepq
11
+ from pybullet_envs.bullet.cartpole_bullet import CartPoleBulletEnv
12
+
13
+
14
+ def main():
15
+ env = gym.make('CartPoleBulletEnv-v1')
16
+ act = deepq.load("cartpole_model.pkl")
17
+
18
+ while True:
19
+ obs, done = env.reset(), False
20
+ print("obs")
21
+ print(obs)
22
+ print("type(obs)")
23
+ print(type(obs))
24
+ episode_rew = 0
25
+ while not done:
26
+ env.render()
27
+
28
+ o = obs[None]
29
+ aa = act(o)
30
+ a = aa[0]
31
+ obs, rew, done, _ = env.step(a)
32
+ episode_rew += rew
33
+ time.sleep(1. / 240.)
34
+ print("Episode reward", episode_rew)
35
+
36
+
37
+ if __name__ == '__main__':
38
+ main()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/enjoy_pybullet_racecar.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #add parent dir to find package. Only needed for source code build, pip install doesn't need it.
2
+ import os, inspect
3
+ currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
4
+ parentdir = os.path.dirname(os.path.dirname(currentdir))
5
+ os.sys.path.insert(0, parentdir)
6
+
7
+ import gym
8
+ from pybullet_envs.bullet.racecarGymEnv import RacecarGymEnv
9
+
10
+ from baselines import deepq
11
+
12
+
13
+ def main():
14
+
15
+ env = RacecarGymEnv(renders=True, isDiscrete=True)
16
+ act = deepq.load("racecar_model.pkl")
17
+ print(act)
18
+ while True:
19
+ obs, done = env.reset(), False
20
+ print("===================================")
21
+ print("obs")
22
+ print(obs)
23
+ episode_rew = 0
24
+ while not done:
25
+ env.render()
26
+ obs, rew, done, _ = env.step(act(obs[None])[0])
27
+ episode_rew += rew
28
+ print("Episode reward", episode_rew)
29
+
30
+
31
+ if __name__ == '__main__':
32
+ main()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/enjoy_pybullet_zed_racecar.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #add parent dir to find package. Only needed for source code build, pip install doesn't need it.
2
+ import os, inspect
3
+ currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
4
+ parentdir = os.path.dirname(os.path.dirname(currentdir))
5
+ os.sys.path.insert(0, parentdir)
6
+
7
+ import gym
8
+ from pybullet_envs.bullet.racecarZEDGymEnv import RacecarZEDGymEnv
9
+
10
+ from baselines import deepq
11
+
12
+
13
+ def main():
14
+
15
+ env = RacecarZEDGymEnv(renders=True)
16
+ act = deepq.load("racecar_zed_model.pkl")
17
+ print(act)
18
+ while True:
19
+ obs, done = env.reset(), False
20
+ print("===================================")
21
+ print("obs")
22
+ print(obs)
23
+ episode_rew = 0
24
+ while not done:
25
+ env.render()
26
+ obs, rew, done, _ = env.step(act(obs[None])[0])
27
+ episode_rew += rew
28
+ print("Episode reward", episode_rew)
29
+
30
+
31
+ if __name__ == '__main__':
32
+ main()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/train_kuka_cam_grasping.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #add parent dir to find package. Only needed for source code build, pip install doesn't need it.
2
+ import os, inspect
3
+ currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
4
+ parentdir = os.path.dirname(os.path.dirname(currentdir))
5
+ os.sys.path.insert(0, parentdir)
6
+
7
+ import gym
8
+ from pybullet_envs.bullet.kukaCamGymEnv import KukaCamGymEnv
9
+
10
+ from baselines import deepq
11
+
12
+ import datetime
13
+
14
+
15
+ def callback(lcl, glb):
16
+ # stop training if reward exceeds 199
17
+ total = sum(lcl['episode_rewards'][-101:-1]) / 100
18
+ totalt = lcl['t']
19
+ #print("totalt")
20
+ #print(totalt)
21
+ is_solved = totalt > 2000 and total >= 10
22
+ return is_solved
23
+
24
+
25
+ def main():
26
+
27
+ env = KukaCamGymEnv(renders=False, isDiscrete=True)
28
+ model = deepq.models.cnn_to_mlp(convs=[(32, 8, 4), (64, 4, 2), (64, 3, 1)],
29
+ hiddens=[256],
30
+ dueling=False)
31
+ act = deepq.learn(env,
32
+ q_func=model,
33
+ lr=1e-3,
34
+ max_timesteps=10000000,
35
+ buffer_size=50000,
36
+ exploration_fraction=0.1,
37
+ exploration_final_eps=0.02,
38
+ print_freq=10,
39
+ callback=callback)
40
+ print("Saving model to kuka_cam_model.pkl")
41
+ act.save("kuka_cam_model.pkl")
42
+
43
+
44
+ if __name__ == '__main__':
45
+ main()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/train_kuka_grasping.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #add parent dir to find package. Only needed for source code build, pip install doesn't need it.
2
+ import os, inspect
3
+ currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
4
+ parentdir = os.path.dirname(os.path.dirname(currentdir))
5
+ os.sys.path.insert(0, parentdir)
6
+
7
+ import gym
8
+ from pybullet_envs.bullet.kukaGymEnv import KukaGymEnv
9
+
10
+ from baselines import deepq
11
+
12
+ import datetime
13
+
14
+
15
+ def callback(lcl, glb):
16
+ # stop training if reward exceeds 199
17
+ total = sum(lcl['episode_rewards'][-101:-1]) / 100
18
+ totalt = lcl['t']
19
+ #print("totalt")
20
+ #print(totalt)
21
+ is_solved = totalt > 2000 and total >= 10
22
+ return is_solved
23
+
24
+
25
+ def main():
26
+
27
+ env = KukaGymEnv(renders=False, isDiscrete=True)
28
+ model = deepq.models.mlp([64])
29
+ act = deepq.learn(env,
30
+ q_func=model,
31
+ lr=1e-3,
32
+ max_timesteps=10000000,
33
+ buffer_size=50000,
34
+ exploration_fraction=0.1,
35
+ exploration_final_eps=0.02,
36
+ print_freq=10,
37
+ callback=callback)
38
+ print("Saving model to kuka_model.pkl")
39
+ act.save("kuka_model.pkl")
40
+
41
+
42
+ if __name__ == '__main__':
43
+ main()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/train_pybullet_cartpole.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #add parent dir to find package. Only needed for source code build, pip install doesn't need it.
2
+ import os, inspect
3
+ currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
4
+ parentdir = os.path.dirname(os.path.dirname(currentdir))
5
+ os.sys.path.insert(0, parentdir)
6
+
7
+ import gym
8
+ from pybullet_envs.bullet.cartpole_bullet import CartPoleBulletEnv
9
+
10
+ from baselines import deepq
11
+
12
+
13
+ def callback(lcl, glb):
14
+ # stop training if reward exceeds 199
15
+ is_solved = lcl['t'] > 100 and sum(lcl['episode_rewards'][-101:-1]) / 100 >= 199
16
+ return is_solved
17
+
18
+
19
+ def main():
20
+
21
+ env = CartPoleBulletEnv(renders=False)
22
+ model = deepq.models.mlp([64])
23
+ act = deepq.learn(env,
24
+ q_func=model,
25
+ lr=1e-3,
26
+ max_timesteps=100000,
27
+ buffer_size=50000,
28
+ exploration_fraction=0.1,
29
+ exploration_final_eps=0.02,
30
+ print_freq=10,
31
+ callback=callback)
32
+ print("Saving model to cartpole_model.pkl")
33
+ act.save("cartpole_model.pkl")
34
+
35
+
36
+ if __name__ == '__main__':
37
+ main()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/train_pybullet_racecar.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #add parent dir to find package. Only needed for source code build, pip install doesn't need it.
2
+ import os, inspect
3
+ currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
4
+ parentdir = os.path.dirname(os.path.dirname(currentdir))
5
+ os.sys.path.insert(0, parentdir)
6
+
7
+ import gym
8
+ from pybullet_envs.bullet.racecarGymEnv import RacecarGymEnv
9
+
10
+ from baselines import deepq
11
+
12
+ import datetime
13
+
14
+
15
+ def callback(lcl, glb):
16
+ # stop training if reward exceeds 199
17
+ total = sum(lcl['episode_rewards'][-101:-1]) / 100
18
+ totalt = lcl['t']
19
+ is_solved = totalt > 2000 and total >= -50
20
+ return is_solved
21
+
22
+
23
+ def main():
24
+
25
+ env = RacecarGymEnv(renders=False, isDiscrete=True)
26
+ model = deepq.models.mlp([64])
27
+ act = deepq.learn(env,
28
+ q_func=model,
29
+ lr=1e-3,
30
+ max_timesteps=10000,
31
+ buffer_size=50000,
32
+ exploration_fraction=0.1,
33
+ exploration_final_eps=0.02,
34
+ print_freq=10,
35
+ callback=callback)
36
+ print("Saving model to racecar_model.pkl")
37
+ act.save("racecar_model.pkl")
38
+
39
+
40
+ if __name__ == '__main__':
41
+ main()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/baselines/train_pybullet_zed_racecar.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #add parent dir to find package. Only needed for source code build, pip install doesn't need it.
2
+ import os, inspect
3
+ currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
4
+ parentdir = os.path.dirname(os.path.dirname(currentdir))
5
+ os.sys.path.insert(0, parentdir)
6
+
7
+ import gym
8
+ from pybullet_envs.bullet.racecarZEDGymEnv import RacecarZEDGymEnv
9
+
10
+ from baselines import deepq
11
+
12
+ import datetime
13
+
14
+
15
+ def callback(lcl, glb):
16
+ # stop training if reward exceeds 199
17
+ total = sum(lcl['episode_rewards'][-101:-1]) / 100
18
+ totalt = lcl['t']
19
+ is_solved = totalt > 2000 and total >= -50
20
+ return is_solved
21
+
22
+
23
+ def main():
24
+
25
+ env = RacecarZEDGymEnv(renders=False, isDiscrete=True)
26
+ model = deepq.models.cnn_to_mlp(convs=[(32, 8, 4), (64, 4, 2), (64, 3, 1)],
27
+ hiddens=[256],
28
+ dueling=False)
29
+ act = deepq.learn(env,
30
+ q_func=model,
31
+ lr=1e-3,
32
+ max_timesteps=10000,
33
+ buffer_size=50000,
34
+ exploration_fraction=0.1,
35
+ exploration_final_eps=0.02,
36
+ print_freq=10,
37
+ callback=callback)
38
+ print("Saving model to racecar_zed_model.pkl")
39
+ act.save("racecar_zed_model.pkl")
40
+
41
+
42
+ if __name__ == '__main__':
43
+ main()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from pybullet_envs.bullet.cartpole_bullet import CartPoleBulletEnv
2
+ from pybullet_envs.bullet.cartpole_bullet import CartPoleContinuousBulletEnv
3
+ from pybullet_envs.bullet.minitaur_gym_env import MinitaurBulletEnv
4
+ from pybullet_envs.bullet.minitaur_duck_gym_env import MinitaurBulletDuckEnv
5
+ from pybullet_envs.bullet.racecarGymEnv import RacecarGymEnv
6
+ from pybullet_envs.bullet.racecarZEDGymEnv import RacecarZEDGymEnv
7
+ from pybullet_envs.bullet.kukaGymEnv import KukaGymEnv
8
+ from pybullet_envs.bullet.kukaCamGymEnv import KukaCamGymEnv
9
+ from pybullet_envs.bullet.kuka_diverse_object_gym_env import KukaDiverseObjectEnv
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (1.08 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__pycache__/cartpole_bullet.cpython-311.pyc ADDED
Binary file (10.4 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__pycache__/env_randomizer_base.cpython-311.pyc ADDED
Binary file (1.31 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__pycache__/kuka.cpython-311.pyc ADDED
Binary file (9.85 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__pycache__/kukaCamGymEnv.cpython-311.pyc ADDED
Binary file (12 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__pycache__/kukaGymEnv.cpython-311.pyc ADDED
Binary file (14.3 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__pycache__/kuka_diverse_object_gym_env.cpython-311.pyc ADDED
Binary file (15.9 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/pybullet_envs/bullet/__pycache__/minitaur.cpython-311.pyc ADDED
Binary file (27 kB). View file