mujoco 4.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mujoco/__init__.py ADDED
@@ -0,0 +1,330 @@
1
+ # Copyright 2022 DeepMind Technologies Limited
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
+ # ==============================================================================
15
+ """Python bindings for MuJoCo."""
16
+
17
+ import ctypes
18
+ import ctypes.util
19
+ import os
20
+ import platform
21
+ import subprocess
22
+ from typing import Any, IO, Sequence, TypeAlias, Union
23
+ import warnings
24
+ import zipfile
25
+
26
+ # Extend the path to enable multiple directories to contribute to the same
27
+ # package. Without this line, the `mujoco-mjx` package would not be able to
28
+ # be discovered by import. For more information, see: https://packaging.python.org/guides/packaging-namespace-packages/#pkgutil-style-namespace-packages
29
+ # NOTE: As per the Python Packaging User Guide linked above, the preferable way
30
+ # of declaring the namespace package is to use the native namespace packages.
31
+ # This seems non-trivial at the current state of the project, however.
32
+ # For more information, see: https://github.com/google-deepmind/mujoco/issues/2119
33
+ __path__ = __import__('pkgutil').extend_path(__path__, __name__)
34
+
35
+ _SYSTEM = platform.system()
36
+ if _SYSTEM == 'Windows':
37
+ _dll_path = os.path.join(os.path.dirname(__file__), 'mujoco.dll')
38
+ if os.path.exists(_dll_path):
39
+ ctypes.WinDLL(_dll_path)
40
+ elif _SYSTEM == 'Darwin':
41
+ # sysctl is in /usr/sbin, which is not on minimal PATHs (e.g. the
42
+ # environment Bazel runs tests in), so don't rely on PATH lookup.
43
+ try:
44
+ proc_translated = subprocess.run(
45
+ ['/usr/sbin/sysctl', '-n', 'sysctl.proc_translated'],
46
+ capture_output=True).stdout
47
+ is_rosetta = bool(int(proc_translated))
48
+ except (OSError, ValueError):
49
+ is_rosetta = False
50
+ if is_rosetta and platform.machine() == 'x86_64':
51
+ raise ImportError(
52
+ 'You are running an x86_64 build of Python on an Apple Silicon '
53
+ 'machine. This is not supported by MuJoCo. Please install and run a '
54
+ 'native, arm64 build of Python.')
55
+
56
+ _EXPECTED_VERSION = '4.0.0'
57
+ try:
58
+ from mujoco._version import __version__ as _core_version
59
+ import mujoco._specs
60
+ except ModuleNotFoundError as _e:
61
+ if not (_e.name or '').startswith('mujoco'):
62
+ raise
63
+ raise ImportError(
64
+ "The 'mujoco' package is installed, but its core bindings "
65
+ "('mujoco-core') are missing or corrupted (for example, after "
66
+ "uninstalling a previous monolithic 'mujoco' package). "
67
+ "Repair your environment with:\n"
68
+ ' pip install --force-reinstall --no-deps '
69
+ 'mujoco mujoco-core mujoco-studio'
70
+ ) from _e
71
+ if _core_version != _EXPECTED_VERSION:
72
+ raise ImportError(
73
+ f"Version mismatch between 'mujoco' ({_EXPECTED_VERSION}) and "
74
+ f"'mujoco-core' ({_core_version}). Please upgrade all packages "
75
+ 'together:\n'
76
+ f" pip install --upgrade 'mujoco=={_EXPECTED_VERSION}' "
77
+ f"'mujoco-core=={_EXPECTED_VERSION}' "
78
+ f"'mujoco-studio=={_EXPECTED_VERSION}'"
79
+ )
80
+
81
+ from mujoco import _specs
82
+ from mujoco import _structs
83
+ from mujoco._callbacks import *
84
+ from mujoco._constants import *
85
+ from mujoco._enums import *
86
+ from mujoco._errors import *
87
+ from mujoco._functions import *
88
+ from mujoco._specs import *
89
+ from mujoco._structs import *
90
+
91
+ import numpy as np
92
+ MJTNUM_DTYPE = np.float32 if MJTNUM_BYTES == 4 else np.float64 # pylint: disable=undefined-variable
93
+
94
+ try:
95
+ from mujoco._render import *
96
+ except ImportError:
97
+ pass
98
+
99
+ try:
100
+ from mujoco.rendering.classic.renderer import Renderer # pyrefly: ignore[missing-import]
101
+ except ImportError:
102
+ pass
103
+
104
+ try:
105
+ from mujoco.rendering.classic.gl_context import * # pyrefly: ignore[missing-import]
106
+ except ImportError:
107
+ pass
108
+
109
+ MjStruct: TypeAlias = Union[
110
+ _specs.MjsBody,
111
+ _specs.MjsFrame,
112
+ _specs.MjsGeom,
113
+ _specs.MjsJoint,
114
+ _specs.MjsLight,
115
+ _specs.MjsMaterial,
116
+ _specs.MjsSite,
117
+ _specs.MjsMesh,
118
+ _specs.MjsSkin,
119
+ _specs.MjsTexture,
120
+ _specs.MjsText,
121
+ _specs.MjsTuple,
122
+ _specs.MjsCamera,
123
+ _specs.MjsFlex,
124
+ _specs.MjsHField,
125
+ _specs.MjsKey,
126
+ _specs.MjsNumeric,
127
+ _specs.MjsPair,
128
+ _specs.MjsExclude,
129
+ _specs.MjsEquality,
130
+ _specs.MjsTendon,
131
+ _specs.MjsSensor,
132
+ _specs.MjsActuator,
133
+ _specs.MjsPlugin,
134
+ ]
135
+
136
+
137
+ def to_zip(spec: _specs.MjSpec, file: Union[str, IO[bytes]]) -> None:
138
+ """Converts an MjSpec to a zip file.
139
+
140
+ Args:
141
+ spec: The mjSpec to save to a file.
142
+ file: The path to the file to save to or the file object to write to.
143
+ """
144
+ files_to_zip = dict(spec.assets)
145
+ files_to_zip[spec.modelname + '.xml'] = spec.to_xml()
146
+ if isinstance(file, str):
147
+ directory = os.path.dirname(file)
148
+ if directory:
149
+ os.makedirs(directory, exist_ok=True)
150
+ file = open(file, 'wb')
151
+ with zipfile.ZipFile(file, 'w') as zip_file:
152
+ for filename, contents in files_to_zip.items():
153
+ zip_info = zipfile.ZipInfo(filename)
154
+ zip_file.writestr(zip_info, contents)
155
+
156
+
157
+ def from_zip(file: Union[str, IO[bytes]]) -> _specs.MjSpec:
158
+ """Reads a zip file and returns an MjSpec.
159
+
160
+ Args:
161
+ file: The path to the file to read from or the file object to read from.
162
+ Returns:
163
+ An MjSpec object.
164
+ """
165
+ assets = {}
166
+ xml_string = None
167
+ if isinstance(file, str):
168
+ file = open(file, 'rb')
169
+ if not zipfile.is_zipfile(file):
170
+ raise ValueError(f'File {file} is not a zip file.')
171
+ with zipfile.ZipFile(file, 'r') as zip_file:
172
+ xml_dir = None
173
+ for zip_info in zip_file.infolist():
174
+ if not zip_info.filename.endswith(os.path.sep):
175
+ with zip_file.open(zip_info.filename) as f:
176
+ if zip_info.filename.endswith('.xml'):
177
+ xml_string = f.read()
178
+ xml_dir = os.path.dirname(zip_info.filename)
179
+ else:
180
+ assets[zip_info.filename] = f.read()
181
+
182
+ if not xml_string:
183
+ raise ValueError('No XML file found in zip file.')
184
+
185
+ relative_assets = {}
186
+ for key, value in assets.items():
187
+ new_key = os.path.relpath(key, xml_dir)
188
+ relative_assets[new_key] = value
189
+ assets = relative_assets
190
+
191
+ return _specs.MjSpec.from_string(xml_string, assets=assets)
192
+
193
+
194
+ def _bind_getattr(elements: Sequence[Any], key: str):
195
+ items = []
196
+ for e in elements:
197
+ val = getattr(e, key)
198
+ if isinstance(val, (str, bytes)):
199
+ items.append(val)
200
+ else:
201
+ try:
202
+ items.extend(val)
203
+ except TypeError:
204
+ items.append(val)
205
+ return items
206
+
207
+
208
+ class _MjBindModel:
209
+ """Wrapper for MjModel that allows binding multiple specs."""
210
+
211
+ def __init__(self, elements: Sequence[Any]):
212
+ object.__setattr__(self, 'elements', elements)
213
+
214
+ def __getattr__(self, key: str):
215
+ return _bind_getattr(self.elements, key)
216
+
217
+ def __setattr__(self, key: str, value: Any):
218
+ try:
219
+ values = list(value)
220
+ except TypeError:
221
+ raise ValueError(
222
+ f'Expected {len(self.elements)} values, got non-iterable'
223
+ f' {type(value).__name__}'
224
+ ) from None
225
+ if len(values) != len(self.elements):
226
+ raise ValueError(
227
+ f'Expected {len(self.elements)} values, got {len(values)}'
228
+ )
229
+ for element, val in zip(self.elements, values):
230
+ setattr(element, key, val)
231
+
232
+
233
+ class _MjBindData:
234
+ """Wrapper for MjData that allows binding multiple specs."""
235
+
236
+ def __init__(self, elements: Sequence[Any]):
237
+ object.__setattr__(self, 'elements', elements)
238
+
239
+ def __getattr__(self, key: str):
240
+ return _bind_getattr(self.elements, key)
241
+
242
+ def __setattr__(self, key: str, value: Any):
243
+ try:
244
+ values = list(value)
245
+ except TypeError:
246
+ raise ValueError(
247
+ f'Expected {len(self.elements)} values, got non-iterable'
248
+ f' {type(value).__name__}'
249
+ ) from None
250
+ if len(values) != len(self.elements):
251
+ raise ValueError(
252
+ f'Expected {len(self.elements)} values, got {len(values)}'
253
+ )
254
+ for element, val in zip(self.elements, values):
255
+ setattr(element, key, val)
256
+
257
+
258
+ def _bind_model(
259
+ model: _structs.MjModel, specs: Union[Sequence[MjStruct], MjStruct]
260
+ ):
261
+ """Bind a Mujoco spec to a mjModel.
262
+
263
+ Args:
264
+ model: The mjModel to bind to.
265
+ specs: The mjSpec elements to use for binding, can be a single element or a
266
+ sequence.
267
+ Returns:
268
+ A MjModelGroupedViews object or a list of the same type.
269
+ """
270
+ if isinstance(specs, Sequence):
271
+ return _MjBindModel([model.bind_scalar(s) for s in specs])
272
+ else:
273
+ return model.bind_scalar(specs)
274
+
275
+
276
+ def _bind_data(
277
+ data: _structs.MjData, specs: Union[Sequence[MjStruct], MjStruct]
278
+ ):
279
+ """Bind a Mujoco spec to a mjData.
280
+
281
+ Args:
282
+ data: The mjData to bind to.
283
+ specs: The mjSpec elements to use for binding, can be a single element or a
284
+ sequence.
285
+ Returns:
286
+ A MjDataGroupedViews object or a list of the same type.
287
+ """
288
+ if isinstance(specs, Sequence):
289
+ return _MjBindData([data.bind_scalar(s) for s in specs])
290
+ else:
291
+ return data.bind_scalar(specs)
292
+
293
+ _specs.MjSpec.from_zip = from_zip
294
+ _specs.MjSpec.to_zip = to_zip
295
+ _structs.MjData.bind = _bind_data # pyrefly: ignore[bad-assignment]
296
+ _structs.MjModel.bind = _bind_model # pyrefly: ignore[bad-assignment]
297
+
298
+ __version__ = mj_versionString() # pylint: disable=undefined-variable
299
+
300
+ HEADERS_DIR = os.path.join(os.path.dirname(__file__), 'include/mujoco')
301
+ PLUGINS_DIR = os.path.join(os.path.dirname(__file__), 'plugin')
302
+
303
+ PLUGIN_HANDLES = []
304
+
305
+ def _load_all_bundled_plugins():
306
+ if os.path.isdir(PLUGINS_DIR):
307
+ for directory, _, filenames in os.walk(PLUGINS_DIR):
308
+ for filename in filenames:
309
+ if os.path.splitext(filename)[-1] in [".dll", ".dylib", ".so"]:
310
+ lib_path = os.path.join(directory, filename)
311
+ PLUGIN_HANDLES.append(ctypes.CDLL(lib_path))
312
+ elif filename == "__init__.py":
313
+ pass
314
+ else:
315
+ warnings.warn('Ignoring non-library in plugin directory: '
316
+ f'{os.path.join(directory, filename)}', ImportWarning)
317
+ try:
318
+ import importlib.metadata as _metadata
319
+ for _ep in _metadata.entry_points(group='mujoco.plugins'):
320
+ try:
321
+ _ep.load()()
322
+ except Exception as _ep_err: # pylint: disable=broad-exception-caught
323
+ warnings.warn(
324
+ f'Failed to load mujoco plugin entry point {_ep.name}: {_ep_err}',
325
+ RuntimeWarning,
326
+ )
327
+ except Exception: # pylint: disable=broad-exception-caught
328
+ pass
329
+
330
+ _load_all_bundled_plugins()