vuer-env 0.1.4__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.
vuer_env/__init__.py ADDED
@@ -0,0 +1,71 @@
1
+ """Environment contracts and entry points for simulators and real robots.
2
+
3
+ See ``vuer_env.core``, ``vuer_env.transport``, and ``vuer_env.execution``
4
+ for imports grouped by use case.
5
+ """
6
+
7
+ from typing import TYPE_CHECKING as _TYPE_CHECKING
8
+
9
+ from ._exports import resolve as _resolve
10
+
11
+ if _TYPE_CHECKING:
12
+ from . import registry, spaces
13
+ from .adapters import AsyncFromSync, SyncFromAsync
14
+ from .client import AsyncRobotEnv
15
+ from .core._factory import make
16
+ from .interface import (
17
+ Actions,
18
+ AsyncEnv,
19
+ Camera,
20
+ Env,
21
+ EnvConfig,
22
+ EnvSpec,
23
+ Imu,
24
+ Lidar,
25
+ Observations,
26
+ Reset,
27
+ describe_env,
28
+ )
29
+ from .rate import AsyncFixedRate, FixedRate
30
+ from .registry import register
31
+ from .sync import ControlSession, RobotEnv
32
+ from .vector import SyncVecEnv, VecEnv, make_vec
33
+
34
+
35
+ _EXPORTS = {
36
+ "Actions": ".interface:Actions",
37
+ "AsyncEnv": ".interface:AsyncEnv",
38
+ "AsyncFixedRate": ".rate:AsyncFixedRate",
39
+ "AsyncFromSync": ".adapters:AsyncFromSync",
40
+ "AsyncRobotEnv": ".client:AsyncRobotEnv",
41
+ "Camera": ".interface:Camera",
42
+ "ControlSession": ".sync:ControlSession",
43
+ "Env": ".interface:Env",
44
+ "EnvConfig": ".interface:EnvConfig",
45
+ "EnvSpec": ".interface:EnvSpec",
46
+ "FixedRate": ".rate:FixedRate",
47
+ "Imu": ".interface:Imu",
48
+ "Lidar": ".interface:Lidar",
49
+ "Observations": ".interface:Observations",
50
+ "Reset": ".interface:Reset",
51
+ "RobotEnv": ".sync:RobotEnv",
52
+ "SyncFromAsync": ".adapters:SyncFromAsync",
53
+ "SyncVecEnv": ".vector:SyncVecEnv",
54
+ "VecEnv": ".vector:VecEnv",
55
+ "describe_env": ".interface:describe_env",
56
+ "make": ".core._factory:make",
57
+ "make_vec": ".vector:make_vec",
58
+ "register": ".registry:register",
59
+ "registry": ".registry",
60
+ "spaces": ".spaces",
61
+ }
62
+
63
+ __all__ = list(_EXPORTS)
64
+
65
+
66
+ def __getattr__(name):
67
+ return _resolve(globals(), _EXPORTS, name)
68
+
69
+
70
+ def __dir__():
71
+ return sorted(set(globals()) | _EXPORTS.keys())
vuer_env/_exports.py ADDED
@@ -0,0 +1,13 @@
1
+ """Resolve public re-exports on first access."""
2
+
3
+ from importlib import import_module
4
+
5
+
6
+ def resolve(namespace, exports, name):
7
+ if name not in exports:
8
+ raise AttributeError(f"module {namespace['__name__']!r} has no attribute {name!r}")
9
+ module_name, _, attribute = exports[name].partition(":")
10
+ module = import_module(module_name, "vuer_env")
11
+ value = getattr(module, attribute) if attribute else module
12
+ namespace[name] = value
13
+ return value
vuer_env/adapters.py ADDED
@@ -0,0 +1,220 @@
1
+ """Turn a sync ``Env`` into an ``AsyncEnv`` and back.
2
+
3
+ ``AsyncFromSync`` runs every call of a sync env on one private worker thread.
4
+ Simulators and their GL/CUDA contexts are bound to the thread that created
5
+ them, so ``AsyncFromSync.create(factory)`` also builds the env on that thread.
6
+
7
+ ``SyncFromAsync`` owns an event loop on a daemon thread and runs every
8
+ coroutine of an async env there, so background tasks of the env (readers,
9
+ keepalives) keep running while the caller blocks between calls. Build the async
10
+ env on that loop with ``SyncFromAsync.create(factory)`` when it binds to the
11
+ running loop at construction.
12
+ """
13
+
14
+ import asyncio
15
+ import inspect
16
+ import threading
17
+ from collections.abc import Awaitable, Callable
18
+ from concurrent.futures import ThreadPoolExecutor
19
+ from typing import Any
20
+
21
+ from .interface import (
22
+ Action,
23
+ AsyncEnv,
24
+ Env,
25
+ EnvSpec,
26
+ Info,
27
+ Observation,
28
+ StepResult,
29
+ step_options,
30
+ )
31
+
32
+ __all__ = ["AsyncFromSync", "SyncFromAsync"]
33
+
34
+
35
+ class AsyncFromSync(AsyncEnv):
36
+ """Async view of a sync env; all calls run on one worker thread."""
37
+
38
+ def __init__(self, env: Env, *, executor: ThreadPoolExecutor | None = None):
39
+ self._env = env
40
+ self._executor = executor or _worker()
41
+ self._closed = False
42
+
43
+ @classmethod
44
+ async def create(cls, factory: Callable[[], Env]) -> "AsyncFromSync":
45
+ """Build the env with ``factory()`` on the worker thread, then wrap it."""
46
+ executor = _worker()
47
+ try:
48
+ env = await asyncio.get_running_loop().run_in_executor(executor, factory)
49
+ except BaseException:
50
+ executor.shutdown(wait=False)
51
+ raise
52
+ return cls(env, executor=executor)
53
+
54
+ async def _run(self, function, *args, **kwargs):
55
+ if self._closed:
56
+ raise RuntimeError("Environment is closed")
57
+ return await asyncio.get_running_loop().run_in_executor(
58
+ self._executor, lambda: function(*args, **kwargs)
59
+ )
60
+
61
+ @property
62
+ def env(self) -> Env:
63
+ """The wrapped sync env."""
64
+ return self._env
65
+
66
+ @property
67
+ def unwrapped(self) -> Env:
68
+ return self._env.unwrapped
69
+
70
+ @property
71
+ def spec(self) -> EnvSpec:
72
+ return self._env.spec
73
+
74
+ @property
75
+ def action_space(self) -> Any:
76
+ return self._env.action_space
77
+
78
+ @property
79
+ def observation_space(self) -> Any:
80
+ return self._env.observation_space
81
+
82
+ async def reset(
83
+ self, *, seed: int | None = None, options: dict[str, Any] | None = None
84
+ ) -> tuple[Observation, Info]:
85
+ return await self._run(self._env.reset, seed=seed, options=options)
86
+
87
+ async def step(
88
+ self, action: Action, *, modes: dict[str, str] | None = None, dt: float | None = None
89
+ ) -> StepResult:
90
+ return await self._run(self._env.step, action, **step_options(modes, dt))
91
+
92
+ async def call(self, name: str, *args, **kwargs) -> Any:
93
+ """Run any other method of the sync env (for example ``render``) on the worker thread."""
94
+ return await self._run(getattr(self._env, name), *args, **kwargs)
95
+
96
+ async def close(self) -> None:
97
+ if self._closed:
98
+ return
99
+ try:
100
+ await self._run(self._env.close)
101
+ finally:
102
+ self._closed = True
103
+ self._executor.shutdown(wait=True)
104
+
105
+
106
+ class SyncFromAsync(Env):
107
+ """Blocking view of an async env; all coroutines run on a private event loop thread."""
108
+
109
+ def __init__(self, env: AsyncEnv, *, timeout: float | None = None, _loop=None):
110
+ self._env = env
111
+ self._loop = _loop or _LoopThread()
112
+ self._timeout = timeout
113
+
114
+ @classmethod
115
+ def create(
116
+ cls,
117
+ factory: Callable[[], AsyncEnv | Awaitable[AsyncEnv]],
118
+ *,
119
+ timeout: float | None = None,
120
+ ) -> "SyncFromAsync":
121
+ """Build the async env on the private loop, then wrap it.
122
+
123
+ ``factory`` returns an ``AsyncEnv`` or an awaitable of one (for example
124
+ ``lambda: vuer_env.aio.make(url, token=token)``).
125
+ """
126
+ loop = _LoopThread()
127
+
128
+ async def build():
129
+ env = factory()
130
+ return await env if inspect.isawaitable(env) else env
131
+
132
+ try:
133
+ env = loop.call(build(), timeout)
134
+ except BaseException:
135
+ loop.close()
136
+ raise
137
+ return cls(env, timeout=timeout, _loop=loop)
138
+
139
+ def _call(self, coroutine):
140
+ return self._loop.call(coroutine, self._timeout)
141
+
142
+ @property
143
+ def env(self) -> AsyncEnv:
144
+ """The wrapped async env."""
145
+ return self._env
146
+
147
+ @property
148
+ def unwrapped(self) -> AsyncEnv:
149
+ return self._env.unwrapped
150
+
151
+ @property
152
+ def spec(self) -> EnvSpec:
153
+ return self._env.spec
154
+
155
+ @property
156
+ def action_space(self) -> Any:
157
+ return self._env.action_space
158
+
159
+ @property
160
+ def observation_space(self) -> Any:
161
+ return self._env.observation_space
162
+
163
+ def reset(
164
+ self, *, seed: int | None = None, options: dict[str, Any] | None = None
165
+ ) -> tuple[Observation, Info]:
166
+ return self._call(self._env.reset(seed=seed, options=options))
167
+
168
+ def step(
169
+ self, action: Action, *, modes: dict[str, str] | None = None, dt: float | None = None
170
+ ) -> StepResult:
171
+ return self._call(self._env.step(action, **step_options(modes, dt)))
172
+
173
+ def call(self, name: str, *args, **kwargs) -> Any:
174
+ """Run any other coroutine method of the async env and wait for its result."""
175
+ return self._call(getattr(self._env, name)(*args, **kwargs))
176
+
177
+ def close(self) -> None:
178
+ if self._loop.loop.is_closed():
179
+ return
180
+ try:
181
+ self._call(self._env.close())
182
+ finally:
183
+ self._loop.close()
184
+
185
+
186
+ def _worker() -> ThreadPoolExecutor:
187
+ return ThreadPoolExecutor(max_workers=1, thread_name_prefix="vuer-env-worker")
188
+
189
+
190
+ class _LoopThread:
191
+ """One asyncio event loop running forever on a daemon thread."""
192
+
193
+ def __init__(self):
194
+ self.loop = asyncio.new_event_loop()
195
+ self._thread = threading.Thread(target=self._run, name="vuer-env-loop", daemon=True)
196
+ self._thread.start()
197
+
198
+ def _run(self):
199
+ asyncio.set_event_loop(self.loop)
200
+ self.loop.run_forever()
201
+
202
+ def call(self, coroutine, timeout=None):
203
+ if threading.current_thread() is self._thread:
204
+ coroutine.close()
205
+ raise RuntimeError("Sync vuer_env API called from its own event loop")
206
+ future = asyncio.run_coroutine_threadsafe(coroutine, self.loop)
207
+ try:
208
+ return future.result(timeout)
209
+ except BaseException:
210
+ # KeyboardInterrupt or a timeout: cancel so the coroutine's own cleanup runs.
211
+ future.cancel()
212
+ raise
213
+
214
+ def close(self):
215
+ if self.loop.is_closed():
216
+ return
217
+ self.loop.call_soon_threadsafe(self.loop.stop)
218
+ self._thread.join(5)
219
+ if not self._thread.is_alive():
220
+ self.loop.close()
vuer_env/aio.py ADDED
@@ -0,0 +1,46 @@
1
+ """Async API. Mirrors ``vuer_env`` (sync) name for name: ``await make(...)``."""
2
+
3
+ from typing import TYPE_CHECKING as _TYPE_CHECKING
4
+
5
+ from ._exports import resolve as _resolve
6
+ from .core._factory import _local_options, _remote_options, is_remote
7
+
8
+ if _TYPE_CHECKING:
9
+ from .client import AsyncRobotEnv as AsyncRobotEnv
10
+ from .control_client import ControlSession as ControlSession
11
+
12
+
13
+ async def make(target="ws://127.0.0.1:8767", *, token=None, timeout=None, **overrides):
14
+ """Make an async env: local by registry id, or remote by ``ws://``/``wss://`` URL.
15
+
16
+ ``await make("fortyfive/s1-tabletop-mujoco-v0", **overrides)`` builds the env
17
+ in this process (it runs on its own thread). ``await make("ws://host:8767",
18
+ token=...)`` connects to an env server (``timeout`` in seconds, default 2) and
19
+ returns ``AsyncRobotEnv``. Both return an ``AsyncEnv``.
20
+ """
21
+ if not is_remote(target):
22
+ options = _local_options(target, token, timeout, overrides)
23
+ from .registry import make_async as make_local
24
+
25
+ return await make_local(target, **options)
26
+
27
+ options = _remote_options(target, token, timeout, overrides)
28
+ from .client import make as connect
29
+
30
+ return await connect(target, **options)
31
+
32
+
33
+ _EXPORTS = {
34
+ "AsyncRobotEnv": ".client:AsyncRobotEnv",
35
+ "ControlSession": ".control_client:ControlSession",
36
+ }
37
+
38
+ __all__ = ["AsyncRobotEnv", "ControlSession", "make"]
39
+
40
+
41
+ def __getattr__(name):
42
+ return _resolve(globals(), _EXPORTS, name)
43
+
44
+
45
+ def __dir__():
46
+ return sorted(set(globals()) | _EXPORTS.keys())