repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bitvavo/__init__.py
cryptoxlib/clients/bitvavo/__init__.py
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bitvavo/functions.py
cryptoxlib/clients/bitvavo/functions.py
from cryptoxlib.Pair import Pair def map_pair(pair: Pair) -> str: return f"{pair.base}-{pair.quote}"
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bitvavo/BitvavoClient.py
cryptoxlib/clients/bitvavo/BitvavoClient.py
import ssl import logging import hmac import json import hashlib from multidict import CIMultiDictProxy from typing import List, Optional from cryptoxlib.CryptoXLibClient import CryptoXLibClient, RestCallType from cryptoxlib.clients.bitvavo import enums from cryptoxlib.clients.bitvavo.exceptions import BitvavoException from cryptoxlib.clients.bitvavo.functions import map_pair from cryptoxlib.Pair import Pair from cryptoxlib.WebsocketMgr import WebsocketMgr, Subscription from cryptoxlib.clients.bitvavo.BitvavoWebsocket import BitvavoWebsocket LOG = logging.getLogger(__name__) class BitvavoClient(CryptoXLibClient): REST_API_URI = "https://api.bitvavo.com/v2/" VALIDITY_WINDOW_MS = 5000 def __init__(self, api_key: str = None, sec_key: str = None, api_trace_log: bool = False, ssl_context: ssl.SSLContext = None) -> None: super().__init__(api_trace_log, ssl_context) self.api_key = api_key self.sec_key = sec_key def _get_rest_api_uri(self) -> str: return self.REST_API_URI def _sign_payload(self, rest_call_type: RestCallType, resource: str, data: dict = None, params: dict = None, headers: dict = None) -> None: timestamp = self._get_current_timestamp_ms() resource_string = resource if params is not None and len(params) > 0: params_string = '&'.join([f"{key}={val}" for key, val in params.items()]) if "?" in resource: resource_string += "&" else: resource_string += "?" resource_string += params_string signature_string = str(timestamp) + rest_call_type.value + '/v2/' + resource_string if data is not None: signature_string += json.dumps(data, separators=(',',':')) LOG.debug(f"Signature input string: {signature_string}") signature = hmac.new(self.sec_key.encode('utf-8'), signature_string.encode('utf-8'), hashlib.sha256).hexdigest() headers['Bitvavo-Access-Key'] = self.api_key headers['Bitvavo-Access-Signature'] = signature headers['Bitvavo-Access-Timestamp'] = str(timestamp) headers['Bitvavo-Access-Window'] = str(self.VALIDITY_WINDOW_MS) def _preprocess_rest_response(self, status_code: int, headers: 'CIMultiDictProxy[str]', body: Optional[dict]) -> None: if str(status_code)[0] != '2': raise BitvavoException(f"BitvavoException: status [{status_code}], response [{body}]") def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0, ssl_context = None) -> WebsocketMgr: return BitvavoWebsocket(subscriptions, self.api_key, self.sec_key, ssl_context) async def get_time(self) -> dict: return await self._create_get("time") async def get_exchange_info(self) -> dict: return await self._create_get("markets") async def get_assets(self) -> dict: return await self._create_get("assets") async def get_open_orders(self, pair: Pair = None) -> dict: get_params = "" if pair is not None: get_params = f"?market={map_pair(pair)}" return await self._create_get(f"ordersOpen{get_params}", signed = True) async def create_order(self, pair: Pair, type: enums.OrderType, side: enums.OrderSide, amount: str = None, price: str = None, amount_quote: str = None, time_in_force: enums.TimeInForce = None, self_trade_prevention: enums.SelfTradePrevention = None, prevent_limit_immediate_fill: bool = None, disable_market_protection: bool = None, full_response: bool = None) -> dict: data = self._clean_request_params({ "market": map_pair(pair), "side": side.value, "orderType": type.value, "amount": amount, "price": price, "amountQuote": amount_quote, "postOnly": prevent_limit_immediate_fill, "disableMarketProtection": disable_market_protection, "responseRequired": full_response }) if time_in_force is not None: data['timeInForce'] = time_in_force.value if time_in_force is not None: data['selfTradePrevention'] = self_trade_prevention.value return await self._create_post("order", data = data, signed = True) async def cancel_order(self, pair: Pair, order_id: str) -> dict: params = self._clean_request_params({ "market": map_pair(pair), "orderId": order_id }) return await self._create_delete("order", params = params, signed = True) async def get_balance(self, coin: str = None) -> dict: params = self._clean_request_params({ "symbol": coin }) return await self._create_get("balance", params = params, signed = True) async def get_24h_price_ticker(self, pair: Pair = None) -> dict: get_params = "" if pair is not None: get_params = f"?market={map_pair(pair)}" return await self._create_get(f"ticker/24h{get_params}", signed = True) async def get_price_ticker(self, pair: Pair = None) -> dict: get_params = "" if pair is not None: get_params = f"?market={map_pair(pair)}" return await self._create_get(f"ticker/price{get_params}", signed = True) async def get_best_orderbook_ticker(self, pair: Optional[Pair] = None) -> dict: get_params = "" if pair is not None: get_params = f"?market={map_pair(pair)}" return await self._create_get(f"ticker/book{get_params}", signed = True)
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/eterbase/enums.py
cryptoxlib/clients/eterbase/enums.py
import enum class OrderType(enum.Enum): MARKET = "1" LIMIT = "2" STOP_MARKET = "3" STOP_LIMIT = "4" class OrderSide(enum.Enum): BUY = "1" SELL = "2" class TimeInForce(enum.Enum): GOOD_TILL_CANCELLED = "GTC"
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/eterbase/exceptions.py
cryptoxlib/clients/eterbase/exceptions.py
from typing import Optional from cryptoxlib.exceptions import CryptoXLibException class EterbaseException(CryptoXLibException): pass class EterbaseRestException(EterbaseException): def __init__(self, status_code: int, body: Optional[dict]): super().__init__(f"Rest API exception: status [{status_code}], response [{body}]") self.status_code = status_code self.body = body
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/eterbase/__init__.py
cryptoxlib/clients/eterbase/__init__.py
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/eterbase/EterbaseClient.py
cryptoxlib/clients/eterbase/EterbaseClient.py
import ssl import logging import datetime import hmac import hashlib import json import base64 from multidict import CIMultiDictProxy from typing import List, Optional from cryptoxlib.CryptoXLibClient import CryptoXLibClient, RestCallType from cryptoxlib.clients.eterbase import enums from cryptoxlib.clients.eterbase.exceptions import EterbaseRestException from cryptoxlib.WebsocketMgr import WebsocketMgr, Subscription from cryptoxlib.clients.eterbase.EterbaseWebsocket import EterbaseWebsocket LOG = logging.getLogger(__name__) class EterbaseClient(CryptoXLibClient): REST_API_URI = "https://api.eterbase.exchange/api/v1/" def __init__(self, account_id: str = None, api_key: str = None, sec_key: str = None, api_trace_log: bool = False, ssl_context: ssl.SSLContext = None) -> None: super().__init__(api_trace_log, ssl_context) self.account_id = account_id self.api_key = api_key self.sec_key = sec_key def _get_rest_api_uri(self) -> str: return self.REST_API_URI def _sign_payload(self, rest_call_type: RestCallType, resource: str, data: dict = None, params: dict = None, headers: dict = None) -> None: http_date = datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT") headers["Date"] = http_date message = 'date' + ':' + ' ' + http_date + "\n" + rest_call_type.value + ' ' + '/api/v1/' + resource + ' HTTP/1.1' headers_line = 'date request-line' if data is not None: headers_line += ' digest' digest = "SHA-256=" + base64.b64encode(hashlib.new("sha256", json.dumps(data).encode('utf-8')).digest()).decode() message += "\ndigest" + ':' + ' ' + digest headers['Digest'] = digest signature = base64.b64encode(hmac.new(self.sec_key.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).digest()).decode() headers["Authorization"] = 'hmac username="' + self.api_key + \ '",algorithm="hmac-sha256",headers="' + headers_line + '",' + \ 'signature="' + signature + '"' headers["Content-Type"] = "application/json" def _preprocess_rest_response(self, status_code: int, headers: 'CIMultiDictProxy[str]', body: Optional[dict]) -> None: if str(status_code)[0] != '2': raise EterbaseRestException(status_code, body) def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0, ssl_context = None) -> WebsocketMgr: return EterbaseWebsocket(subscriptions = subscriptions, eterbase_client = self, account_id = self.account_id, ssl_context = ssl_context, startup_delay_ms = startup_delay_ms) async def get_ping(self) -> dict: return await self._create_get("ping") async def get_currencies(self) -> dict: return await self._create_get("assets") async def get_markets(self) -> dict: return await self._create_get("markets") async def get_balances(self) -> dict: return await self._create_get(f"accounts/{self.account_id}/balances", signed = True) async def get_token(self) -> dict: return await self._create_get(f"wstoken", signed = True) async def create_order(self, pair_id: str, side: enums.OrderSide, type: enums.OrderType, amount: str, price: str = None, stop_price: str = None, time_in_force: enums.TimeInForce = None, client_id: str = None, post_only: bool = None, cost: str = None) -> dict: data = { "accountId": self.account_id, "marketId": pair_id, "side": side.value, "type": type.value, "qty": amount, "limitPrice": price, "stopPrice": stop_price, "refId": client_id, "postOnly": post_only, "cost": cost } if time_in_force is not None: data['timeInForce'] = time_in_force.value return await self._create_post("orders", data = data, signed = True) async def cancel_order(self, order_id: str) -> dict: return await self._create_delete(f"orders/{order_id}", signed = True)
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/eterbase/functions.py
cryptoxlib/clients/eterbase/functions.py
from typing import List from cryptoxlib.Pair import Pair def map_pair(pair: Pair) -> str: return f"{pair.base}-{pair.quote}" def map_multiple_pairs(pairs : List[Pair], sort = False) -> List[str]: pairs = [pair.base + "-" + pair.quote for pair in pairs] if sort: return sorted(pairs) else: return pairs
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/eterbase/EterbaseWebsocket.py
cryptoxlib/clients/eterbase/EterbaseWebsocket.py
import json import logging import datetime import hmac import hashlib from typing import List, Any from cryptoxlib.WebsocketMgr import Subscription, WebsocketMgr, WebsocketMessage, Websocket, CallbacksType from cryptoxlib.clients.eterbase.exceptions import EterbaseException LOG = logging.getLogger(__name__) class EterbaseWebsocket(WebsocketMgr): WEBSOCKET_URI = "wss://api.eterbase.exchange/feed" MAX_MESSAGE_SIZE = 3 * 1024 * 1024 # 3MB def __init__(self, subscriptions: List[Subscription], eterbase_client, account_id: str = None, ssl_context = None, startup_delay_ms: int = 0) -> None: super().__init__(websocket_uri = self.WEBSOCKET_URI, subscriptions = subscriptions, ssl_context = ssl_context, builtin_ping_interval = None, auto_reconnect = True, max_message_size = self.MAX_MESSAGE_SIZE, periodic_timeout_sec = 30, startup_delay_ms = startup_delay_ms) self.eterbase_client = eterbase_client self.account_id = account_id def get_websocket(self) -> Websocket: return self.get_aiohttp_websocket() def get_websocket_uri_variable_part(self): for subscription in self.subscriptions: if subscription.requires_authentication() is True: return f"?wstoken={subscription.token}" return "" async def initialize_subscriptions(self, subscriptions: List[Subscription]) -> None: for subscription in subscriptions: await subscription.initialize(eterbase_client = self.eterbase_client) async def _process_periodic(self, websocket: Websocket) -> None: ping_msg = { "type": "ping" } LOG.debug(f"> {ping_msg}") await websocket.send(json.dumps(ping_msg)) async def send_subscription_message(self, subscriptions: List[Subscription]): for subscription in subscriptions: subscription_message = subscription.get_subscription_message(account_id = self.account_id) LOG.debug(f"> {subscription_message}") await self.websocket.send(json.dumps(subscription_message)) async def _process_message(self, websocket: Websocket, message: str) -> None: message = json.loads(message) if 'type' not in message: LOG.error(f"ERROR: Message without 'type' property received: {message}") elif message['type'] == 'pong': # ignore pong responses pass else: # regular message subscription_id = self._map_message_to_subscription_id(message) await self.publish_message(WebsocketMessage( subscription_id = subscription_id, message = message) ) def _map_message_to_subscription_id(self, message: dict): if message['type'] in ['ob_snapshot', 'ob_update']: return "order_book" elif message['type'] == 'trade': return "trade_history" elif message['type'] == 'ohlcv': return "ohlcv_tick" elif message['type'] in ["o_placed", "o_rejected", "o_fill", "o_closed", "o_triggered"]: return "account" else: return "" class EterbaseSubscription(Subscription): def __init__(self, callbacks: CallbacksType = None): super().__init__(callbacks) def requires_authentication(self) -> bool: return False class AccountSubscription(EterbaseSubscription): def __init__(self, market_ids: List[str], callbacks: CallbacksType = None): super().__init__(callbacks) self.market_ids = market_ids def get_subscription_message(self, **kwargs) -> dict: return { "type": "subscribe", "channelId": "my_orders", "marketIds": self.market_ids, "accountId": kwargs['account_id'] } def construct_subscription_id(self) -> Any: return "account" def requires_authentication(self) -> bool: return True async def initialize(self, **kwargs): eterbase_client = kwargs['eterbase_client'] token_response = await eterbase_client.get_token() self.token = token_response["response"]["wstoken"] LOG.debug(f'Token: {self.token}') class OrderbookSubscription(EterbaseSubscription): def __init__(self, market_ids: List[str], callbacks: CallbacksType = None): super().__init__(callbacks) self.market_ids = market_ids def get_subscription_message(self, **kwargs) -> dict: return { "type": "subscribe", "channelId": "order_book", "marketIds": self.market_ids } def construct_subscription_id(self) -> Any: return f"order_book" class OHLCVSubscription(EterbaseSubscription): def __init__(self, market_ids: List[str], callbacks: CallbacksType = None): super().__init__(callbacks) self.market_ids = market_ids def get_subscription_message(self, **kwargs) -> dict: return { "type": "subscribe", "channelId": "ohlcv_tick", "marketIds": self.market_ids } def construct_subscription_id(self) -> Any: return f"ohlcv_tick" class TradesSubscription(EterbaseSubscription): def __init__(self, market_ids: List[str], callbacks: CallbacksType = None): super().__init__(callbacks) self.market_ids = market_ids def get_subscription_message(self, **kwargs) -> dict: return { "type": "subscribe", "channelId": "trade_history", "marketIds": self.market_ids } def construct_subscription_id(self) -> Any: return f"trade_history"
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/aax/AAXWebsocket.py
cryptoxlib/clients/aax/AAXWebsocket.py
import json import logging import datetime import hashlib import hmac from abc import abstractmethod from typing import List, Callable, Any, Union, Optional from cryptoxlib.WebsocketMgr import Subscription, WebsocketMgr, WebsocketMessage, Websocket from cryptoxlib.Pair import Pair from cryptoxlib.clients.aax import enums from cryptoxlib.clients.aax.exceptions import AAXException from cryptoxlib.clients.aax.functions import map_pair from cryptoxlib.PeriodicChecker import PeriodicChecker LOG = logging.getLogger(__name__) class AAXWebsocket(WebsocketMgr): WEBSOCKET_URI = "wss://stream.aax.com/" def __init__(self, subscriptions: List[Subscription], api_key: str = None, sec_key: str = None, user_id: str = None, ssl_context = None) -> None: super().__init__(websocket_uri = self.WEBSOCKET_URI, subscriptions = subscriptions, ssl_context = ssl_context, builtin_ping_interval = None, auto_reconnect = True, periodic_timeout_sec = 5) self.api_key = api_key self.sec_key = sec_key def get_websocket(self) -> Websocket: return self.get_aiohttp_websocket() async def send_authentication_message(self): requires_authentication = False for subscription in self.subscriptions: if subscription.requires_authentication(): requires_authentication = True break if requires_authentication: handshake_message = '{"event":"#handshake","cid":1}' LOG.debug(f"> {handshake_message}") await self.websocket.send(handshake_message) handshake_response = await self.websocket.receive() LOG.debug(f"< {handshake_response}") timestamp_ms = int(datetime.datetime.now(tz = datetime.timezone.utc).timestamp() * 1000) signature_string = f"{timestamp_ms}:{self.api_key}" signature = hmac.new(self.sec_key.encode('utf-8'), signature_string.encode('utf-8'), hashlib.sha256).hexdigest() authentication_message = { "event": "login", "data": { "apiKey": self.api_key, "nonce": str(timestamp_ms), "signature": signature } } LOG.debug(f"> {authentication_message}") await self.websocket.send(json.dumps(authentication_message)) message = json.loads(await self.websocket.receive()) LOG.debug(f"< {message}") if 'data' in message and 'isAuthenticated' in message['data'] and message['data']['isAuthenticated'] is True: LOG.info(f"Websocket authenticated successfully.") else: raise AAXException(f"Authentication error. Response [{message}]") async def send_subscription_message(self, subscriptions: List[Subscription]): for subscription in subscriptions: LOG.debug(f"> {subscription.get_subscription_message()}") await self.websocket.send(json.dumps(subscription.get_subscription_message())) async def validate_subscriptions(self, subscriptions: List[Subscription]) -> None: pass def get_websocket_uri_variable_part(self): return self.subscriptions[0].get_stream_uri() async def _process_message(self, websocket: Websocket, message: str) -> None: if message == '#1': pong = '#2' LOG.debug(f"> {pong}") await websocket.send(pong) return message = json.loads(message) if message['e'] == 'empty': pass elif message['e'] == 'system': pass elif message['e'] == 'reply' and message['status'] == 'ok': LOG.info("Channel subscribed successfully.") elif message['e'] == 'reply' and message['status'] == 'error': raise AAXException(f"Websocket error message received: {message}") else: await self.publish_message(WebsocketMessage(subscription_id = self.map_subscription_id(message), message = message)) def map_subscription_id(self, message: dict): if "event" in message and message['event'] in ['USER_BALANCE', 'SPOT', 'FUTURES']: return "notification" else: return message['e'] class AAXSubscription(Subscription): def __init__(self, callbacks: Optional[List[Callable[[dict], Any]]] = None): super().__init__(callbacks) @abstractmethod def get_channel_name(self) -> str: pass @abstractmethod def get_stream_uri(self) -> str: pass def construct_subscription_id(self) -> Any: return self.get_channel_name() def get_subscription_message(self, **kwargs) -> dict: return { "e": "subscribe", "stream": self.get_channel_name() } def requires_authentication(self) -> bool: return False class OrderBookSubscription(AAXSubscription): def __init__(self, pair: Pair, depth: int, callbacks: Optional[List[Callable[[dict], Any]]] = None): super().__init__(callbacks) assert(depth in (20, 50)) self.pair = pair self.depth = depth def get_channel_name(self): return f"{map_pair(self.pair)}@book_{self.depth}" def get_stream_uri(self) -> str: return "marketdata/v2/" class AccountSubscription(AAXSubscription): def __init__(self, user_id: str, callbacks: Optional[List[Callable[[dict], Any]]] = None): super().__init__(callbacks) self.user_id = user_id def get_channel_name(self): return f"notification" def get_stream_uri(self) -> str: return "notification/v2/" def requires_authentication(self) -> bool: return True def get_subscription_message(self, **kwargs) -> dict: return { "e": "subscribe", "data": { "channel": f"user/{self.user_id}" }, "cid": 2 }
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/aax/enums.py
cryptoxlib/clients/aax/enums.py
import enum class OrderSide(enum.Enum): BUY = "BUY" SELL = "SELL" class OrderType(enum.Enum): MARKET = "MARKET" LIMIT = "LIMIT" STOP = "STOP" STOP_LIMIT = "STOP-LIMIT" class TimeInForce(enum.Enum): GOOD_TILL_CANCELLED = "GTC" IMMEDIATE_OR_CANCELLED = "IOC" FILL_OR_KILL = "FOK"
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/aax/AAXClient.py
cryptoxlib/clients/aax/AAXClient.py
import ssl import logging import hmac import hashlib import json from multidict import CIMultiDictProxy from typing import List, Optional from cryptoxlib.CryptoXLibClient import CryptoXLibClient, RestCallType from cryptoxlib.clients.aax import enums from cryptoxlib.Pair import Pair from cryptoxlib.clients.aax.exceptions import AAXRestException from cryptoxlib.WebsocketMgr import WebsocketMgr, Subscription from cryptoxlib.clients.aax.AAXWebsocket import AAXWebsocket from cryptoxlib.clients.aax.functions import map_pair LOG = logging.getLogger(__name__) class AAXClient(CryptoXLibClient): REST_API_URI = "https://api.aax.com/v2/" def __init__(self, api_key: str = None, sec_key: str = None, api_trace_log: bool = False, ssl_context: ssl.SSLContext = None) -> None: super().__init__(api_trace_log, ssl_context) self.api_key = api_key self.sec_key = sec_key def _get_rest_api_uri(self) -> str: return self.REST_API_URI def _sign_payload(self, rest_call_type: RestCallType, resource: str, data: dict = None, params: dict = None, headers: dict = None) -> None: timestamp = self._get_current_timestamp_ms() signature_string = f"{timestamp}:{rest_call_type.value}/v2/{resource}" if data is not None: signature_string += json.dumps(data) if params is not None: signature_string += json.dumps(params) LOG.debug(f"Signature input string: {signature_string}") signature = hmac.new(self.sec_key.encode('utf-8'), signature_string.encode('utf-8'), hashlib.sha256).hexdigest() headers['X-ACCESS-KEY'] = self.api_key headers['X-ACCESS-NONCE'] = str(timestamp) headers['X-ACCESS-SIGN'] = signature def _preprocess_rest_response(self, status_code: int, headers: 'CIMultiDictProxy[str]', body: Optional[dict]) -> None: if str(status_code)[0] != '2': raise AAXRestException(status_code, body) def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0, ssl_context = None) -> WebsocketMgr: return AAXWebsocket(subscriptions, self.api_key, self.sec_key, ssl_context) async def get_exchange_info(self) -> dict: return await self._create_get("instruments") async def get_funds(self) -> dict: return await self._create_get("user/balances", signed = True) async def get_user_info(self) -> dict: return await self._create_get("user/info", signed = True) async def create_spot_order(self, pair: Pair, type: enums.OrderType, side: enums.OrderSide, amount: str, price: str = None, stop_price: str = None, time_in_force: enums.TimeInForce = None, client_id: str = None) -> dict: data = self._clean_request_params({ "symbol": map_pair(pair), "side": side.value, "orderType": type.value, "orderQty": amount, "price": price, "stopPrice": stop_price, "clOrdID": client_id }) if time_in_force is not None: data['timeInForce'] = time_in_force.value return await self._create_post("spot/orders", data = data, signed = True) async def update_spot_order(self, order_id: str, amount: str, price: str = None, stop_price: str = None) -> dict: data = self._clean_request_params({ "orderId": order_id, "orderQty": amount, "price": price, "stopPrice": stop_price }) return await self._create_put("spot/orders", data = data, signed = True) async def cancel_spot_order(self, order_id: str) -> dict: return await self._create_delete(f"spot/orders/cancel/{order_id}", signed = True) async def cancel_batch_spot_order(self, pair: Pair, order_id: str = None, client_id: str = None) -> dict: data = self._clean_request_params({ "symbol": map_pair(pair), "orderId": order_id, "clOrdID": client_id }) return await self._create_delete("spot/orders/cancel/all", data = data, signed = True) async def cancel_all_spot_order(self, timeout_ms: int) -> dict: data = { "timeout": timeout_ms } return await self._create_post("spot/orders/cancelAllOnTimeout", data = data, signed = True)
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/aax/exceptions.py
cryptoxlib/clients/aax/exceptions.py
from typing import Optional from cryptoxlib.exceptions import CryptoXLibException class AAXException(CryptoXLibException): pass class AAXRestException(AAXException): def __init__(self, status_code: int, body: Optional[dict]): super().__init__(f"Rest API exception: status [{status_code}], response [{body}]") self.status_code = status_code self.body = body
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/aax/__init__.py
cryptoxlib/clients/aax/__init__.py
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/aax/functions.py
cryptoxlib/clients/aax/functions.py
from cryptoxlib.Pair import Pair def map_pair(pair: Pair) -> str: return f"{pair.base}{pair.quote}"
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/hitbtc/enums.py
cryptoxlib/clients/hitbtc/enums.py
import enum class OrderSide(enum.Enum): BUY = "buy" SELL = "sell" class OrderType(enum.Enum): MARKET = "market" LIMIT = "limit" STOP_LIMIT = "stopLimit" class TimeInForce(enum.Enum): GOOD_TILL_CANCELLED = "GTC" IMMEDIATE_OR_CANCELLED = "IOC" FILL_OR_KILL = "FOK" DAY = "Day" GOOD_TILL_DATE = "GTD"
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/hitbtc/exceptions.py
cryptoxlib/clients/hitbtc/exceptions.py
from typing import Optional from cryptoxlib.exceptions import CryptoXLibException class HitbtcException(CryptoXLibException): pass class HitbtcRestException(HitbtcException): def __init__(self, status_code: int, body: Optional[dict]): super().__init__(f"Rest API exception: status [{status_code}], response [{body}]") self.status_code = status_code self.body = body
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/hitbtc/HitbtcClient.py
cryptoxlib/clients/hitbtc/HitbtcClient.py
import ssl import logging import base64 import datetime import pytz from multidict import CIMultiDictProxy from typing import List, Optional from cryptoxlib.CryptoXLibClient import CryptoXLibClient, RestCallType from cryptoxlib.clients.hitbtc import enums from cryptoxlib.clients.hitbtc.exceptions import HitbtcRestException from cryptoxlib.clients.hitbtc.functions import map_pair from cryptoxlib.Pair import Pair from cryptoxlib.WebsocketMgr import WebsocketMgr, Subscription from cryptoxlib.clients.hitbtc.HitbtcWebsocket import HitbtcWebsocket LOG = logging.getLogger(__name__) class HitbtcClient(CryptoXLibClient): REST_API_URI = "https://api.hitbtc.com/api/2/" def __init__(self, api_key: str = None, sec_key: str = None, api_trace_log: bool = False, ssl_context: ssl.SSLContext = None) -> None: super().__init__(api_trace_log, ssl_context) self.api_key = api_key self.sec_key = sec_key def _get_rest_api_uri(self) -> str: return self.REST_API_URI def _sign_payload(self, rest_call_type: RestCallType, resource: str, data: dict = None, params: dict = None, headers: dict = None) -> None: headers["Authorization"] = "Basic " + base64.b64encode(bytes(f"{self.api_key}:{self.sec_key}", "utf-8")).decode('utf-8') def _preprocess_rest_response(self, status_code: int, headers: 'CIMultiDictProxy[str]', body: Optional[dict]) -> None: if str(status_code)[0] != '2': raise HitbtcRestException(status_code, body) def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0, ssl_context = None) -> WebsocketMgr: return HitbtcWebsocket(subscriptions, self.api_key, self.sec_key, ssl_context, startup_delay_ms) async def get_currencies(self, currencies: List[str] = None) -> dict: params = {} if currencies: params['currencies'] = ','.join(currencies) return await self._create_get("public/currency", params = params) async def get_currency(self, currency: str) -> dict: return await self._create_get(f"public/currency/{currency}") async def get_symbols(self, pairs: List[Pair] = None) -> dict: params = {} if pairs is not None: params['symbols'] = ','.join(map_pair(pair) for pair in pairs) return await self._create_get("public/symbol", params = params) async def get_symbol(self, pair: Pair) -> dict: return await self._create_get(f"public/symbol/{map_pair(pair)}") async def get_tickers(self, pairs: List[Pair] = None) -> dict: params = {} if pairs is not None: params['symbols'] = ','.join(map_pair(pair) for pair in pairs) return await self._create_get("public/ticker", params = params) async def get_ticker(self, pair: Pair) -> dict: return await self._create_get(f"public/ticker/{map_pair(pair)}") async def get_order_books(self, limit: int = None, pairs: List[Pair] = None) -> dict: params = self._clean_request_params({ "limit": limit }) if pairs is not None: params['symbols'] = ','.join(map_pair(pair) for pair in pairs) return await self._create_get("public/orderbook", params = params) async def get_order_book(self, pair: Pair, limit: int = None, volume: int = None) -> dict: params = self._clean_request_params({ "limit": limit, "volume": volume }) return await self._create_get(f"public/orderbook/{map_pair(pair)}", params = params) async def get_balance(self) -> dict: return await self._create_get(f"trading/balance", signed = True) async def create_order(self, pair: Pair, side: enums.OrderSide, type: enums.OrderType, amount: str, price: str = None, stop_price: str = None, time_in_force: enums.TimeInForce = None, client_id: str = None, expire_time: datetime.datetime = None, strict_validate: bool = None, post_only: bool = None) -> dict: data = { "symbol": map_pair(pair), "side": side.value, "type": type.value, "quantity": amount, "price": price, "stopPrice": stop_price, "clientOrderId": client_id, "strictValidate": strict_validate, "postOnly": post_only } if time_in_force is not None: data['timeInForce'] = time_in_force.value if expire_time: data["expireTime"] = expire_time.astimezone(pytz.utc).isoformat() return await self._create_post("order", data = data, signed = True) async def cancel_orders(self, pair: Pair = None) -> dict: params = {} if pair is not None: params['symbol'] = map_pair(pair) return await self._create_delete(f"order", params = params, signed = True) async def cancel_order(self, client_id: str) -> dict: return await self._create_delete(f"order/{client_id}", signed = True)
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/hitbtc/__init__.py
cryptoxlib/clients/hitbtc/__init__.py
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/hitbtc/HitbtcWebsocket.py
cryptoxlib/clients/hitbtc/HitbtcWebsocket.py
import json import logging import datetime import hmac import pytz import hashlib from typing import List, Any from cryptoxlib.WebsocketMgr import Subscription, WebsocketMgr, WebsocketMessage, Websocket, CallbacksType, \ ClientWebsocketHandle, WebsocketOutboundMessage from cryptoxlib.Pair import Pair from cryptoxlib.clients.hitbtc.functions import map_pair from cryptoxlib.clients.hitbtc.exceptions import HitbtcException from cryptoxlib.clients.hitbtc import enums LOG = logging.getLogger(__name__) class HitbtcWebsocket(WebsocketMgr): WEBSOCKET_URI = "wss://api.hitbtc.com/api/2/ws" MAX_MESSAGE_SIZE = 3 * 1024 * 1024 # 3MB def __init__(self, subscriptions: List[Subscription], api_key: str = None, sec_key: str = None, ssl_context = None, startup_delay_ms: int = 0) -> None: super().__init__(websocket_uri = self.WEBSOCKET_URI, subscriptions = subscriptions, ssl_context = ssl_context, builtin_ping_interval = None, auto_reconnect = True, max_message_size = self.MAX_MESSAGE_SIZE, startup_delay_ms = startup_delay_ms) self.api_key = api_key self.sec_key = sec_key def get_websocket(self) -> Websocket: return self.get_aiohttp_websocket() async def send_authentication_message(self): requires_authentication = False for subscription in self.subscriptions: if subscription.requires_authentication(): requires_authentication = True break if requires_authentication: timestamp_ms = str(int(datetime.datetime.now(tz = datetime.timezone.utc).timestamp() * 1000)) signature = hmac.new(self.sec_key.encode('utf-8'), timestamp_ms.encode('utf-8'), hashlib.sha256).hexdigest() authentication_message = { "method": "login", "params": { "algo": "HS256", "pKey": self.api_key, "nonce": timestamp_ms, "signature": signature } } LOG.debug(f"> {authentication_message}") await self.websocket.send(json.dumps(authentication_message)) message = await self.websocket.receive() LOG.debug(f"< {message}") message = json.loads(message) if 'result' in message and message['result'] == True: LOG.info(f"Authenticated websocket connected successfully.") else: raise HitbtcException(f"Authentication error. Response [{message}]") async def send_subscription_message(self, subscriptions: List[Subscription]): for subscription in subscriptions: subscription_message = subscription.get_subscription_message() LOG.debug(f"> {subscription_message}") await self.websocket.send(json.dumps(subscription_message)) async def _process_message(self, websocket: Websocket, message: str) -> None: message = json.loads(message) if 'id' in message and 'result' in message and message['result'] == True: # subscription confirmation # for confirmed account channel publish the confirmation downstream in order to communicate the websocket handle for subscription in self.subscriptions: if subscription.external_id == message['id'] and subscription.get_subscription_id() == 'account': await self.publish_message(WebsocketMessage( subscription_id = 'account', message = message, websocket = ClientWebsocketHandle(websocket = websocket) )) else: # regular message subscription_id = self._map_message_to_subscription_id(message) await self.publish_message(WebsocketMessage( subscription_id = subscription_id, message = message, # for account channel communicate also the websocket handle websocket = ClientWebsocketHandle(websocket = websocket) if subscription_id == 'account' else None ) ) def _map_message_to_subscription_id(self, message: dict): if 'method' in message: if message['method'] in ['snapshotOrderbook', 'updateOrderbook']: return f"orderbook{message['params']['symbol']}" elif message['method'] == 'ticker': return f"{message['method']}{message['params']['symbol']}" elif message['method'] in ['snapshotTrades', 'updateTrades']: return f"trades{message['params']['symbol']}" elif message['method'] in ['activeOrders', 'report']: return "account" elif 'error' in message and 'id' in message: for subscription in self.subscriptions: if subscription.external_id == message['id']: return subscription.get_subscription_id() # if error message does not belong to any subscription based on the id, then assume it relates # to a placed order and send it to the account channel return "account" else: return "" class HitbtcSubscription(Subscription): EXTERNAL_SUBSCRIPTION_ID = 0 def __init__(self, callbacks: CallbacksType = None): super().__init__(callbacks) self.external_id = HitbtcSubscription.generate_new_external_id() def requires_authentication(self) -> bool: return False @staticmethod def generate_new_external_id(): HitbtcSubscription.EXTERNAL_SUBSCRIPTION_ID += 1 return HitbtcSubscription.EXTERNAL_SUBSCRIPTION_ID class AccountSubscription(HitbtcSubscription): def __init__(self, callbacks: CallbacksType = None): super().__init__(callbacks) def get_subscription_message(self, **kwargs) -> dict: return { "method": "subscribeReports", "params": {}, "id": self.external_id } def construct_subscription_id(self) -> Any: return "account" def requires_authentication(self) -> bool: return True class OrderbookSubscription(HitbtcSubscription): def __init__(self, pair: Pair, callbacks: CallbacksType = None): super().__init__(callbacks) self.pair = pair def get_subscription_message(self, **kwargs) -> dict: return { "method": "subscribeOrderbook", "params": { "symbol": map_pair(self.pair), }, "id": self.external_id } def construct_subscription_id(self) -> Any: return f"orderbook{map_pair(self.pair)}" class TickerSubscription(HitbtcSubscription): def __init__(self, pair: Pair, callbacks: CallbacksType = None): super().__init__(callbacks) self.pair = pair def get_subscription_message(self, **kwargs) -> dict: return { "method": "subscribeTicker", "params": { "symbol": map_pair(self.pair), }, "id": self.external_id } def construct_subscription_id(self) -> Any: return f"ticker{map_pair(self.pair)}" class TradesSubscription(HitbtcSubscription): def __init__(self, pair: Pair, limit: int = None, callbacks: CallbacksType = None): super().__init__(callbacks) self.pair = pair self.limit = limit def get_subscription_message(self, **kwargs) -> dict: params = { "method": "subscribeTrades", "params": { "symbol": map_pair(self.pair), }, "id": self.external_id } if self.limit is not None: params['params']['limit'] = self.limit return params def construct_subscription_id(self) -> Any: return f"trades{map_pair(self.pair)}" class CreateOrderMessage(WebsocketOutboundMessage): def __init__(self, pair: Pair, side: enums.OrderSide, type: enums.OrderType, amount: str,client_id: str, price: str = None, stop_price: str = None, time_in_force: enums.TimeInForce = None, expire_time: datetime.datetime = None, strict_validate: bool = None, post_only: bool = None): self.pair = pair self.type = type self.side = side self.amount = amount self.price = price self.stop_price = stop_price self.time_in_force = time_in_force self.client_id = client_id self.expire_time = expire_time self.strict_validate = strict_validate self.post_only = post_only def to_json(self): id = HitbtcSubscription.generate_new_external_id() ret = { "method": "newOrder", "params": { "symbol": map_pair(self.pair), "side": self.side.value, "type": self.type.value, "quantity": self.amount, 'clientOrderId': self.client_id }, "id": id } if self.price is not None: ret['params']['price'] = self.price if self.stop_price is not None: ret['params']['stopPrice'] = self.stop_price if self.strict_validate is not None: ret['params']['strictValidate'] = self.strict_validate if self.post_only is not None: ret['params']['postOnly'] = self.post_only if self.time_in_force is not None: ret['params']['timeInForce'] = self.time_in_force.value if self.expire_time: ret['parms']["expireTime"] = self.expire_time.astimezone(pytz.utc).isoformat() return ret class CancelOrderMessage(WebsocketOutboundMessage): def __init__(self, client_id: str): self.client_id = client_id def to_json(self): id = HitbtcSubscription.generate_new_external_id() ret = { 'method': 'cancelOrder', 'params': { "clientOrderId": self.client_id }, 'id': id } return ret
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/hitbtc/functions.py
cryptoxlib/clients/hitbtc/functions.py
from typing import List from cryptoxlib.Pair import Pair def map_pair(pair: Pair) -> str: return f"{pair.base.upper()}{pair.quote.upper()}" def map_multiple_pairs(pairs : List[Pair], sort = False) -> List[str]: pairs = [pair.base + "_" + pair.quote for pair in pairs] if sort: return sorted(pairs) else: return pairs
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/liquid/enums.py
cryptoxlib/clients/liquid/enums.py
import enum class OrderType(enum.Enum): MARKET = "market" LIMIT = "limit" class OrderSide(enum.Enum): BUY = "buy" SELL = "sell"
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/liquid/exceptions.py
cryptoxlib/clients/liquid/exceptions.py
from cryptoxlib.exceptions import CryptoXLibException class LiquidException(CryptoXLibException): pass
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/liquid/LiquidWebsocket.py
cryptoxlib/clients/liquid/LiquidWebsocket.py
import json import jwt import time import logging import websockets from abc import abstractmethod from typing import List, Callable, Any, Optional from cryptoxlib.WebsocketMgr import Subscription, WebsocketMgr, WebsocketMessage, Websocket from cryptoxlib.Pair import Pair from cryptoxlib.clients.liquid.functions import map_pair from cryptoxlib.clients.liquid import enums from cryptoxlib.clients.liquid.exceptions import LiquidException from cryptoxlib.PeriodicChecker import PeriodicChecker LOG = logging.getLogger(__name__) class LiquidWebsocket(WebsocketMgr): WEBSOCKET_URI = "wss://tap.liquid.com/app/LiquidTapClient" def __init__(self, subscriptions: List[Subscription], api_key: str = None, sec_key: str = None, ssl_context = None) -> None: super().__init__(websocket_uri = self.WEBSOCKET_URI, subscriptions = subscriptions, builtin_ping_interval = None, periodic_timeout_sec = 10, ssl_context = ssl_context) self.api_key = api_key self.sec_key = sec_key self.ping_checker = PeriodicChecker(period_ms = 60 * 1000) async def send_subscription_message(self, subscriptions: List[Subscription]): authentication_payload = { "token_id": self.api_key, "path": '/realtime', "nonce": int(time.time_ns()) } LOG.debug(f"Authentication payload: {authentication_payload}") signature = jwt.encode(authentication_payload, self.sec_key, 'HS256') authentication_data = { "headers": { "X-Quoine-Auth": signature.decode('utf-8') }, "path": "/realtime" } authentication_request = { "event": "quoine:auth_request", "data": authentication_data } LOG.debug(f"> {authentication_request}") await self.websocket.send(json.dumps(authentication_request)) async def _process_periodic(self, websocket: Websocket) -> None: if self.ping_checker.check(): ping_message = { "event": "pusher:ping", "data": '' } LOG.debug(f"> {ping_message}") await websocket.send(json.dumps(ping_message)) async def _process_message(self, websocket: Websocket, message: str) -> None: message = json.loads(message) if message['event'] == "pusher:connection_established": pass elif message['event'] == "pusher:pong": pass elif message['event'] == "quoine:auth_success": subscription_messages = [] for subscription in self.subscriptions: subscription_message = subscription.get_subscription_message() subscription_messages.append(subscription_message) LOG.debug(f"> {subscription_messages}") await websocket.send(json.dumps(subscription_messages)) elif message['event'] == "quoine:auth_failure": raise LiquidException(f"Websocket authentication error: {message}") elif message['event'] == "pusher_internal:subscription_succeeded": LOG.info(f'Websocket subscribed successfuly: {message}') elif message['event'] == "updated": await self.publish_message(WebsocketMessage(subscription_id = message['channel'], message = message)) else: raise LiquidException(f"Websocket unknown event type: {message}") class LiquidSubscription(Subscription): def __init__(self, callbacks: Optional[List[Callable[[dict], Any]]] = None): super().__init__(callbacks) @abstractmethod def get_channel_name(self) -> str: pass def construct_subscription_id(self) -> Any: return self.get_channel_name() def get_subscription_message(self, **kwargs) -> dict: return { "event": "pusher:subscribe", "data": { "channel": self.get_channel_name() }, } class OrderBookSideSubscription(LiquidSubscription): def __init__(self, pair: Pair, order_side: enums.OrderSide, callbacks: Optional[List[Callable[[dict], Any]]] = None): super().__init__(callbacks) self.pair = pair self.order_side = order_side def get_channel_name(self): return f"price_ladders_cash_{map_pair(self.pair)}_{self.order_side.value}" class OrderBookSubscription(LiquidSubscription): def __init__(self, pair: Pair, callbacks: Optional[List[Callable[[dict], Any]]] = None): super().__init__(callbacks) self.pair = pair def get_channel_name(self): return f"price_ladders_cash_{map_pair(self.pair)}" class OrderSubscription(LiquidSubscription): def __init__(self, quote: str, callbacks: Optional[List[Callable[[dict], Any]]] = None): super().__init__(callbacks) self.quote = quote def get_channel_name(self): return f"user_account_{self.quote.lower()}_orders" class TradeSubscription(LiquidSubscription): def __init__(self, currency: str, callbacks: Optional[List[Callable[[dict], Any]]] = None): super().__init__(callbacks) self.currency = currency def get_channel_name(self): return f"user_account_{self.currency.lower()}_trades" class ExecutionsSubscription(LiquidSubscription): def __init__(self, pair: Pair, callbacks: Optional[List[Callable[[dict], Any]]] = None): super().__init__(callbacks) self.pair = pair def get_channel_name(self): return f"user_executions_cash_{map_pair(self.pair)}"
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/liquid/__init__.py
cryptoxlib/clients/liquid/__init__.py
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/liquid/functions.py
cryptoxlib/clients/liquid/functions.py
from cryptoxlib.Pair import Pair def map_pair(pair: Pair) -> str: return f"{pair.base.lower()}{pair.quote.lower()}"
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/liquid/LiquidClient.py
cryptoxlib/clients/liquid/LiquidClient.py
import ssl import logging import jwt from multidict import CIMultiDictProxy from typing import List, Optional from cryptoxlib.CryptoXLibClient import CryptoXLibClient, RestCallType from cryptoxlib.clients.liquid import enums from cryptoxlib.clients.liquid.exceptions import LiquidException from cryptoxlib.WebsocketMgr import WebsocketMgr, Subscription from cryptoxlib.clients.liquid.LiquidWebsocket import LiquidWebsocket LOG = logging.getLogger(__name__) class LiquidClient(CryptoXLibClient): REST_API_URI = "https://api.liquid.com/" def __init__(self, api_key: str = None, sec_key: str = None, api_trace_log: bool = False, ssl_context: ssl.SSLContext = None) -> None: super().__init__(api_trace_log, ssl_context) self.api_key = api_key self.sec_key = sec_key def _get_rest_api_uri(self) -> str: return self.REST_API_URI def _sign_payload(self, rest_call_type: RestCallType, resource: str, data: dict = None, params: dict = None, headers: dict = None) -> None: authentication_payload = { "path": "/" + resource, "nonce": self._get_unix_timestamp_ns(), "token_id": self.api_key } LOG.debug(f"Authentication payload: {authentication_payload}") signature = jwt.encode(authentication_payload, self.sec_key, 'HS256') headers["X-Quoine-Auth"] = signature.decode('utf-8') def _preprocess_rest_response(self, status_code: int, headers: 'CIMultiDictProxy[str]', body: Optional[dict]) -> None: if str(status_code)[0] != '2': raise LiquidException(f"LiquidException: status [{status_code}], response [{body}]") def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0, ssl_context = None) -> WebsocketMgr: return LiquidWebsocket(subscriptions, self.api_key, self.sec_key, ssl_context) @staticmethod def _get_headers() -> dict: return { 'X-Quoine-API-Version': '2', 'Content-Type': 'application/json' } async def get_products(self) -> dict: return await self._create_get("products", headers = self._get_headers()) async def get_product(self, product_id: str) -> dict: return await self._create_get("products/" + product_id, headers = self._get_headers()) async def get_order_book(self, product_id: str, full: bool = False) -> dict: params = {} if full: params['full'] = 1 return await self._create_get("products/" + product_id + "/price_levels", params = params, headers = self._get_headers()) async def get_order(self, order_id: str) -> dict: return await self._create_get("orders/" + order_id, headers = self._get_headers(), signed = True) async def create_order(self, product_id: str, order_type: enums.OrderType, order_side: enums.OrderSide, quantity: str, price: str, client_order_id: str = None) -> dict: data = CryptoXLibClient._clean_request_params({ "product_id": int(product_id), "price": price, "quantity": quantity, "order_type": order_type.value, "side": order_side.value, "client_order_id": client_order_id }) return await self._create_post("orders", data = data, headers = self._get_headers(), signed = True) async def cancel_order(self, order_id: str) -> dict: return await self._create_put("orders/" + order_id + "/cancel", headers = self._get_headers(), signed = True) async def get_crypto_accounts(self) -> dict: return await self._create_get("crypto_accounts", headers = self._get_headers(), signed = True) async def get_fiat_accounts(self) -> dict: return await self._create_get("fiat_accounts", headers = self._get_headers(), signed = True) async def get_account_details(self, currency: str): return await self._create_get(f"accounts/{currency}", headers = self._get_headers(), signed = True) async def get_currencies(self) -> dict: return await self._create_get("currencies", headers = self._get_headers())
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/onetrading/enums.py
cryptoxlib/clients/onetrading/enums.py
import enum class OrderType(enum.Enum): MARKET = "MARKET" LIMIT = "LIMIT" STOP_LIMIT = "STOP" class OrderSide(enum.Enum): BUY = "BUY" SELL = "SELL" class TimeInForce(enum.Enum): GOOD_TILL_CANCELLED = "GOOD_TILL_CANCELLED" IMMEDIATE_OR_CANCELLED = "IMMEDIATE_OR_CANCELLED" FILL_OR_KILL = "FILL_OR_KILL" GOOD_TILL_TIME = "GOOD_TILL_TIME" class TimeUnit(enum.Enum): MINUTES = "MINUTES" HOURS = "HOURS" DAYS = "DAYS" WEEKS = "WEEKS" MONTHS = "MONTHS" class PricePointsMode(enum.Enum): SPLIT = 'SPLIT' INLINE = 'INLINE' OMIT = 'OMIT'
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/onetrading/OneTradingClient.py
cryptoxlib/clients/onetrading/OneTradingClient.py
import ssl import logging import datetime import pytz from multidict import CIMultiDictProxy from typing import List, Optional from cryptoxlib.CryptoXLibClient import CryptoXLibClient, RestCallType from cryptoxlib.clients.onetrading import enums from cryptoxlib.clients.onetrading.exceptions import OneTradingRestException, OneTradingException from cryptoxlib.clients.onetrading.functions import map_pair from cryptoxlib.Pair import Pair from cryptoxlib.WebsocketMgr import WebsocketMgr, Subscription from cryptoxlib.clients.onetrading.OneTradingWebsocket import OneTradingWebsocket LOG = logging.getLogger(__name__) class OneTradingClient(CryptoXLibClient): REST_API_URI = "https://api.onetrading.com/public/v1/" def __init__(self, api_key: str = None, api_trace_log: bool = False, ssl_context: ssl.SSLContext = None) -> None: super().__init__(api_trace_log, ssl_context) self.api_key = api_key def _get_rest_api_uri(self) -> str: return self.REST_API_URI def _sign_payload(self, rest_call_type: RestCallType, resource: str, data: dict = None, params: dict = None, headers: dict = None) -> None: headers["Authorization"] = "Bearer " + self.api_key def _preprocess_rest_response(self, status_code: int, headers: 'CIMultiDictProxy[str]', body: Optional[dict]) -> None: if str(status_code)[0] != '2': raise OneTradingRestException(status_code, body) def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0, ssl_context = None) -> WebsocketMgr: return OneTradingWebsocket(subscriptions = subscriptions, api_key = self.api_key, ssl_context = ssl_context, startup_delay_ms = startup_delay_ms) async def get_currencies(self) -> dict: return await self._create_get("currencies") async def get_fee_groups(self) -> dict: return await self._create_get("fees") async def get_account_balances(self) -> dict: return await self._create_get("account/balances", signed = True) async def get_account_fees(self) -> dict: return await self._create_get("account/fees", signed = True) async def get_account_orders(self, from_timestamp: datetime.datetime = None, to_timestamp: datetime.datetime = None, pair: Pair = None, with_cancelled_and_rejected: str = None, with_just_filled_inactive: str = None, with_just_orders: str = None, max_page_size: str = None, cursor: str = None) -> dict: params = OneTradingClient._clean_request_params({ "with_cancelled_and_rejected": with_cancelled_and_rejected, "with_just_filled_inactive": with_just_filled_inactive, "with_just_orders": with_just_orders, "max_page_size": max_page_size, "cursor": cursor, }) if pair is not None: params["instrument_code"] = map_pair(pair) if from_timestamp is not None: params["from"] = from_timestamp.astimezone(pytz.utc).isoformat() if to_timestamp is not None: params["to"] = to_timestamp.astimezone(pytz.utc).isoformat() return await self._create_get("account/orders", params = params, signed = True) async def get_account_order(self, order_id: str) -> dict: return await self._create_get("account/orders/" + order_id, signed = True) async def get_account_order_trades(self, order_id: str) -> dict: return await self._create_get("account/orders/" + order_id + "/trades", signed = True) async def get_account_trades(self, from_timestamp: datetime.datetime = None, to_timestamp: datetime.datetime = None, pair: Pair = None, max_page_size: str = None, cursor: str = None) -> dict: params = OneTradingClient._clean_request_params({ "max_page_size": max_page_size, "cursor": cursor, }) if pair is not None: params["instrument_code"] = map_pair(pair) if from_timestamp is not None: params["from"] = from_timestamp.astimezone(pytz.utc).isoformat() if to_timestamp is not None: params["to"] = to_timestamp.astimezone(pytz.utc).isoformat() return await self._create_get("account/trades", params = params, signed = True) async def get_account_trade(self, trade_id: str) -> dict: return await self._create_get("account/trades/" + trade_id, signed = True) async def get_account_trading_volume(self) -> dict: return await self._create_get("account/trading-volume", signed = True) async def create_market_order(self, pair: Pair, side: enums.OrderSide, amount: str, client_id: str = None) -> dict: data = { "instrument_code": map_pair(pair), "side": side.value, "type": enums.OrderType.MARKET.value, "amount": amount } if client_id is not None: data['client_id'] = client_id return await self._create_post("account/orders", data = data, signed = True) async def create_limit_order(self, pair: Pair, side: enums.OrderSide, amount: str, limit_price: str, time_in_force: enums.TimeInForce = None, client_id: str = None) -> dict: data = { "instrument_code": map_pair(pair), "side": side.value, "type": enums.OrderType.LIMIT.value, "amount": amount, "price": limit_price } if client_id is not None: data['client_id'] = client_id if time_in_force is not None: data['time_in_force'] = time_in_force.value return await self._create_post("account/orders", data = data, signed = True) async def create_stop_limit_order(self, pair: Pair, side: enums.OrderSide, amount: str, limit_price: str, stop_price: str, time_in_force: enums.TimeInForce = None, client_id: str = None) -> dict: data = { "instrument_code": map_pair(pair), "side": side.value, "type": enums.OrderType.STOP_LIMIT.value, "amount": amount, "price": limit_price, "trigger_price": stop_price } if client_id is not None: data['client_id'] = client_id if time_in_force is not None: data['time_in_force'] = time_in_force.value return await self._create_post("account/orders", data = data, signed = True) async def delete_account_orders(self, pair: Pair = None, ids: List[str] = None) -> dict: params = {} if pair is not None: params["instrument_code"] = map_pair(pair) if ids is not None: params['ids'] = ','.join(ids) return await self._create_delete("account/orders", params = params, signed = True) async def delete_account_order(self, order_id: str = None, client_id: str = None) -> dict: if order_id is None and client_id is None: raise OneTradingException('One of order_id/client_id has to be provided.') if order_id is not None and client_id is not None: raise OneTradingException('Only one of order_id/client_id can be provided.') if order_id is not None: return await self._create_delete("account/orders/" + order_id, signed = True) else: return await self._create_delete("account/orders/client/" + client_id, signed = True) async def update_order(self, amount: str, order_id: str = None, client_id: str = None) -> dict: if order_id is None and client_id is None: raise OneTradingException('One of order_id/client_id has to be provided.') if order_id is not None and client_id is not None: raise OneTradingException('Only one of order_id/client_id can be provided.') data = { "amount": amount } if order_id is not None: return await self._create_put("account/orders/" + order_id, data = data, signed = True) else: return await self._create_put("account/orders/client/" + client_id, data = data, signed = True) async def get_candlesticks(self, pair: Pair, unit: enums.TimeUnit, period: str, from_timestamp: datetime.datetime, to_timestamp: datetime.datetime) -> dict: params = { "unit": unit.value, "period": period, "from": from_timestamp.astimezone(pytz.utc).isoformat(), "to": to_timestamp.astimezone(pytz.utc).isoformat(), } return await self._create_get("candlesticks/" + map_pair(pair), params = params) async def get_instruments(self) -> dict: return await self._create_get("instruments") async def get_order_book(self, pair: Pair, level: str = None, depth: str = None) -> dict: params = OneTradingClient._clean_request_params({ "level": level, "depth": depth }) return await self._create_get("order-book/" + map_pair(pair), params = params) async def get_time(self) -> dict: return await self._create_get("time") async def get_market_tickers(self) -> dict: return await self._create_get("market-ticker") async def get_market_ticker(self, pair: Pair) -> dict: return await self._create_get("market-ticker/" + map_pair(pair)) async def get_price_tick(self, pair: Pair, from_timestamp: datetime.datetime = None, to_timestamp: datetime.datetime = None) -> dict: params = {} if from_timestamp is not None: params['from'] = from_timestamp.astimezone(pytz.utc).isoformat() if to_timestamp is not None: params['to'] = to_timestamp.astimezone(pytz.utc).isoformat() return await self._create_get("price-ticks/" + map_pair(pair), params = params) async def create_deposit_crypto_address(self, currency: str) -> dict: data = { "currency": currency } return await self._create_post("account/deposit/crypto", data = data, signed = True) async def get_deposit_crypto_address(self, currency: str) -> dict: return await self._create_get("account/deposit/crypto/" + currency, signed = True) async def get_fiat_deposit_info(self) -> dict: return await self._create_get("account/deposit/fiat/EUR", signed = True) async def withdraw_crypto(self, currency: str, amount: str, address: str, destination_tag: str = None) -> dict: data = { 'currency': currency, 'amount': amount, 'recipient': { 'address': address } } if destination_tag is not None: data['recipient']['destination_tag'] = destination_tag return await self._create_post("account/withdraw/crypto", data = data, signed = True) async def withdraw_fiat(self, currency: str, amount: str, payout_account_id: str) -> dict: data = { 'currency': currency, 'amount': amount, 'payout_account_id': payout_account_id } return await self._create_post("account/withdraw/fiat", data = data, signed = True) async def get_deposits(self, from_timestamp: datetime.datetime = None, to_timestamp: datetime.datetime = None, currency: str = None, max_page_size: int = None, cursor: int = None) -> dict: params = self._clean_request_params({ 'currency_code': currency, 'max_page_size': max_page_size, 'cursor': cursor }) if from_timestamp is not None: params['from'] = from_timestamp.astimezone(pytz.utc).isoformat() if to_timestamp is not None: params['to'] = to_timestamp.astimezone(pytz.utc).isoformat() return await self._create_get("account/deposits", params = params, signed = True) async def get_onetrading_deposits(self, from_timestamp: datetime.datetime = None, to_timestamp: datetime.datetime = None, currency: str = None, max_page_size: int = None, cursor: int = None) -> dict: params = self._clean_request_params({ 'currency_code': currency, 'max_page_size': max_page_size, 'cursor': cursor }) if from_timestamp is not None: params['from'] = from_timestamp.astimezone(pytz.utc).isoformat() if to_timestamp is not None: params['to'] = to_timestamp.astimezone(pytz.utc).isoformat() return await self._create_get("account/deposits/onetrading", params = params, signed = True) async def get_withdrawals(self, from_timestamp: datetime.datetime = None, to_timestamp: datetime.datetime = None, currency: str = None, max_page_size: int = None, cursor: int = None) -> dict: params = self._clean_request_params({ 'currency_code': currency, 'max_page_size': max_page_size, 'cursor': cursor }) if from_timestamp is not None: params['from'] = from_timestamp.astimezone(pytz.utc).isoformat() if to_timestamp is not None: params['to'] = to_timestamp.astimezone(pytz.utc).isoformat() return await self._create_get("account/withdrawals", params = params, signed = True) async def get_onetrading_withdrawals(self, from_timestamp: datetime.datetime = None, to_timestamp: datetime.datetime = None, currency: str = None, max_page_size: int = None, cursor: int = None) -> dict: params = self._clean_request_params({ 'currency_code': currency, 'max_page_size': max_page_size, 'cursor': cursor }) if from_timestamp is not None: params['from'] = from_timestamp.astimezone(pytz.utc).isoformat() if to_timestamp is not None: params['to'] = to_timestamp.astimezone(pytz.utc).isoformat() return await self._create_get("account/withdrawals/onetrading", params = params, signed = True) async def toggle_best_fee_collection(self, indicator: bool) -> dict: data = { 'collect_fees_in_best': indicator } return await self._create_post("account/fees", data = data, signed = True) async def auto_cancel_all_orders(self, timeout_ms: int) -> dict: data = { 'timeout': timeout_ms } return await self._create_post("account/orders/cancel-all-after", data = data, signed = True) async def delete_auto_cancel_all_orders(self) -> dict: return await self._create_delete("account/orders/cancel-all-after", signed = True)
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/onetrading/OneTradingWebsocket.py
cryptoxlib/clients/onetrading/OneTradingWebsocket.py
import json import logging from typing import List, Any from cryptoxlib.Pair import Pair from cryptoxlib.WebsocketMgr import Subscription, WebsocketMgr, WebsocketMessage, Websocket, CallbacksType, \ ClientWebsocketHandle, WebsocketOutboundMessage from cryptoxlib.clients.onetrading import enums from cryptoxlib.clients.onetrading.exceptions import OneTradingException from cryptoxlib.clients.onetrading.functions import map_pair, map_multiple_pairs from cryptoxlib.exceptions import WebsocketReconnectionException LOG = logging.getLogger(__name__) class OneTradingWebsocket(WebsocketMgr): WEBSOCKET_URI = "wss://streams.onetrading.com" MAX_MESSAGE_SIZE = 3 * 1024 * 1024 # 3MB def __init__(self, subscriptions: List[Subscription], api_key: str = None, ssl_context = None, startup_delay_ms: int = 0) -> None: super().__init__(websocket_uri = self.WEBSOCKET_URI, subscriptions = subscriptions, max_message_size = OneTradingWebsocket.MAX_MESSAGE_SIZE, ssl_context = ssl_context, auto_reconnect = True, startup_delay_ms = startup_delay_ms) self.api_key = api_key def get_websocket(self) -> Websocket: return self.get_aiohttp_websocket() async def send_authentication_message(self): requires_authentication = False for subscription in self.subscriptions: if subscription.requires_authentication(): requires_authentication = True break if requires_authentication: authentication_message = { "type": "AUTHENTICATE", "api_token": self.api_key } LOG.debug(f"> {authentication_message}") await self.websocket.send(json.dumps(authentication_message)) message = await self.websocket.receive() LOG.debug(f"< {message}") message = json.loads(message) if 'type' in message and message['type'] == 'AUTHENTICATED': LOG.info(f"Websocket authenticated successfully.") else: raise OneTradingException(f"Authentication error. Response [{message}]") def _get_subscription_message(self, subscriptions: List[Subscription]): return { "type": "SUBSCRIBE", "channels": [ subscription.get_subscription_message() for subscription in subscriptions ] } def _get_unsubscription_message(self, subscriptions: List[Subscription]): return { "type": "UNSUBSCRIBE", "channels": # pick only 'name' from the subscription message and remove duplicates list(set(subscription.get_subscription_message()['name'] for subscription in subscriptions)) } async def send_subscription_message(self, subscriptions: List[Subscription]): subscription_message = self._get_subscription_message(subscriptions) LOG.debug(f"> {subscription_message}") await self.websocket.send(json.dumps(subscription_message)) async def send_unsubscription_message(self, subscriptions: List[Subscription]): unsubscription_message = self._get_unsubscription_message(subscriptions) LOG.debug(f"> {unsubscription_message}") await self.websocket.send(json.dumps(unsubscription_message)) async def _process_message(self, websocket: Websocket, message: str) -> None: message = json.loads(message) # subscription negative response if "error" in message or message['type'] == "ERROR": raise OneTradingException( f"Subscription error. Request [{json.dumps(self._get_subscription_message())}] Response [{json.dumps(message)}]") # subscription positive response elif message['type'] == "SUBSCRIPTIONS": LOG.info(f"Subscription confirmed for channels [" + ",".join( [channel["name"] for channel in message["channels"]]) + "]") # for confirmed ORDERS channel publish the confirmation downstream in order to communicate the websocket handle if 'ORDERS' in [channel['name'] for channel in message['channels']]: await self.publish_message(WebsocketMessage( subscription_id = 'ORDERS', message = message, websocket = ClientWebsocketHandle(websocket = websocket) )) # remote termination with an opportunity to reconnect elif message["type"] == "CONNECTION_CLOSING": LOG.warning(f"Server is performing connection termination with an opportunity to reconnect.") raise WebsocketReconnectionException("Graceful connection termination.") # heartbeat message elif message["type"] == "HEARTBEAT": pass # regular message else: await self.publish_message(WebsocketMessage( subscription_id = message['channel_name'], message = message, # for ORDERS channel communicate also the websocket handle websocket = ClientWebsocketHandle(websocket = websocket) if message['channel_name'] == 'ORDERS' else None )) class OneTradingSubscription(Subscription): def __init__(self, callbacks: CallbacksType = None): super().__init__(callbacks) @staticmethod def get_channel_name(): pass def construct_subscription_id(self) -> Any: return self.get_channel_name() def requires_authentication(self) -> bool: return False class AccountSubscription(OneTradingSubscription): def __init__(self, callbacks: CallbacksType = None): super().__init__(callbacks) @staticmethod def get_channel_name(): return "ACCOUNT_HISTORY" def get_subscription_message(self, **kwargs) -> dict: return { "name": self.get_channel_name(), } def requires_authentication(self) -> bool: return True class PricesSubscription(OneTradingSubscription): def __init__(self, pairs: List[Pair], callbacks: CallbacksType = None): super().__init__(callbacks) self.pairs = pairs @staticmethod def get_channel_name(): return "PRICE_TICKS" def get_subscription_message(self, **kwargs) -> dict: return { "name": self.get_channel_name(), "instrument_codes": map_multiple_pairs(self.pairs, sort = True) } class OrderbookSubscription(OneTradingSubscription): def __init__(self, pairs: List[Pair], depth: str, callbacks: CallbacksType = None): super().__init__(callbacks) self.pairs = pairs self.depth = depth @staticmethod def get_channel_name(): return "ORDER_BOOK" def get_subscription_message(self, **kwargs) -> dict: return { "name": self.get_channel_name(), "depth": self.depth, "instrument_codes": map_multiple_pairs(self.pairs, sort = True) } class CandlesticksSubscriptionParams(object): def __init__(self, pair : Pair, unit : enums.TimeUnit, period: int): self.pair = pair self.unit = unit self.period = period class CandlesticksSubscription(OneTradingSubscription): def __init__(self, subscription_params: List[CandlesticksSubscriptionParams], callbacks: CallbacksType = None): super().__init__(callbacks) self.subscription_params = subscription_params @staticmethod def get_channel_name(): return "CANDLESTICKS" def get_subscription_message(self, **kwargs) -> dict: return { "name": self.get_channel_name(), "properties": [{ "instrument_code": map_pair(params.pair), "time_granularity": { "unit": params.unit.value, "period": params.period } } for params in sorted(self.subscription_params)] } class MarketTickerSubscription(OneTradingSubscription): def __init__(self, pairs: List[Pair], price_points_mode: enums.PricePointsMode = None, callbacks: CallbacksType = None): super().__init__(callbacks) self.pairs = pairs self.price_points_mode = price_points_mode @staticmethod def get_channel_name(): return "MARKET_TICKER" def get_subscription_message(self, **kwargs) -> dict: msg = { "name": self.get_channel_name(), "instrument_codes": map_multiple_pairs(self.pairs, sort = True) } if self.price_points_mode is not None: msg['price_points_mode'] = self.price_points_mode.value return msg class TradingSubscription(OneTradingSubscription): def __init__(self, callbacks: CallbacksType = None): super().__init__(callbacks) @staticmethod def get_channel_name(): return "TRADING" def get_subscription_message(self, **kwargs) -> dict: return { "name": self.get_channel_name(), } def requires_authentication(self) -> bool: return True class OrdersSubscription(OneTradingSubscription): def __init__(self, callbacks: CallbacksType = None): super().__init__(callbacks) @staticmethod def get_channel_name(): return "ORDERS" def get_subscription_message(self, **kwargs) -> dict: return { "name": self.get_channel_name(), } def requires_authentication(self) -> bool: return True class CreateOrderMessage(WebsocketOutboundMessage): def __init__(self, pair: Pair, type: enums.OrderType, side: enums.OrderSide, amount: str, price: str = None, stop_price: str = None, client_id: str = None, time_in_force: enums.TimeInForce = None, is_post_only: bool = None): self.pair = pair self.type = type self.side = side self.amount = amount self.price = price self.stop_price = stop_price self.client_id = client_id self.time_in_force = time_in_force self.is_post_only = is_post_only def to_json(self): ret = { "type": "CREATE_ORDER", "order": { "instrument_code": map_pair(self.pair), "type": self.type.value, "side": self.side.value, "amount": self.amount } } if self.price is not None: ret['order']['price'] = self.price if self.stop_price is not None: ret['order']['trigger_price'] = self.stop_price if self.client_id is not None: ret['order']['client_id'] = self.client_id if self.time_in_force is not None: ret['order']['time_in_force'] = self.time_in_force.value if self.is_post_only is not None: ret['order']['is_post_only'] = self.is_post_only return ret class CancelOrderMessage(WebsocketOutboundMessage): def __init__(self, order_id: str = None, client_id: str = None): self.order_id = order_id self.client_id = client_id def to_json(self): ret = { "type": "CANCEL_ORDER", } if self.order_id is not None: ret['order_id'] = self.order_id if self.client_id is not None: ret['client_id'] = self.client_id return ret class CancelAllOrdersMessage(WebsocketOutboundMessage): def __init__(self, order_ids: List[str] = None, pair: Pair = None): self.order_ids = order_ids self.pair = pair def to_json(self): ret = { "type": "CANCEL_ALL_ORDERS", } if self.order_ids is not None: ret['order_ids'] = self.order_ids if self.pair is not None: ret['instrument_code'] = map_pair(self.pair) return ret class AutoCancelAllOrdersMessage(WebsocketOutboundMessage): def __init__(self, timeout_ms: int): self.timeout_ms = timeout_ms def to_json(self): ret = { "type": "CANCEL_ALL_AFTER", "timeout": self.timeout_ms } return ret class DeactivateAutoCancelAllOrdersMessage(WebsocketOutboundMessage): def __init__(self): pass def to_json(self): ret = { "type": "DEACTIVATE_CANCEL_ALL_AFTER" } return ret class UpdateOrderMessage(WebsocketOutboundMessage): def __init__(self, amount: str, order_id: str = None, client_id: str = None): self.amount = amount self.order_id = order_id self.client_id = client_id def to_json(self): ret = { "type": "UPDATE_ORDER", "order": { "amount": self.amount } } if self.order_id is not None: ret['order']['order_id'] = self.order_id if self.client_id is not None: ret['order']['client_id'] = self.client_id return ret
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/onetrading/exceptions.py
cryptoxlib/clients/onetrading/exceptions.py
from typing import Optional from cryptoxlib.exceptions import CryptoXLibException class OneTradingException(CryptoXLibException): pass class OneTradingRestException(OneTradingException): def __init__(self, status_code: int, body: Optional[dict]): super().__init__(f"Rest API exception: status [{status_code}], response [{body}]") self.status_code = status_code self.body = body
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/onetrading/__init__.py
cryptoxlib/clients/onetrading/__init__.py
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/onetrading/functions.py
cryptoxlib/clients/onetrading/functions.py
from typing import List from cryptoxlib.Pair import Pair def map_pair(pair: Pair) -> str: return f"{pair.base}_{pair.quote}" def map_multiple_pairs(pairs : List[Pair], sort = False) -> List[str]: pairs = [pair.base + "_" + pair.quote for pair in pairs] if sort: return sorted(pairs) else: return pairs
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/btse/enums.py
cryptoxlib/clients/btse/enums.py
import enum class OrderSide(enum.Enum): BUY = "BUY" SELL = "SELL" class OrderType(enum.Enum): LIMIT = "LIMIT" MARKET = "MARKET" OCO = "OCO" class TransactionType(enum.Enum): LIMIT = "LIMIT" MARKET = "MARKET" TRIGGER = "TRIGGER" class TimeInForce(enum.Enum): GOOD_TILL_CANCELLED = "GTC" IMMEDIATE_OR_CANCELLED = "IOC" TIME_5MIN = "FIVEMIN" TIME_1HOUR = "HOUR" TIME_12HOUR = "TWELVEHOUR" TIME_1DAY = "DAY" TIME_1WEEK = "WEEK" TIME_1MONTH = "MONTH"
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/btse/exceptions.py
cryptoxlib/clients/btse/exceptions.py
from typing import Optional from cryptoxlib.exceptions import CryptoXLibException class BtseException(CryptoXLibException): pass class BtseRestException(BtseException): def __init__(self, status_code: int, body: Optional[dict]): super().__init__(f"Rest API exception: status [{status_code}], response [{body}]") self.status_code = status_code self.body = body
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/btse/BtseClient.py
cryptoxlib/clients/btse/BtseClient.py
import ssl import logging import datetime import pytz import hmac import hashlib import json from multidict import CIMultiDictProxy from typing import List, Optional from cryptoxlib.CryptoXLibClient import CryptoXLibClient, RestCallType from cryptoxlib.clients.btse import enums from cryptoxlib.clients.btse.exceptions import BtseRestException from cryptoxlib.clients.btse.functions import map_pair from cryptoxlib.Pair import Pair from cryptoxlib.WebsocketMgr import WebsocketMgr, Subscription from cryptoxlib.clients.btse.BtseWebsocket import BtseWebsocket LOG = logging.getLogger(__name__) class BtseClient(CryptoXLibClient): REST_API_URI = "https://api.btse.com/spot/api/v3.1/" def __init__(self, api_key: str = None, sec_key: str = None, api_trace_log: bool = False, ssl_context: ssl.SSLContext = None) -> None: super().__init__(api_trace_log, ssl_context) self.api_key = api_key self.sec_key = sec_key def _get_rest_api_uri(self) -> str: return self.REST_API_URI def _sign_payload(self, rest_call_type: RestCallType, resource: str, data: dict = None, params: dict = None, headers: dict = None) -> None: timestamp = self._get_current_timestamp_ms() signature_string = f"/api/v3.1/{resource}{timestamp}" if data is not None: signature_string += json.dumps(data) LOG.debug(f"Signature input string: {signature_string}") signature = hmac.new(self.sec_key.encode('utf-8'), signature_string.encode('utf-8'), hashlib.sha384).hexdigest() headers['btse-api'] = self.api_key headers['btse-nonce'] = str(timestamp) headers['btse-sign'] = signature def _preprocess_rest_response(self, status_code: int, headers: 'CIMultiDictProxy[str]', body: Optional[dict]) -> None: if str(status_code)[0] != '2': raise BtseRestException(status_code, body) def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0, ssl_context = None) -> WebsocketMgr: return BtseWebsocket(subscriptions, self.api_key, self.sec_key, ssl_context) def _get_header(self): header = { 'Accept': 'application/json' } return header async def get_time(self) -> dict: return await self._create_get("time", headers = self._get_header()) async def get_exchange_info(self, pair: Pair = None) -> dict: params = {} if pair is not None: params['symbol'] = map_pair(pair) return await self._create_get("market_summary", params = params, headers = self._get_header()) async def get_order_book(self, pair: Pair = None, depth: int = None) -> dict: params = self._clean_request_params({ "depth": depth, }) if pair is not None: params['symbol'] = map_pair(pair) return await self._create_get("orderbook/L2", params = params, headers = self._get_header()) async def get_price(self, pair: Pair = None) -> dict: params = {} if pair is not None: params['symbol'] = map_pair(pair) return await self._create_get("price", params = params, headers = self._get_header()) async def get_funds(self) -> dict: return await self._create_get("user/wallet", headers = self._get_header(), signed = True) async def get_open_orders(self, pair: Pair) -> dict: params = { 'symbol': map_pair(pair) } return await self._create_get("user/open_orders", params = params, headers = self._get_header(), signed = True) async def get_fees(self, pair: Pair = None) -> dict: params = {} if pair is not None: params['symbol'] = map_pair(pair) return await self._create_get("user/fees", params = params, headers = self._get_header(), signed = True) async def create_order(self, pair: Pair, side: enums.OrderSide, type: enums.OrderType, amount: str, price: str = None, stop_price: str = None, post_only = None, trail_value: str = None, trigger_price: str = None, transction_type: enums.TransactionType = None, time_in_force: enums.TimeInForce = None, client_id: str = None) -> dict: data = self._clean_request_params({ "symbol": map_pair(pair), "side": side.value, "type": type.value, "size": amount, "price": price, "stopPrice": stop_price, "postOnly": post_only, "clOrderID": client_id, "trailValue": trail_value, "triggerPrice": trigger_price }) if time_in_force is not None: data['time_in_force'] = time_in_force.value if transction_type is not None: data['txType'] = transction_type.value return await self._create_post("order", data = data, headers = self._get_header(), signed = True) async def cancel_order(self, pair: Pair, order_id: str = None, client_order_id: str = None) -> dict: params = self._clean_request_params({ "symbol": map_pair(pair), "orderId": order_id, "clOrderID": client_order_id }) return await self._create_delete("order", params = params, headers = self._get_header(), signed = True)
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/btse/BtseWebsocket.py
cryptoxlib/clients/btse/BtseWebsocket.py
import json import logging import datetime import websockets import hmac import hashlib from typing import List, Callable, Any, Optional from cryptoxlib.WebsocketMgr import Subscription, WebsocketMgr, WebsocketMessage, Websocket, CallbacksType from cryptoxlib.Pair import Pair from cryptoxlib.clients.btse.functions import map_pair from cryptoxlib.clients.btse.exceptions import BtseException from cryptoxlib.PeriodicChecker import PeriodicChecker LOG = logging.getLogger(__name__) class BtseWebsocket(WebsocketMgr): WEBSOCKET_URI = "wss://ws.btse.com/spotWS" def __init__(self, subscriptions: List[Subscription], api_key: str = None, sec_key: str = None, ssl_context = None) -> None: super().__init__(websocket_uri = self.WEBSOCKET_URI, subscriptions = subscriptions, ssl_context = ssl_context, builtin_ping_interval = None, auto_reconnect = True, periodic_timeout_sec = 5) self.api_key = api_key self.sec_key = sec_key self.ping_checker = PeriodicChecker(period_ms = 30 * 1000) def get_websocket(self) -> Websocket: return self.get_aiohttp_websocket() async def _process_periodic(self, websocket: Websocket) -> None: if self.ping_checker.check(): await websocket.send("2") async def send_authentication_message(self): requires_authentication = False for subscription in self.subscriptions: if subscription.requires_authentication(): requires_authentication = True break if requires_authentication: timestamp_ms = int(datetime.datetime.now(tz = datetime.timezone.utc).timestamp() * 1000) signature_string = f"/spotWS{timestamp_ms}" signature = hmac.new(self.sec_key.encode('utf-8'), signature_string.encode('utf-8'), hashlib.sha384).hexdigest() authentication_message = { "op": "authKeyExpires", "args": [self.api_key, timestamp_ms, signature] } LOG.debug(f"> {authentication_message}") await self.websocket.send(json.dumps(authentication_message)) message = await self.websocket.receive() LOG.debug(f"< {message}") message = json.loads(message) if 'success' in message and message['success'] is True: LOG.info(f"Authenticated websocket connected successfully.") else: raise BtseException(f"Authentication error. Response [{message}]") async def send_subscription_message(self, subscriptions: List[Subscription]): subscription_list = [] for subscription in subscriptions: subscription_list += subscription.get_subscription_list() subscription_message = { "op": "subscribe", "args": subscription_list } LOG.debug(f"> {subscription_message}") await self.websocket.send(json.dumps(subscription_message)) message = await self.websocket.receive() LOG.debug(f"< {message}") try: message = json.loads(message) if message['event'] == 'subscribe' and len(message['channel']) > 0: LOG.info(f"Websocket subscribed successfully.") else: raise BtseException(f"Subscription error. Response [{message}]") except: raise BtseException(f"Subscription error. Response [{message}]") async def _process_message(self, websocket: Websocket, message: str) -> None: message = json.loads(message) topic = message['topic'] channel = topic.split(':')[0] await self.publish_message(WebsocketMessage(subscription_id = channel, message = message)) class BtseSubscription(Subscription): def __init__(self, callbacks: CallbacksType = None): super().__init__(callbacks) def get_subscription_list(self) -> List[str]: pass def construct_subscription_id(self) -> Any: return self.get_subscription_list()[0].split(':')[0] def requires_authentication(self) -> bool: return False def get_subscription_message(self, **kwargs) -> dict: return {} class AccountSubscription(BtseSubscription): def __init__(self, callbacks: CallbacksType = None): super().__init__(callbacks) def get_subscription_list(self) -> List[str]: return ["notificationApi"] def requires_authentication(self) -> bool: return True class OrderbookSubscription(BtseSubscription): def __init__(self, pairs: List[Pair], grouping_level: int = 0, callbacks: CallbacksType = None): super().__init__(callbacks) self.pairs = pairs self.grouping_level = grouping_level def get_subscription_list(self) -> List[str]: subscription_list = [] for pair in self.pairs: subscription_list.append(f"orderBookApi:{map_pair(pair)}_{self.grouping_level}") return subscription_list class OrderbookL2Subscription(BtseSubscription): def __init__(self, pairs: List[Pair], depth: int, callbacks: CallbacksType = None): super().__init__(callbacks) self.pairs = pairs self.depth = depth def get_subscription_list(self) -> List[str]: subscription_list = [] for pair in self.pairs: subscription_list.append(f"orderBookL2Api:{map_pair(pair)}_{self.depth}") return subscription_list class TradeSubscription(BtseSubscription): def __init__(self, pairs: List[Pair], callbacks: CallbacksType = None): super().__init__(callbacks) self.pairs = pairs def get_subscription_list(self) -> List[str]: subscription_list = [] for pair in self.pairs: subscription_list.append(f"tradeHistoryApi:{map_pair(pair)}") return subscription_list
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/btse/__init__.py
cryptoxlib/clients/btse/__init__.py
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
nardew/cryptoxlib-aio
https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/btse/functions.py
cryptoxlib/clients/btse/functions.py
from cryptoxlib.Pair import Pair def map_pair(pair: Pair) -> str: return f"{pair.base}-{pair.quote}"
python
MIT
3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8
2026-01-05T07:14:19.536370Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/setup.py
setup.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Installs robel. To install: pip install -e . """ import fnmatch import os import setuptools with open("README.md", "r") as fh: long_description = fh.read() def get_requirements(file_name): """Returns requirements from the given file.""" file_path = os.path.join(os.path.dirname(__file__), file_name) with open(file_path, 'r') as f: return [line.strip() for line in f] def get_data_files(package_dir, patterns): """Returns filepaths matching the given pattern.""" paths = set() for directory, _, filenames in os.walk(package_dir): for pattern in patterns: for filename in fnmatch.filter(filenames, pattern): base_path = os.path.relpath(directory, package_dir) paths.add(os.path.join(base_path, filename)) return list(paths) setuptools.setup( name="robel", version="0.1.2", license='Apache 2.0', description=('Robotics reinforcement learning benchmark tasks with ' 'cost-effective robots.'), long_description=long_description, long_description_content_type="text/markdown", packages=setuptools.find_packages(), package_data={ 'robel': get_data_files('robel', ['*.xml', '*.pkl', '*.stl', '*.png']), }, data_files=[ ('', ['requirements.txt', 'requirements.dev.txt']), ], install_requires=get_requirements('requirements.txt'), extra_requires={ 'dev': get_requirements('requirements.dev.txt'), }, tests_require=['absl-py'], python_requires='>=3.5.3', classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: Apache Software License', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Intended Audience :: Science/Research', ], )
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/robot_env_test.py
robel/robot_env_test.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for RobotEnv.""" import collections from absl.testing import absltest from absl.testing.absltest import mock import numpy as np from robel.robot_env import RobotEnv from robel.utils.testing.mock_sim_scene import patch_sim_scene class TestEnv(RobotEnv): """Dummy environment for testing RobotEnv.""" def __init__(self, nq=1, **kwargs): # Replace SimScene with a mocked object. with patch_sim_scene('robel.robot_env.SimScene', nq=nq): super().__init__('', **kwargs) def _reset(self): pass def _step(self, action): pass def get_obs_dict(self): return {} def get_reward_dict(self, action, obs_dict): return {} def get_score_dict(self, obs_dict, reward_dict): return {} class RobotEnvTest(absltest.TestCase): """Unit test class for RobotEnv.""" # pylint: disable=protected-access def test_sim_properties(self): """Accesses the sim, model, and data properties.""" test = TestEnv() self.assertIsNotNone(test.sim) self.assertIsNotNone(test.model) self.assertIsNotNone(test.data) # Check that the random state is initialized. self.assertIsNotNone(test.np_random) def test_init_observation_space(self): """Initializes the observation space.""" test = TestEnv() test._initialize_observation_space = mock.Mock(return_value=1) self.assertEqual(test._initialize_observation_space.call_count, 0) # Check that the observation space gets correctly initialized. self.assertEqual(test.observation_space, 1) self.assertEqual(test._initialize_observation_space.call_count, 1) # Check that the observation space does not get re-initialized. self.assertEqual(test.observation_space, 1) self.assertEqual(test._initialize_observation_space.call_count, 1) def test_default_observation_space(self): """Tests the default observation space.""" test = TestEnv() test.get_obs_dict = mock.Mock( return_value=collections.OrderedDict([('a', [1, 2])])) self.assertEqual(test.observation_space.shape, (2,)) def test_dict_observation_space(self): """Tests the default observation space.""" test = TestEnv(use_dict_obs=True) test.get_obs_dict = mock.Mock( return_value=collections.OrderedDict([('a', [1, 2])])) self.assertEqual(test.observation_space.spaces['a'].shape, (2,)) def test_init_action_space(self): """Initializes the action space.""" test = TestEnv() test._initialize_action_space = mock.Mock(return_value=1) self.assertEqual(test._initialize_action_space.call_count, 0) # Check that the action space gets correctly initialized. self.assertEqual(test.action_space, 1) self.assertEqual(test._initialize_action_space.call_count, 1) # Check that the action space does not get re-initialized. self.assertEqual(test.action_space, 1) self.assertEqual(test._initialize_action_space.call_count, 1) def test_default_action_space(self): """Tests the default action space.""" test = TestEnv(nq=5) self.assertEqual(test.action_space.shape, (5,)) np.testing.assert_array_equal(test.action_space.low, [-1] * 5) np.testing.assert_array_equal(test.action_space.high, [1] * 5) def test_init_state_space(self): """Initializes the state space.""" test = TestEnv() test._initialize_state_space = mock.Mock(return_value=1) self.assertEqual(test._initialize_state_space.call_count, 0) # Check that the state space gets correctly initialized. self.assertEqual(test.state_space, 1) self.assertEqual(test._initialize_state_space.call_count, 1) # Check that the state space does not get re-initialized. self.assertEqual(test.state_space, 1) self.assertEqual(test._initialize_state_space.call_count, 1) def test_default_state_space(self): """Tests the default state space.""" test = TestEnv(nq=4) self.assertEqual(test.state_space[0].shape, (4,)) self.assertEqual(test.state_space[1].shape, (4,)) def test_reset(self): """Performs a reset.""" test = TestEnv() test._reset = mock.Mock() test.get_obs_dict = mock.Mock( return_value=collections.OrderedDict([('a', [1, 1])])) obs = test.reset() self.assertIsNone(test.last_action) self.assertDictEqual(test.last_obs_dict, {'a': [1, 1]}) self.assertIsNone(test.last_reward_dict) self.assertIsNone(test.last_score_dict) self.assertFalse(test.is_done) self.assertEqual(test.step_count, 0) self.assertEqual(test._reset.call_count, 1) np.testing.assert_array_equal(obs, [1, 1]) def test_reset_dict(self): """Performs a reset using dictionary observations.""" test = TestEnv(use_dict_obs=True) test._reset = mock.Mock() test.get_obs_dict = mock.Mock( return_value=collections.OrderedDict([('a', [1, 1])])) obs = test.reset() self.assertEqual(test._reset.call_count, 1) self.assertEqual(test.get_obs_dict.call_count, 1) np.testing.assert_array_equal(obs['a'], [1, 1]) def test_step(self): """Checks that step calls its subcomponents.""" test = TestEnv() test.get_obs_dict = mock.Mock( return_value=collections.OrderedDict([ ('o1', [0]), ('o2', [1, 2]), ])) test.get_reward_dict = mock.Mock(return_value={ 'r1': np.array(1), 'r2': np.array(2), }) test.get_score_dict = mock.Mock(return_value={ 's1': np.array(1), }) test.get_done = mock.Mock(return_value=np.array(False)) obs, reward, done, info = test.step([0]) np.testing.assert_array_equal(test.last_action, [0]) self.assertDictEqual(test.last_obs_dict, {'o1': [0], 'o2': [1, 2]}) self.assertDictEqual(test.last_reward_dict, {'r1': 1, 'r2': 2}) self.assertDictEqual(test.last_score_dict, {'s1': 1}) self.assertFalse(test.is_done) self.assertEqual(test.step_count, 1) # Check that step calls its sub-methods exactly once. self.assertEqual(test.get_obs_dict.call_count, 1) self.assertEqual(test.get_reward_dict.call_count, 1) self.assertEqual(test.get_score_dict.call_count, 1) self.assertEqual(test.get_done.call_count, 1) np.testing.assert_array_equal(obs, [0, 1, 2]) self.assertEqual(reward, 3) self.assertFalse(done) self.assertListEqual( sorted(info.keys()), [ 'obs/o1', 'obs/o2', 'reward/r1', 'reward/r2', 'reward/total', 'score/s1' ]) np.testing.assert_array_equal(info['obs/o1'], [0]) np.testing.assert_array_equal(info['obs/o2'], [1, 2]) np.testing.assert_array_equal(info['reward/r1'], 1) np.testing.assert_array_equal(info['reward/r2'], 2) np.testing.assert_array_equal(info['reward/total'], 3) np.testing.assert_array_equal(info['score/s1'], 1) def test_step_dict(self): """Checks the output of step using dictionary observations.""" test = TestEnv(use_dict_obs=True) test.get_obs_dict = mock.Mock( return_value=collections.OrderedDict([ ('o1', [0]), ('o2', [1, 2]), ])) test.get_reward_dict = mock.Mock(return_value={ 'r1': np.array(1), 'r2': np.array(2), }) obs, _, _, _ = test.step([0]) self.assertListEqual(sorted(obs.keys()), ['o1', 'o2']) np.testing.assert_array_equal(obs['o1'], [0]) np.testing.assert_array_equal(obs['o2'], [1, 2]) def test_get_obs_subset(self): """Tests `_get_obs` flattening a subset of keys.""" test = TestEnv(observation_keys=['b', 'd']) test.get_obs_dict = mock.Mock(return_value={ 'a': [0], 'b': [1, 2], 'c': [3, 4], 'd': [5], }) np.testing.assert_array_equal(test._get_obs(), [1, 2, 5]) def test_get_obs_subset_dict(self): """Tests `_get_obs` flattening a subset of keys.""" test = TestEnv(observation_keys=['b', 'd'], use_dict_obs=True) test.get_obs_dict = mock.Mock(return_value={ 'a': [0], 'b': [1, 2], 'c': [3, 4], 'd': [5], }) obs = test._get_obs() self.assertListEqual(sorted(obs.keys()), ['b', 'd']) np.testing.assert_array_equal(obs['b'], [1, 2]) np.testing.assert_array_equal(obs['d'], [5]) def test_get_total_reward(self): """Tests `_get_total_reward` summing a subset of keys.""" test = TestEnv(reward_keys=['b', 'c']) test_rewards = { 'a': 1, 'b': 3, 'c': 5, 'd': 7, } self.assertEqual(test._get_total_reward(test_rewards), 8) def test_get_done(self): """Tests default behavior of `get_done`.""" test = TestEnv(reward_keys=['b', 'c']) test_rewards = { 'a': np.array([1, 2]), } np.testing.assert_array_equal( test.get_done({}, test_rewards), [False, False]) def test_last_action(self): """Tests reading the last action.""" test = TestEnv(nq=3) test.get_obs_dict = mock.Mock( return_value=collections.OrderedDict([('o', [0])])) test.get_reward_dict = mock.Mock(return_value={'r': np.array(0)}) self.assertIsNone(test.last_action) np.testing.assert_array_equal(test._get_last_action(), [0, 0, 0]) test.step([1, 1, 1]) np.testing.assert_array_equal(test._get_last_action(), [1, 1, 1]) self.assertIs(test.last_action, test._get_last_action()) def test_sticky_actions(self): """Tests sticky actions.""" test = TestEnv(nq=3, sticky_action_probability=1) test.get_obs_dict = mock.Mock( return_value=collections.OrderedDict([('o', [0])])) test.get_reward_dict = mock.Mock(return_value={'r': np.array(0)}) test._step = mock.Mock() test.last_action = np.ones(3) test.step([0, 0, 0]) args, _ = test._step.call_args_list[0] np.testing.assert_array_equal(args[0], np.ones(3)) if __name__ == '__main__': absltest.main()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/robot_env.py
robel/robot_env.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Base environment API for robotics tasks.""" import abc import collections from typing import Any, Dict, Optional, Sequence, Union, Tuple import gym from gym import spaces from gym.utils import seeding import numpy as np from robel.components.builder import ComponentBuilder from robel.simulation.sim_scene import SimScene, SimBackend from robel.simulation.renderer import RenderMode DEFAULT_RENDER_SIZE = 480 # The simulation backend to use by default. DEFAULT_SIM_BACKEND = SimBackend.MUJOCO_PY def make_box_space(low: Union[float, Sequence[float]], high: Union[float, Sequence[float]], shape: Optional[Tuple[int]] = None) -> gym.spaces.Box: """Returns a Box gym space.""" # HACK: Fallback for gym 0.9.x # TODO(michaelahn): Consider whether we still need to support 0.9.x try: return spaces.Box(low, high, shape, dtype=np.float32) except TypeError: return spaces.Box(low, high, shape) class RobotEnv(gym.Env, metaclass=abc.ABCMeta): """Base Gym environment for robotics tasks.""" def __init__(self, sim_model: Any, observation_keys: Optional[Sequence[str]] = None, reward_keys: Optional[Sequence[str]] = None, use_dict_obs: bool = False, frame_skip: int = 1, camera_settings: Optional[Dict] = None, sim_backend: SimBackend = DEFAULT_SIM_BACKEND, sticky_action_probability: float = 0.): """Initializes a robotics environment. Args: sim_model: The path to the simulation to load. observation_keys: The keys of `get_obs_dict` to extract and flatten for the default implementation of `_get_obs`. If this is not set, `get_obs_dict` must return an OrderedDict. reward_keys: The keys of `get_reward_dict` to extract and sum for the default implementation of `_get_total_reward`. If this is not set, `_get_total_reward` will sum all of the values. use_dict_obs: If True, the observations will be returned as dictionaries rather than as a flattened array. The observation space of this environment will be a dictionary space. frame_skip: The number of simulation steps per environment step. This multiplied by the timestep defined in the model file is the step duration. camera_settings: Settings to apply to the free camera in simulation. sim_backend: The simulation backend to use. sticky_action_probability: Repeat previous action with this probability. Default is 0 (no sticky actions). """ self._observation_keys = observation_keys self._reward_keys = reward_keys self._use_dict_obs = use_dict_obs self._sticky_action_probability = sticky_action_probability self._components = [] # The following spaces are initialized by their respective `initialize` # methods, e.g. `_initialize_observation_space`. self._observation_space = None self._action_space = None self._state_space = None # The following are populated by step() and/or reset(). self.last_action = None self.last_obs_dict = None self.last_reward_dict = None self.last_score_dict = None self.is_done = False self.step_count = 0 # Load the simulation. self.sim_scene = SimScene.create( sim_model, backend=sim_backend, frame_skip=frame_skip) self.sim = self.sim_scene.sim self.model = self.sim_scene.model self.data = self.sim_scene.data if camera_settings: self.sim_scene.renderer.set_free_camera_settings(**camera_settings) # Set common metadata for Gym environments. self.metadata = { 'render.modes': ['human', 'rgb_array', 'depth_array'], 'video.frames_per_second': int( np.round(1.0 / self.sim_scene.step_duration)) } # Ensure gym does not try to patch `_step` and `_reset`. self._gym_disable_underscore_compat = True self.seed() #=========================================================================== # Environment API. # These methods should not be overridden by subclasses. #=========================================================================== @property def observation_space(self) -> gym.Space: """Returns the observation space of the environment. The observation space is the return specification for `reset`, `_get_obs`, and the first element of the returned tuple from `step`. Subclasses should override `_initialize_observation_space` to customize the observation space. """ # Initialize and cache the observation space on the first call. if self._observation_space is None: self._observation_space = self._initialize_observation_space() assert self._observation_space is not None return self._observation_space @property def action_space(self) -> gym.Space: """Returns the action space of the environment. The action space is the argument specifiction for `step`. Subclasses should override `_initialize_action_space` to customize the action space. """ # Initialize and cache the action space on the first call. if self._action_space is None: self._action_space = self._initialize_action_space() assert self._action_space is not None return self._action_space @property def state_space(self) -> gym.Space: """Returns the state space of the environment. The state space is the return specification for `get_state` and is the argument specification for `set_state`. Subclasses should override `_initialize_state_space` to customize the state space. """ # Initialize and cache the state space on the first call. if self._state_space is None: self._state_space = self._initialize_state_space() assert self._state_space is not None return self._state_space @property def dt(self) -> float: """Returns the step duration of each step, in seconds.""" return self.sim_scene.step_duration @property def obs_dim(self) -> int: """Returns the size of the observation space. NOTE: This is for compatibility with gym.MujocoEnv. """ if not isinstance(self.observation_space, spaces.Box): raise NotImplementedError('`obs_dim` only supports Box spaces.') return np.prod(self.observation_space.shape).item() @property def action_dim(self) -> int: """Returns the size of the action space.""" if not isinstance(self.action_space, spaces.Box): raise NotImplementedError('`action_dim` only supports Box spaces.') return np.prod(self.action_space.shape).item() def seed(self, seed: Optional[int] = None) -> Sequence[int]: """Seeds the environment. Args: seed: The value to seed the random number generator with. If None, uses a random seed. """ self.np_random, seed = seeding.np_random(seed) return [seed] def reset(self) -> Any: """Resets the environment. Args: state: The state to reset to. This must match with the state space of the environment. Returns: The initial observation of the environment after resetting. """ self.last_action = None self.sim.reset() self.sim.forward() self._reset() obs_dict = self.get_obs_dict() self.last_obs_dict = obs_dict self.last_reward_dict = None self.last_score_dict = None self.is_done = False self.step_count = 0 return self._get_obs(obs_dict) def step(self, action: Any) -> Tuple[Any, float, bool, Dict]: """Runs one timestep of the environment with the given action. Subclasses must override 4 subcomponents of step: - `_step`: Applies an action to the robot - `get_obs_dict`: Returns the current observation of the robot. - `get_reward_dict`: Calculates the reward for the step. - `get_done`: Returns whether the episode should terminate. Args: action: An action to control the environment. Returns: observation: The observation of the environment after the timestep. reward: The amount of reward obtained during the timestep. done: Whether the episode has ended. `env.reset()` should be called if this is True. info: Auxiliary information about the timestep. """ # Perform the step. action = self._preprocess_action(action) self._step(action) self.last_action = action # Get the observation after the step. obs_dict = self.get_obs_dict() self.last_obs_dict = obs_dict flattened_obs = self._get_obs(obs_dict) # Get the rewards for the observation. batched_action = np.expand_dims(np.atleast_1d(action), axis=0) batched_obs_dict = { k: np.expand_dims(np.atleast_1d(v), axis=0) for k, v in obs_dict.items() } batched_reward_dict = self.get_reward_dict(batched_action, batched_obs_dict) # Calculate the total reward. reward_dict = {k: v.item() for k, v in batched_reward_dict.items()} self.last_reward_dict = reward_dict reward = self._get_total_reward(reward_dict) # Calculate the score. batched_score_dict = self.get_score_dict(batched_obs_dict, batched_reward_dict) score_dict = {k: v.item() for k, v in batched_score_dict.items()} self.last_score_dict = score_dict # Get whether the episode should end. dones = self.get_done(batched_obs_dict, batched_reward_dict) done = dones.item() self.is_done = done # Combine the dictionaries as the auxiliary information. info = collections.OrderedDict() info.update(('obs/' + key, val) for key, val in obs_dict.items()) info.update(('reward/' + key, val) for key, val in reward_dict.items()) info['reward/total'] = reward info.update(('score/' + key, val) for key, val in score_dict.items()) self.step_count += 1 return flattened_obs, reward, done, info def render( self, mode: str = 'human', width: int = DEFAULT_RENDER_SIZE, height: int = DEFAULT_RENDER_SIZE, camera_id: int = -1, ) -> Optional[np.ndarray]: """Renders the environment. Args: mode: The type of rendering to use. - 'human': Renders to a graphical window. - 'rgb_array': Returns the RGB image as an np.ndarray. - 'depth_array': Returns the depth image as an np.ndarray. width: The width of the rendered image. This only affects offscreen rendering. height: The height of the rendered image. This only affects offscreen rendering. camera_id: The ID of the camera to use. By default, this is the free camera. If specified, only affects offscreen rendering. Returns: If mode is `rgb_array` or `depth_array`, a Numpy array of the rendered pixels. Otherwise, returns None. """ if mode == 'human': self.sim_scene.renderer.render_to_window() elif mode == 'rgb_array': return self.sim_scene.renderer.render_offscreen( width, height, mode=RenderMode.RGB, camera_id=camera_id) elif mode == 'depth_array': return self.sim_scene.renderer.render_offscreen( width, height, mode=RenderMode.DEPTH, camera_id=camera_id) else: raise NotImplementedError(mode) return None def close(self): """Cleans up any resources used by the environment.""" for component in self._components: component.close() self._components.clear() self.sim_scene.close() #=========================================================================== # Overridable Methods #=========================================================================== @abc.abstractmethod def _reset(self): """Task-specific reset for the environment.""" @abc.abstractmethod def _step(self, action: np.ndarray): """Task-specific step for the environment.""" @abc.abstractmethod def get_obs_dict(self) -> Dict[str, Any]: """Returns the current observation of the environment. Returns: A dictionary of observation values. This should be an ordered dictionary if `observation_keys` isn't set. """ @abc.abstractmethod def get_reward_dict( self, action: np.ndarray, obs_dict: Dict[str, np.ndarray], ) -> Dict[str, np.ndarray]: """Returns the reward for the given action and observation. Args: action: A batch of actions. obs_dict: A dictionary of batched observations. The batch dimension matches the batch dimension of the actions. Returns: A dictionary of reward components. The values should be batched to match the given actions and observations. """ @abc.abstractmethod def get_score_dict( self, obs_dict: Dict[str, np.ndarray], reward_dict: Dict[str, np.ndarray], ) -> Dict[str, np.ndarray]: """Returns a standardized measure of success for the environment. Args: obs_dict: A dictionary of batched observations. reward_dict: A dictionary of batched rewards to correspond with the observations. Returns: A dictionary of scores. """ def get_done( self, obs_dict: Dict[str, np.ndarray], reward_dict: Dict[str, np.ndarray], ) -> np.ndarray: """Returns whether the episode should terminate. Args: obs_dict: A dictionary of batched observations. reward_dict: A dictionary of batched rewards to correspond with the observations. Returns: A boolean to denote if the episode should terminate. This should have the same batch dimension as the observations and rewards. """ del obs_dict return np.zeros_like(next(iter(reward_dict.values())), dtype=bool) def get_state(self) -> Any: """Returns the current state of the environment.""" return (self.data.qpos.copy(), self.data.qvel.copy()) def set_state(self, state: Any): """Sets the state of the environment.""" qpos, qvel = state self.data.qpos[:] = qpos self.data.qvel[:] = qvel self.sim.forward() def _initialize_observation_space(self) -> gym.Space: """Returns the observation space to use for this environment. The default implementation calls `_get_obs()` and returns a dictionary space if the observation is a mapping, or a box space otherwise. """ observation = self._get_obs() if isinstance(observation, collections.Mapping): assert self._use_dict_obs return spaces.Dict({ key: make_box_space(-np.inf, np.inf, shape=np.shape(value)) for key, value in observation.items() }) return make_box_space(-np.inf, np.inf, shape=observation.shape) def _initialize_action_space(self) -> gym.Space: """Returns the action space to use for this environment. The default implementation uses the simulation's control actuator dimensions as the action space, using normalized actions in [-1, 1]. """ return make_box_space(-1.0, 1.0, shape=(self.model.nu,)) def _initialize_state_space(self) -> gym.Space: """Returns the state space to use for this environment. The default implementation calls `get_state()` and returns a space corresponding to the type of the state object: - Mapping: Dict space - List/Tuple: Tuple space """ state = self.get_state() if isinstance(state, collections.Mapping): return spaces.Dict({ key: make_box_space(-np.inf, np.inf, shape=np.shape(value)) for key, value in state.items() # pylint: disable=no-member }) elif isinstance(state, (list, tuple)): return spaces.Tuple([ make_box_space(-np.inf, np.inf, shape=np.shape(value)) for value in state ]) raise NotImplementedError( 'Override _initialize_state_space for state: {}'.format(state)) def _get_last_action(self) -> np.ndarray: """Returns the previous action, or zeros if no action has been taken.""" if self.last_action is None: return np.zeros((self.action_dim,), dtype=self.action_space.dtype) return self.last_action def _preprocess_action(self, action: np.ndarray) -> np.ndarray: """Transforms an action before passing it to `_step()`. Args: action: The action in the environment's action space. Returns: The transformed action to pass to `_step()`. """ # Clip to the normalized action space. action = np.clip(action, -1.0, 1.0) # Prevent elements of the action from changing if sticky actions are # being used. if self._sticky_action_probability > 0 and self.last_action is not None: sticky_indices = ( self.np_random.uniform() < self._sticky_action_probability) action = np.where(sticky_indices, self.last_action, action) return action def _get_obs(self, obs_dict: Optional[Dict[str, np.ndarray]] = None) -> Any: """Returns the current observation of the environment. This matches the environment's observation space. """ if obs_dict is None: obs_dict = self.get_obs_dict() if self._use_dict_obs: if self._observation_keys: obs = collections.OrderedDict( (key, obs_dict[key]) for key in self._observation_keys) else: obs = obs_dict else: if self._observation_keys: obs_values = (obs_dict[key] for key in self._observation_keys) else: assert isinstance(obs_dict, collections.OrderedDict), \ 'Must use OrderedDict if not using `observation_keys`' obs_values = obs_dict.values() obs = np.concatenate([np.ravel(v) for v in obs_values]) return obs def _get_total_reward(self, reward_dict: Dict[str, np.ndarray]) -> float: """Returns the total reward for the given reward dictionary. The default implementation extracts the keys from `reward_keys` and sums the values. Args: reward_dict: A dictionary of rewards. The values may have a batch dimension. Returns: The total reward for the dictionary. """ # TODO(michaelahn): Enforce that the reward values are scalar. if self._reward_keys: reward_values = (reward_dict[key] for key in self._reward_keys) else: reward_values = reward_dict.values() return np.sum(np.fromiter(reward_values, dtype=float)) def _add_component(self, component_builder: ComponentBuilder, **component_kwargs) -> Any: """Creates a new component for this environment instance. Args: component_builder: The configured ComponentBuilder to build the component with. """ # Build the component. component = component_builder.build( sim_scene=self.sim_scene, random_state=self.np_random, **component_kwargs) self._components.append(component) return component
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/__init__.py
robel/__init__.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Import all robot submodules.""" import robel.dclaw import robel.dkitty from robel.utils.configurable import set_env_params
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/scripts/play.py
robel/scripts/play.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Loads environments and allows the user to interact with it. Example: ``` $> python robel.scripts.play ... >>> load DClawTurnFixed-v0 >>> obs claw_qpos: ... claw_qvel: ... ... >>> action [0]*9 Sending action: [0, 0, 0, 0, 0, 0, 0, 0, 0] >>> reset ... ``` The script can be started with an environment: ``` $> python robel.scripts.play -e DClawTurnFixed-v0 ``` """ import collections import cmd import logging import time import threading from typing import Any, Dict, Optional import gym import numpy as np import robel from robel.scripts.utils import parse_env_args MIN_FRAME_TIME = 1.0 / 60.0 INTRODUCTION = """Interactive shell for Adept Environments. Type `help` or `?` to list commands. """ _ENV_COMMANDS = ['obs', 'action', 'reset', 'random', 'engage', 'disengage'] class PlayShell(cmd.Cmd): """Implements a command-line interface for visualizing an environment.""" intro = INTRODUCTION prompt = '>>> ' def __init__(self, env_name: Optional[str] = None, env_params: Optional[Dict[str, Any]] = None): """Initializes a new command-line interface. Args: env_name: The environment to initially load. device: The device to run the environment on. env_params: Parameters to pass to the environment. """ super().__init__() self._env_lock = threading.Lock() self._action = None self._do_random_actions = False self._do_reset = False self._env = None self._cv2_module = None self._load_env(env_name, env_params=env_params) self._stop_event = threading.Event() self._env_thread = threading.Thread(target=self._run_env) self._env_thread.daemon = True self._env_thread.start() def close(self): """Cleans up resources used by the program.""" if self._env_thread is None: return self._stop_event.set() self._env_thread.join() self._stop_event = None self._env_thread = None def do_quit(self, _): """Quits the program.""" self.close() return True def do_load(self, arg): """Loads an environment. A device name can be passed as a second argument to run on hardware. Example: # Loads a simulation environment: >>> load DClawTurnFixed-v0 # Loads a hardware environment: >>> load DClawTurnFixed-v0 /dev/ttyUSB0 """ if not arg: return components = arg.split() if not components or len(components) > 2: print('An environment name, and optionally a device path must be ' 'provided.') return env_name = components[0] env_params = components[1:] if len(components) > 1 else None self._load_env(env_name, env_params=env_params) def do_obs(self, _): """Prints out the current observation.""" self._print_obs() def do_action(self, arg): """Sends an action to the environment. Example: >>> action [0] * 9 """ if not arg: return action = eval(arg) print('Sending action: {}'.format(action)) action = np.array(action, dtype=np.float32) if not self._env.action_space.contains(action): print('Action in not in the action space: {}'.format( self._env.action_space)) return with self._env_lock: self._do_random_actions = False self._action = action def do_set_state(self, arg): """Sets the state for a group.""" if not arg: return state = eval(arg) print('Setting state to: {}'.format(state)) state = np.array(state, dtype=np.float32) if not self._env.state_space.contains(state): print('State is not in the state space: {}'.format( self._env.state_space)) with self._env_lock: self._env.set_state(state) def do_random(self, _): """Start doing random actions in the environment.""" with self._env_lock: self._do_random_actions = True def do_reset(self, _): """Resets the environment. Example: >>> reset """ with self._env_lock: self._do_random_actions = False self._action = None self._do_reset = True def do_engage(self, group_names): """Engages motors. This only affects hardware.""" group_names = group_names.split() with self._env_lock: if self._env.robot.is_hardware: self._env.robot.set_motors_engaged(group_names, True) def do_disengage(self, group_names): """Disengages motors. This only affects hardware.""" group_names = group_names.split() with self._env_lock: if self._env.robot.is_hardware: self._env.robot.set_motors_engaged(group_names, False) def emptyline(self): """Overrides behavior when an empty line is sent.""" def precmd(self, line): """Overrides behavior when input is given.""" line = line.strip() if any(line.startswith(prefix) for prefix in _ENV_COMMANDS): if self._env is None: print('No environment loaded.') return '' return line def _print_obs(self): """Prints the current observation.""" assert self._env is not None with self._env_lock: obs = self._env.get_obs_dict() for key, value in obs.items(): print('{}: {}'.format(key, value)) def _load_env(self, env_name: str, device: Optional[str] = None, env_params: Optional[Dict[str, Any]] = None): """Loads the given environment.""" env_params = env_params or {} if device is not None: env_params['device_path'] = device if env_params: robel.set_env_params(env_name, env_params) with self._env_lock: self._load_env_name = env_name self._load_env_params = env_params def _run_env(self): """Runs a loop for the current environment.""" step = 0 while not self._stop_event.is_set(): with self._env_lock: # Unload the current env and load the new one if given. if self._load_env_name is not None: if self._env is not None: self._env.close() robel.set_env_params(self._load_env_name, self._load_env_params) self._env = gym.make(self._load_env_name).unwrapped self._env.reset() self._load_env_name = None self._load_env_params = None if self._env is None: continue frame_start_time = time.time() with self._env_lock: if self._do_reset: self._do_reset = False self._env.reset() if self._do_random_actions: self._action = self._env.action_space.sample() if self._action is not None: self._env.step(self._action) else: self._env.get_obs_dict() self._env.render() # self._display_image_obs(obs) sleep_duration = MIN_FRAME_TIME - (time.time() - frame_start_time) if sleep_duration > 0: time.sleep(sleep_duration) step += 1 with self._env_lock: if self._env is not None: self._env.close() self._env = None def _display_image_obs(self, obs): """Displays the given observation in a window.""" if not isinstance(obs, collections.Mapping): return if self._cv2_module is None: try: import cv2 self._cv2_module = cv2 except ImportError: print('No cv2 module; not displaying images.') self._cv2_module = False return elif not self._cv2_module: return # Display a window for any image values. for key, value in obs.items(): if not isinstance(value, np.ndarray): continue if value.ndim == 3 and value.shape[2] <= 4: # TODO(michaelahn): Consider data format and color space. self._cv2_module.imshow(key, value) self._cv2_module.waitKey(1) def __del__(self): self.close() if __name__ == '__main__': env_id, params, _ = parse_env_args() logging.basicConfig(level=logging.INFO) repl = PlayShell(env_name=env_id, env_params=params) repl.cmdloop()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/scripts/check_mujoco_deps.py
robel/scripts/check_mujoco_deps.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Checks if the given MuJoCo XML file has valid dependencies. Example usage: python -m robel.scripts.check_mujoco_deps path/to/mujoco.xml """ import argparse import logging import os from robel.utils.resources import AssetBundle def main(): parser = argparse.ArgumentParser() parser.add_argument('path', nargs=1, help='The MuJoCo XML to parse.') args = parser.parse_args() model_path = args.path[0] if not os.path.exists(model_path): raise ValueError('Path does not exist: ' + model_path) logging.basicConfig(level=logging.INFO) with AssetBundle(dry_run=True, verbose=True) as bundle: bundle.add_mujoco(model_path) if __name__ == '__main__': main()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/scripts/enjoy_mjrl.py
robel/scripts/enjoy_mjrl.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Runs an MJRL policy. Example usage: python -m robel.scripts.enjoy_mjrl --device /dev/ttyUSB0 This runs the DClawTurnFixed-v0 environment by default. To run other environments, pass in the environment name with `-e/--env_name` python -m robel.scripts.enjoy_mjrl \ --env_name DClawScrewFixed-v0 \ --device /dev/ttyUSB0 """ import argparse import os import pickle from robel.scripts.rollout import rollout_script POLICY_DIR = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'data/mjrl') DEFAULT_POLICY_FORMAT = os.path.join(POLICY_DIR, '{}-policy.pkl') def policy_factory(args: argparse.Namespace): """Creates the policy.""" # Get default policy path from the environment name. policy_path = args.policy if not policy_path: policy_path = DEFAULT_POLICY_FORMAT.format(args.env_name) # Load the policy with open(policy_path, 'rb') as f: policy = pickle.load(f) def policy_fn(obs): _, info = policy.get_action(obs) return info['evaluation'] return policy_fn if __name__ == '__main__': rollout_script(policy_factory=policy_factory, add_policy_arg=True)
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/scripts/reset_hardware.py
robel/scripts/reset_hardware.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Script to test resetting robot hardware environments. To run: python -m robel.scripts.reset_hardware \ -e DKittyWalkFixed-v0 -d /dev/ttyUSB0 """ import argparse import logging import time import gym import robel from robel.scripts.utils import parse_env_args def main(): # Get command line arguments. parser = argparse.ArgumentParser() parser.add_argument( '-n', '--num_repeats', type=int, default=1, help='The number of resets to perform.') env_id, params, args = parse_env_args(parser) # Show INFO-level logs. logging.basicConfig(level=logging.INFO) # Create the environment and get the robot component. robel.set_env_params(env_id, params) env = gym.make(env_id).unwrapped assert env.robot.is_hardware for i in range(args.num_repeats): print('Starting reset #{}'.format(i)) # Disengage all of the motors and let the dkitty fall. env.robot.set_motors_engaged(None, engaged=False) print('Place the robot to a starting position.') input('Press Enter to start the reset...') # Start with all motors engaged. env.robot.set_motors_engaged(None, engaged=True) env.reset() print('Done reset! Turning off the robot in a few seconds.') time.sleep(2) if __name__ == '__main__': main()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/scripts/utils.py
robel/scripts/utils.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Helper functions to load environments in scripts.""" import argparse import collections import csv import os import logging from typing import Any, Dict, Optional, Sequence, Tuple from gym.envs import registration as gym_reg import numpy as np class EpisodeLogger: """Logs episode data.""" def __init__(self, csv_path: Optional[str] = None): """Creates a new logger. Args: csv_path: If given, saves episode data to a csv file. """ self._file = None if csv_path: self._file = open(csv_path, 'w') self._writer = None self._episode_num = 0 self._total_steps = 0 def log_path(self, path: Dict[str, Any], reward_key: str = 'rewards', env_info_key: str = 'infos'): """Logs the given path data as an episode.""" self._total_steps += len(path[reward_key]) total_reward = path[reward_key].sum() data = collections.OrderedDict(( ('episode', self._episode_num), ('total_steps', self._total_steps), ('reward', total_reward), )) for info_key, info_values in path.get(env_info_key, {}).items(): data[info_key + '-first-mean'] = np.mean(info_values[0]) data[info_key + '-last-mean'] = np.mean(info_values[-1]) data[info_key + '-mean-mean'] = np.mean(info_values) self.write_dict(data) self._episode_num += 1 def write_dict(self, data: Dict[str, Any]): if self._file is None: return if self._writer is None: self._writer = csv.DictWriter( self._file, fieldnames=list(data.keys())) self._writer.writeheader() self._writer.writerow(data) self._file.flush() def close(self): if self._file is not None: self._file.close() self._file = None def __enter__(self): return self def __exit__(self, *args): self.close() def parse_env_args( arg_parser: Optional[argparse.ArgumentParser] = None, default_env_name: Optional[str] = None, ) -> Tuple[str, Dict, argparse.Namespace]: """Parses the given arguments to get an environment ID and parameters. Args: arg_parser: An existing argument parser to add arguments to. Returns: env_name: The name of the environment. env_params: A dictionary of environment parameters that can be passed to the constructor of the environment class, or passed via `robel.set_env_params`. args: The Namespace object parsed by the ArgumentParser. """ if arg_parser is None: arg_parser = argparse.ArgumentParser() arg_parser.add_argument( '-e', '--env_name', required=(default_env_name is None), default=default_env_name, help='The environment to load.') arg_parser.add_argument('-d', '--device', help='The device to connect to.') arg_parser.add_argument( '--param', action='append', help=('A "key=value" pair to pass as an environment parameter. This ' 'be repeated, e.g. --param key1=val1 --param key2=val2')) arg_parser.add_argument( '--info', action='store_true', help='Turns on info logging.') arg_parser.add_argument( '--debug', action='store_true', help='Turns on debug logging.') args = arg_parser.parse_args() # Ensure the environment ID is valid. env_name = args.env_name if env_name not in gym_reg.registry.env_specs: raise ValueError('Unregistered environment ID: {}'.format(env_name)) # Ensure the device exists, if given. device_path = args.device if device_path and not os.path.exists(device_path): raise ValueError('Device does not exist: {}'.format(device_path)) # Parse environment params into a dictionary. env_params = {} if args.param: env_params = parse_env_params(args.param) if device_path: env_params['device_path'] = device_path if args.debug: logging.basicConfig(level=logging.DEBUG) elif args.info: logging.basicConfig(level=logging.INFO) return env_name, env_params, args def parse_env_params(user_entries: Sequence[str]) -> Dict[str, Any]: """Parses a list of `key=value` strings as a dictionary.""" def is_value_convertable(v, convert_type) -> bool: try: convert_type(v) except ValueError: return False return True env_params = {} for user_text in user_entries: components = user_text.split('=') if len(components) != 2: raise ValueError('Key-values must be specified as `key=value`') value = components[1] if is_value_convertable(value, int): value = int(value) elif is_value_convertable(value, float): value = float(value) env_params[components[0]] = value return env_params
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/scripts/find_vr_devices.py
robel/scripts/find_vr_devices.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Allows the user to interact with the OpenVR client.""" import cmd import logging from transforms3d.euler import euler2quat from robel.components.tracking.virtual_reality.client import VrClient INTRODUCTION = """Interactive shell for using the OpenVR client. Type `help` or `?` to list commands. """ class VrDeviceShell(cmd.Cmd): """Implements a command-line interface for using the OpenVR client.""" intro = INTRODUCTION prompt = '>>> ' def __init__(self, client: VrClient): super().__init__() self.client = client def do_list(self, unused_arg): """Lists the available devices on the machine.""" devices = self.client.discover_devices() if not devices: print('No devices found!') return for device in devices: print(device.get_summary()) def do_pose(self, args): """Prints the pose for the given device.""" names = args.split() devices = [self.client.get_device(name) for name in names] pose_batch = self.client.get_poses() for device in devices: state = pose_batch.get_state(device) print(device.get_summary()) print('> Pos: [{:.3f} {:.3f} {:.3f}]'.format(*state.pos)) print('> Rot: [{:.3f} {:.3f} {:.3f}]'.format(*state.rot_euler)) def emptyline(self): """Overrides behavior when an empty line is sent.""" if __name__ == '__main__': logging.basicConfig(level=logging.INFO) with VrClient() as vr_client: repl = VrDeviceShell(vr_client) repl.cmdloop()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/scripts/__init__.py
robel/scripts/__init__.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/scripts/rollout.py
robel/scripts/rollout.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Script to perform rollouts on an environment. Example usage: # Visualize an environment: python -m robel.scripts.rollout -e DClawTurnFixed-v0 --render # Benchmark offscreen rendering: python -m robel.scripts.rollout -e DClawTurnFixed-v0 --render rgb_array """ import argparse import collections import os import pickle import time from typing import Callable, Optional import gym import numpy as np import robel from robel.scripts.utils import EpisodeLogger, parse_env_args # The default environment to load when no environment name is given. DEFAULT_ENV_NAME = 'DClawTurnFixed-v0' # The default number of episodes to run. DEFAULT_EPISODE_COUNT = 10 # Named tuple for information stored over a trajectory. Trajectory = collections.namedtuple('Trajectory', [ 'actions', 'observations', 'rewards', 'total_reward', 'infos', 'renders', 'durations', ]) def do_rollouts(env, num_episodes: int, max_episode_length: Optional[int] = None, action_fn: Optional[Callable[[np.ndarray], np.ndarray]] = None, render_mode: Optional[str] = None): """Performs rollouts with the given environment. Args: num_episodes: The number of episodes to do rollouts for. max_episode_length: The maximum length of an episode. action_fn: The function to use to sample actions for steps. If None, uses random actions. render_mode: The rendering mode. If None, no rendering is performed. Yields: Trajectory containing: observations: The observations for the episode. rewards: The rewards for the episode. total_reward: The total reward during the episode. infos: The auxiliary information during the episode. renders: Rendered frames during the episode. durations: The running execution durations. """ # If no action function is given, use random actions from the action space. if action_fn is None: action_fn = lambda _: env.action_space.sample() # Maintain a dictionary of execution durations. durations = collections.defaultdict(float) # Define a function to maintain a running average of durations. def record_duration(key: str, iteration: int, value: float): durations[key] = (durations[key] * iteration + value) / (iteration + 1) total_steps = 0 for episode in range(num_episodes): episode_start = time.time() obs = env.reset() record_duration('reset', episode, time.time() - episode_start) done = False episode_actions = [] episode_obs = [obs] episode_rewards = [] episode_total_reward = 0 episode_info = collections.defaultdict(list) episode_renders = [] while not done: step_start = time.time() # Get the action for the current observation. action = action_fn(obs) action_time = time.time() record_duration('action', total_steps, action_time - step_start) # Advance the environment with the action. obs, reward, done, info = env.step(action) step_time = time.time() record_duration('step', total_steps, step_time - action_time) # Render the environment if needed. if render_mode is not None: render_result = env.render(render_mode) record_duration('render', total_steps, time.time() - step_time) if render_result is not None: episode_renders.append(render_result) # Record episode information. episode_actions.append(action) episode_obs.append(obs) episode_rewards.append(reward) episode_total_reward += reward for key, value in info.items(): episode_info[key].append(value) total_steps += 1 if (max_episode_length is not None and len(episode_obs) >= max_episode_length): done = True # Combine the information into a trajectory. trajectory = Trajectory( actions=np.array(episode_actions), observations=np.array(episode_obs), rewards=np.array(episode_rewards), total_reward=episode_total_reward, infos={key: np.array(value) for key, value in episode_info.items()}, renders=np.array(episode_renders) if episode_renders else None, durations=dict(durations), ) yield trajectory def rollout_script(arg_def_fn=None, env_factory=None, policy_factory=None, add_policy_arg: bool = False): """Performs a rollout script. Args: arg_def_fn: A function that takes an ArgumentParser. Use this to add arguments to the script. env_factory: A function that takes program arguments and returns an environment. Otherwise, uses `gym.make`. policy_factory: A function that takes program arguments and returns a policy function (callable that observations and returns actions) and the environment. add_policy_arg: If True, adds an argument to take a policy path. """ parser = argparse.ArgumentParser() parser.add_argument( '-o', '--output', help='The directory to save rollout data to.') if add_policy_arg: parser.add_argument( '-p', '--policy', help='The path to the policy file to load.') parser.add_argument( '-n', '--num_episodes', type=int, default=DEFAULT_EPISODE_COUNT, help='The number of episodes to run.') parser.add_argument( '--seed', type=int, default=None, help='The seed for the environment.') parser.add_argument( '-r', '--render', nargs='?', const='human', default=None, help=('The rendering mode. If provided, renders to a window. A render ' 'mode string can be passed here.')) # Add additional argparse arguments. if arg_def_fn: arg_def_fn(parser) env_id, params, args = parse_env_args( parser, default_env_name=DEFAULT_ENV_NAME) robel.set_env_params(env_id, params) if env_factory: env = env_factory(args) else: env = gym.make(env_id) action_fn = None if policy_factory: action_fn = policy_factory(args) if args.seed is not None: env.seed(args.seed) paths = [] try: episode_num = 0 for traj in do_rollouts( env, num_episodes=args.num_episodes, action_fn=action_fn, render_mode=args.render, ): print('Episode {}'.format(episode_num)) print('> Total reward: {}'.format(traj.total_reward)) if traj.durations: print('> Execution times:') for key in sorted(traj.durations): print('{}{}: {:.2f}ms'.format(' ' * 4, key, traj.durations[key] * 1000)) episode_num += 1 if args.output: paths.append( dict( actions=traj.actions, observations=traj.observations, rewards=traj.rewards, total_reward=traj.total_reward, infos=traj.infos, )) finally: env.close() if paths and args.output: os.makedirs(args.output, exist_ok=True) # Serialize the paths. save_path = os.path.join(args.output, 'paths.pkl') with open(save_path, 'wb') as f: pickle.dump(paths, f) # Log the paths to a CSV file. csv_path = os.path.join(args.output, '{}-results.csv'.format(env_id)) with EpisodeLogger(csv_path) as logger: for path in paths: logger.log_path(path) if __name__ == '__main__': # If calling this script directly, do rollouts with a random policy. rollout_script()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/scripts/enjoy_softlearning.py
robel/scripts/enjoy_softlearning.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Runs a softlearning policy. Example usage: python -m robel.scripts.enjoy_softlearning --device /dev/ttyUSB0 This runs the DClawTurnFixed-v0 environment by default. To run other environments, pass in the environment name with `-e/--env_name` python -m robel.scripts.enjoy_softlearning \ --env_name DClawScrewFixed-v0 \ --device /dev/ttyUSB0 """ import argparse import os import pickle import numpy as np from robel.scripts.rollout import rollout_script POLICY_DIR = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'data/softlearning') DEFAULT_POLICY_FORMAT = os.path.join(POLICY_DIR, '{}.pkl') def policy_factory(args: argparse.Namespace): """Creates the policy.""" # Get default policy path from the environment name. policy_path = args.policy if not policy_path: policy_path = DEFAULT_POLICY_FORMAT.format(args.env_name) # Load the policy with open(policy_path, 'rb') as f: policy_data = pickle.load(f) policy = policy_data['policy'] policy.set_weights(policy_data['weights']) def policy_fn(obs): with policy.set_deterministic(True): actions = policy.actions_np(np.expand_dims(obs, axis=0)) return actions[0] return policy_fn if __name__ == '__main__': rollout_script(policy_factory=policy_factory, add_policy_arg=True)
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/dkitty/push.py
robel/dkitty/push.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Puash task. The robot must push a block to a target point. By default, this environment does not employ any randomizations, and so will exhibit poor sim2real transfer. For better transfer, one may want to borrow some of the randomizations used in DKittyWalkRandomDynamics. """ import collections from typing import Dict, Optional, Sequence import numpy as np from robel.components.tracking import TrackerState from robel.dkitty.avoid import DKittyAvoid from robel.utils.math_utils import calculate_cosine DKITTY_ASSET_PATH = 'robel/dkitty/assets/dkitty_push-v0.xml' DEFAULT_OBSERVATION_KEYS = ( 'root_pos', 'root_euler', 'kitty_qpos', 'root_vel', 'root_angular_vel', 'last_action', 'upright', 'heading', 'block_error', 'target_error', ) class DKittyPush(DKittyAvoid): """Push task.""" def __init__( self, asset_path: str = DKITTY_ASSET_PATH, observation_keys: Sequence[str] = DEFAULT_OBSERVATION_KEYS, device_path: Optional[str] = None, frame_skip: int = 40, upright_threshold: float = 0.9, # cos(~25deg) upright_reward: float = 1, falling_reward: float = 0, # Don't penalize falling. **kwargs): """Initializes the environment. Args: See DKittyAvoid. """ super().__init__( asset_path=asset_path, observation_keys=observation_keys, device_path=device_path, frame_skip=frame_skip, upright_threshold=upright_threshold, upright_reward=upright_reward, falling_reward=falling_reward, **kwargs) def _reset(self): """Resets the environment.""" target_dist = self.np_random.uniform(low=1.5, high=2.5) target_theta = np.pi / 2 + self.np_random.uniform(low=-1, high=1) self._initial_target_pos = target_dist * np.array([ np.cos(target_theta), np.sin(target_theta), 0 ]) for _ in range(10): block_dist = self.np_random.uniform(low=0.6, high=1.2) block_theta = np.pi / 2 + self.np_random.uniform( low=np.pi / 3, high=5 * np.pi / 3) block_x = ( target_dist * np.cos(target_theta) + block_dist * np.cos(block_theta)) block_y = ( target_dist * np.sin(target_theta) + block_dist * np.sin(block_theta)) # Check that block is at least 0.5 away from initial robot point (0, 0). if np.linalg.norm([block_x, block_y]) > 0.5: break self._initial_block_pos = np.array([block_x, block_y, 0.2]) self._reset_dkitty_standing() target_pos = self._initial_target_pos heading_pos = self._initial_heading_pos if heading_pos is None: heading_pos = target_pos block_pos = self._initial_block_pos # Set the tracker locations. self.tracker.set_state({ 'torso': TrackerState(pos=np.zeros(3), rot=np.identity(3)), 'target': TrackerState(pos=target_pos), 'heading': TrackerState(pos=heading_pos), 'block': TrackerState(pos=block_pos), }) def get_obs_dict(self) -> Dict[str, np.ndarray]: """Returns the current observation of the environment. Returns: A dictionary of observation values. This should be an ordered dictionary if `observation_keys` isn't set. """ robot_state = self.robot.get_state('dkitty') (target_state, heading_state, block_state, torso_track_state) = self.tracker.get_state( ['target', 'heading', 'block', 'torso']) target_xy = target_state.pos[:2] block_xy = block_state.pos[:2] kitty_xy = torso_track_state.pos[:2] # Get the heading of the torso (the x-axis). current_heading = torso_track_state.rot[:2, 0] # Get the direction towards the heading location. desired_heading = heading_state.pos[:2] - kitty_xy # Calculate the alignment of the heading with the desired direction. heading = calculate_cosine(current_heading, desired_heading) return collections.OrderedDict(( # Add observation terms relating to being upright. *self._get_upright_obs(torso_track_state).items(), ('root_pos', torso_track_state.pos), ('root_euler', torso_track_state.rot_euler), ('root_vel', torso_track_state.vel), ('root_angular_vel', torso_track_state.angular_vel), ('kitty_qpos', robot_state.qpos), ('kitty_qvel', robot_state.qvel), ('last_action', self._get_last_action()), ('heading', heading), ('target_pos', target_xy), ('block_error', block_xy - kitty_xy), ('target_error', target_xy - kitty_xy), )) def get_reward_dict( self, action: np.ndarray, obs_dict: Dict[str, np.ndarray], ) -> Dict[str, np.ndarray]: """Returns the reward for the given action and observation.""" target_xy_dist = np.linalg.norm(obs_dict['block_error'] - obs_dict['target_error']) block_xy_dist = np.linalg.norm(obs_dict['block_error']) bonus = 20 * (target_xy_dist < 0.5) reward_dict = collections.OrderedDict(( # Add reward terms for being upright. *self._get_upright_rewards(obs_dict).items(), # Reward for proximity of block to the target. ('target_dist_cost', -4 * target_xy_dist), # Reward for proximity of agent to the block. ('block_dist_cost', -2 * block_xy_dist), # Reached target bonus. ('bonus', bonus), )) return reward_dict def get_score_dict( self, obs_dict: Dict[str, np.ndarray], reward_dict: Dict[str, np.ndarray], ) -> Dict[str, np.ndarray]: """Returns a standardized measure of success for the environment.""" return collections.OrderedDict(( ('points', -np.linalg.norm(obs_dict['block_error'] - obs_dict['target_error']) ), ('success', reward_dict['bonus'] > 0.0), ))
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/dkitty/avoid.py
robel/dkitty/avoid.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Avoid task. The robot must navigate to a target point while avoiding an obstacle. By default, this environment does not employ any randomizations, and so will exhibit poor sim2real transfer. For better transfer, one may want to borrow some of the randomizations used in DKittyWalkRandomDynamics. """ import collections from typing import Dict, Optional, Sequence, Union import numpy as np from robel.components.tracking import TrackerComponentBuilder, TrackerState from robel.dkitty.walk import BaseDKittyWalk from robel.utils.math_utils import calculate_cosine DKITTY_ASSET_PATH = 'robel/dkitty/assets/dkitty_avoid-v0.xml' DEFAULT_OBSERVATION_KEYS = ( 'root_pos', 'root_euler', 'kitty_qpos', 'root_vel', 'root_angular_vel', 'kitty_qvel', 'last_action', 'upright', 'heading', 'block_error', 'target_error', ) class DKittyAvoid(BaseDKittyWalk): """Avoid task.""" def __init__( self, asset_path: str = DKITTY_ASSET_PATH, observation_keys: Sequence[str] = DEFAULT_OBSERVATION_KEYS, block_tracker_id: Optional[Union[str, int]] = None, frame_skip: int = 40, upright_threshold: float = 0.9, # cos(~25deg) upright_reward: float = 1, falling_reward: float = 0, # Don't penalize falling. **kwargs): """Initializes the environment. Args: See BaseDKittyWalk. """ self._block_tracker_id = block_tracker_id super().__init__( asset_path=asset_path, observation_keys=observation_keys, frame_skip=frame_skip, upright_threshold=upright_threshold, upright_reward=upright_reward, falling_reward=falling_reward, **kwargs) self._initial_block_pos = np.array([1., 0., 0.2]) def _configure_tracker(self, builder: TrackerComponentBuilder): """Configures the tracker component.""" super()._configure_tracker(builder) builder.add_tracker_group( 'block', hardware_tracker_id=self._block_tracker_id, sim_params=dict( element_name='block', element_type='body', )) def _reset(self): """Resets the environment.""" target_dist = self.np_random.uniform(low=1.5, high=2.5) target_theta = np.pi / 2 + self.np_random.uniform(low=-1, high=1) self._initial_target_pos = target_dist * np.array([ np.cos(target_theta), np.sin(target_theta), 0 ]) block_dist = max( 0.6, target_dist * self.np_random.uniform(low=0.3, high=0.8)) block_theta = target_theta + self.np_random.uniform(low=-0.5, high=0.5) self._initial_block_pos = np.array([ block_dist * np.cos(block_theta), block_dist * np.sin(block_theta), 0.2, ]) self._reset_dkitty_standing() target_pos = self._initial_target_pos heading_pos = self._initial_heading_pos if heading_pos is None: heading_pos = target_pos block_pos = self._initial_block_pos # Set the tracker locations. self.tracker.set_state({ 'torso': TrackerState(pos=np.zeros(3), rot=np.identity(3)), 'target': TrackerState(pos=target_pos), 'heading': TrackerState(pos=heading_pos), 'block': TrackerState(pos=block_pos), }) def get_obs_dict(self) -> Dict[str, np.ndarray]: """Returns the current observation of the environment. Returns: A dictionary of observation values. This should be an ordered dictionary if `observation_keys` isn't set. """ robot_state = self.robot.get_state('dkitty') target_state, heading_state, block_state, torso_track_state = ( self.tracker.get_state(['target', 'heading', 'block', 'torso'])) target_xy = target_state.pos[:2] block_xy = block_state.pos[:2] kitty_xy = torso_track_state.pos[:2] # Get the heading of the torso (the x-axis). current_heading = torso_track_state.rot[:2, 0] # Get the direction towards the heading location. desired_heading = heading_state.pos[:2] - kitty_xy # Calculate the alignment of the heading with the desired direction. heading = calculate_cosine(current_heading, desired_heading) return collections.OrderedDict(( # Add observation terms relating to being upright. *self._get_upright_obs(torso_track_state).items(), ('root_pos', torso_track_state.pos), ('root_euler', torso_track_state.rot_euler), ('root_vel', torso_track_state.vel), ('root_angular_vel', torso_track_state.angular_vel), ('kitty_qpos', robot_state.qpos), ('kitty_qvel', robot_state.qvel), ('last_action', self._get_last_action()), ('heading', heading), ('target_pos', target_xy), ('block_error', block_xy - kitty_xy), ('target_error', target_xy - kitty_xy), )) def get_reward_dict( self, action: np.ndarray, obs_dict: Dict[str, np.ndarray], ) -> Dict[str, np.ndarray]: """Returns the reward for the given action and observation.""" target_xy_dist = np.linalg.norm(obs_dict['target_error']) block_xy_dist = np.abs(obs_dict['block_error']) block_cost = -40 * np.all(block_xy_dist <= 0.5) bonus = 20 * (target_xy_dist < 0.5) * np.any(block_xy_dist > 0.5) reward_dict = collections.OrderedDict(( # Add reward terms for being upright. *self._get_upright_rewards(obs_dict).items(), # Reward for proximity to the target. ('target_dist_cost', -4 * target_xy_dist), ('block_cost', block_cost), ('bonus', bonus), )) return reward_dict def get_score_dict( self, obs_dict: Dict[str, np.ndarray], reward_dict: Dict[str, np.ndarray], ) -> Dict[str, np.ndarray]: """Returns a standardized measure of success for the environment.""" return collections.OrderedDict(( ('points', -np.linalg.norm(obs_dict['target_error'])), ('success', reward_dict['bonus'] > 0.0), )) def get_done( self, obs_dict: Dict[str, np.ndarray], reward_dict: Dict[str, np.ndarray], ) -> np.ndarray: """Returns whether the episode should terminate.""" return np.array(False) # Never terminate.
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/dkitty/walk_test.py
robel/dkitty/walk_test.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for DKitty walk tasks.""" from absl.testing import absltest from absl.testing import parameterized import gym import numpy as np from robel.dkitty.walk import (DKittyWalkFixed, DKittyWalkRandom, DKittyWalkRandomDynamics) # pylint: disable=no-member @parameterized.parameters( ('DKittyWalkFixed-v0', DKittyWalkFixed), ('DKittyWalkRandom-v0', DKittyWalkRandom), ('DKittyWalkRandomDynamics-v0', DKittyWalkRandomDynamics), ) class DKittyWalkTest(absltest.TestCase): """Unit test class for RobotEnv.""" def test_gym_make(self, env_id, env_cls): """Accesses the sim, model, and data properties.""" env = gym.make(env_id) self.assertIsInstance(env.unwrapped, env_cls) def test_spaces(self, _, env_cls): """Checks the observation, action, and state spaces.""" env = env_cls() observation_size = np.sum([ 3, # root_qpos 3, # root_euler 12, # kitty_qpos 3, # root_vel 3, # root_angular_vel 12, # kitty_qvel 12, # last_action 1, # upright 1, # heading 2, # target error ]) self.assertEqual(env.observation_space.shape, (observation_size,)) self.assertEqual(env.action_space.shape, (12,)) self.assertEqual(env.state_space['root_pos'].shape, (3,)) self.assertEqual(env.state_space['root_euler'].shape, (3,)) self.assertEqual(env.state_space['root_vel'].shape, (3,)) self.assertEqual(env.state_space['root_angular_vel'].shape, (3,)) self.assertEqual(env.state_space['kitty_qpos'].shape, (12,)) self.assertEqual(env.state_space['kitty_qvel'].shape, (12,)) def test_reset_step(self, _, env_cls): """Checks that resetting and stepping works.""" env = env_cls() env.reset() env.step(env.action_space.sample()) if __name__ == '__main__': absltest.main()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/dkitty/orient.py
robel/dkitty/orient.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Orient tasks with D'Kitty robots. The goal is to change the orientation of the D'Kitty in place. """ import abc import collections from typing import Dict, Optional, Sequence, Tuple, Union import numpy as np from transforms3d.euler import euler2quat from robel.components.tracking import TrackerComponentBuilder, TrackerState from robel.dkitty.base_env import BaseDKittyUprightEnv from robel.simulation.randomize import SimRandomizer from robel.utils.configurable import configurable from robel.utils.math_utils import calculate_cosine from robel.utils.resources import get_asset_path DKITTY_ASSET_PATH = 'robel/dkitty/assets/dkitty_orient-v0.xml' DEFAULT_OBSERVATION_KEYS = ( 'root_pos', 'root_euler', 'kitty_qpos', 'root_vel', 'root_angular_vel', 'kitty_qvel', 'last_action', 'upright', 'current_facing', 'desired_facing', ) class BaseDKittyOrient(BaseDKittyUprightEnv, metaclass=abc.ABCMeta): """Shared logic for DKitty orient tasks.""" def __init__( self, asset_path: str = DKITTY_ASSET_PATH, observation_keys: Sequence[str] = DEFAULT_OBSERVATION_KEYS, target_tracker_id: Optional[Union[str, int]] = None, frame_skip: int = 40, upright_threshold: float = 0.9, # cos(~25deg) upright_reward: float = 2, falling_reward: float = -500, **kwargs): """Initializes the environment. Args: asset_path: The XML model file to load. observation_keys: The keys in `get_obs_dict` to concatenate as the observations returned by `step` and `reset`. target_tracker_id: The device index or serial of the tracking device for the target. frame_skip: The number of simulation steps per environment step. upright_threshold: The threshold (in [0, 1]) above which the D'Kitty is considered to be upright. If the cosine similarity of the D'Kitty's z-axis with the global z-axis is below this threshold, the D'Kitty is considered to have fallen. upright_reward: The reward multiplier for uprightedness. falling_reward: The reward multipler for falling. """ self._target_tracker_id = target_tracker_id super().__init__( sim_model=get_asset_path(asset_path), observation_keys=observation_keys, frame_skip=frame_skip, upright_threshold=upright_threshold, upright_reward=upright_reward, falling_reward=falling_reward, **kwargs) self._initial_angle = 0 self._target_angle = 0 self._markers_bid = self.model.body_name2id('markers') self._current_angle_bid = self.model.body_name2id('current_angle') self._target_angle_bid = self.model.body_name2id('target_angle') def _configure_tracker(self, builder): """Configures the tracker component.""" super()._configure_tracker(builder) builder.add_tracker_group( 'target', hardware_tracker_id=self._target_tracker_id, sim_params=dict( element_name='target', element_type='site', ), mimic_xy_only=True) def _reset(self): """Resets the environment.""" self._reset_dkitty_standing() # Set the initial target position. self.tracker.set_state({ 'torso': TrackerState( pos=np.zeros(3), rot_euler=np.array([0, 0, self._initial_angle])), 'target': TrackerState( pos=np.array([ # The D'Kitty is offset to face the y-axis. np.cos(self._target_angle + np.pi / 2), np.sin(self._target_angle + np.pi / 2), 0, ])), }) def _step(self, action: np.ndarray): """Applies an action to the robot.""" self.robot.step({ 'dkitty': action, }) def get_obs_dict(self) -> Dict[str, np.ndarray]: """Returns the current observation of the environment. Returns: A dictionary of observation values. This should be an ordered dictionary if `observation_keys` isn't set. """ robot_state = self.robot.get_state('dkitty') torso_track_state, target_track_state = self.tracker.get_state( ['torso', 'target']) # Get the facing direction of the kitty. (the y-axis). current_facing = torso_track_state.rot[:2, 1] # Get the direction to the target. target_facing = target_track_state.pos[:2] - torso_track_state.pos[:2] target_facing = target_facing / np.linalg.norm(target_facing + 1e-8) # Calculate the alignment to the facing direction. angle_error = np.arccos(calculate_cosine(current_facing, target_facing)) self._update_markers(torso_track_state.pos, current_facing, target_facing) return collections.OrderedDict(( # Add observation terms relating to being upright. *self._get_upright_obs(torso_track_state).items(), ('root_pos', torso_track_state.pos), ('root_euler', torso_track_state.rot_euler), ('root_vel', torso_track_state.vel), ('root_angular_vel', torso_track_state.angular_vel), ('kitty_qpos', robot_state.qpos), ('kitty_qvel', robot_state.qvel), ('last_action', self._get_last_action()), ('current_facing', current_facing), ('desired_facing', target_facing), ('angle_error', angle_error), )) def get_reward_dict( self, action: np.ndarray, obs_dict: Dict[str, np.ndarray], ) -> Dict[str, np.ndarray]: """Returns the reward for the given action and observation.""" angle_error = obs_dict['angle_error'] upright = obs_dict[self._upright_obs_key] center_dist = np.linalg.norm(obs_dict['root_pos'][:2], axis=1) reward_dict = collections.OrderedDict(( # Add reward terms for being upright. *self._get_upright_rewards(obs_dict).items(), # Reward for closeness to desired facing direction. ('alignment_error_cost', -4 * angle_error), # Reward for closeness to center; i.e. being stationary. ('center_distance_cost', -4 * center_dist), # Bonus when mean error < 15deg or upright within 15deg. ('bonus_small', 5 * ((angle_error < 0.26) + (upright > 0.96))), # Bonus when error < 5deg and upright within 15deg. ('bonus_big', 10 * ((angle_error < 0.087) * (upright > 0.96))), )) return reward_dict def get_score_dict( self, obs_dict: Dict[str, np.ndarray], reward_dict: Dict[str, np.ndarray], ) -> Dict[str, np.ndarray]: """Returns a standardized measure of success for the environment.""" return collections.OrderedDict(( ('points', 1.0 - obs_dict['angle_error'] / np.pi), ('success', reward_dict['bonus_big'] > 0.0), )) def _update_markers(self, root_pos: np.ndarray, current_facing: np.ndarray, target_facing: np.ndarray): """Updates the simulation markers denoting the facing direction.""" self.model.body_pos[self._markers_bid][:2] = root_pos[:2] current_angle = np.arctan2(current_facing[1], current_facing[0]) target_angle = np.arctan2(target_facing[1], target_facing[0]) self.model.body_quat[self._current_angle_bid] = euler2quat( 0, 0, current_angle, axes='rxyz') self.model.body_quat[self._target_angle_bid] = euler2quat( 0, 0, target_angle, axes='rxyz') self.sim.forward() @configurable(pickleable=True) class DKittyOrientFixed(BaseDKittyOrient): """Stand up from a fixed position.""" def _reset(self): """Resets the environment.""" # Put target behind the D'Kitty (180deg rotation). self._initial_angle = 0 self._target_angle = np.pi super()._reset() @configurable(pickleable=True) class DKittyOrientRandom(BaseDKittyOrient): """Walk straight towards a random location.""" def __init__( self, *args, # +/-60deg initial_angle_range: Tuple[float, float] = (-np.pi / 3, np.pi / 3), # 180 +/- 60deg target_angle_range: Tuple[float, float] = (2 * np.pi / 3, 4 * np.pi / 3), **kwargs): """Initializes the environment. Args: initial_angle_range: The range to sample an initial orientation of the D'Kitty about the z-axis. target_angle_range: The range to sample a target orientation of the D'Kitty about the z-axis. """ super().__init__(*args, **kwargs) self._initial_angle_range = initial_angle_range self._target_angle_range = target_angle_range def _reset(self): """Resets the environment.""" self._initial_angle = self.np_random.uniform(*self._initial_angle_range) self._target_angle = self.np_random.uniform(*self._target_angle_range) super()._reset() @configurable(pickleable=True) class DKittyOrientRandomDynamics(DKittyOrientRandom): """Walk straight towards a random location.""" def __init__(self, *args, sim_observation_noise: Optional[float] = 0.05, **kwargs): super().__init__( *args, sim_observation_noise=sim_observation_noise, **kwargs) self._randomizer = SimRandomizer(self) self._dof_indices = ( self.robot.get_config('dkitty').qvel_indices.tolist()) def _reset(self): """Resets the environment.""" # Randomize joint dynamics. self._randomizer.randomize_dofs( self._dof_indices, all_same=True, damping_range=(0.1, 0.2), friction_loss_range=(0.001, 0.005), ) self._randomizer.randomize_actuators( all_same=True, kp_range=(2.8, 3.2), ) # Randomize friction on all geoms in the scene. self._randomizer.randomize_geoms( all_same=True, friction_slide_range=(0.8, 1.2), friction_spin_range=(0.003, 0.007), friction_roll_range=(0.00005, 0.00015), ) # Generate a random height field. self._randomizer.randomize_global( total_mass_range=(1.6, 2.0), height_field_range=(0, 0.05), ) self.sim_scene.upload_height_field(0) super()._reset()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/dkitty/stand_test.py
robel/dkitty/stand_test.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for DKitty walk tasks.""" from absl.testing import absltest from absl.testing import parameterized import gym import numpy as np from robel.dkitty.stand import (DKittyStandFixed, DKittyStandRandom, DKittyStandRandomDynamics) # pylint: disable=no-member @parameterized.parameters( ('DKittyStandFixed-v0', DKittyStandFixed), ('DKittyStandRandom-v0', DKittyStandRandom), ('DKittyStandRandomDynamics-v0', DKittyStandRandomDynamics), ) class DKittyStandTest(absltest.TestCase): """Unit test class for RobotEnv.""" def test_gym_make(self, env_id, env_cls): """Accesses the sim, model, and data properties.""" env = gym.make(env_id) self.assertIsInstance(env.unwrapped, env_cls) def test_spaces(self, _, env_cls): """Checks the observation, action, and state spaces.""" env = env_cls() observation_size = np.sum([ 3, # root_qpos 3, # root_euler 12, # kitty_qpos 3, # root_vel 3, # root_angular_vel 12, # kitty_qvel 12, # last_action 1, # upright 12, # pose error ]) self.assertEqual(env.observation_space.shape, (observation_size,)) self.assertEqual(env.action_space.shape, (12,)) self.assertEqual(env.state_space['root_pos'].shape, (3,)) self.assertEqual(env.state_space['root_euler'].shape, (3,)) self.assertEqual(env.state_space['root_vel'].shape, (3,)) self.assertEqual(env.state_space['root_angular_vel'].shape, (3,)) self.assertEqual(env.state_space['kitty_qpos'].shape, (12,)) self.assertEqual(env.state_space['kitty_qvel'].shape, (12,)) def test_reset_step(self, _, env_cls): """Checks that resetting and stepping works.""" env = env_cls() env.reset() env.step(env.action_space.sample()) if __name__ == '__main__': absltest.main()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/dkitty/stand.py
robel/dkitty/stand.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Standing tasks with D'Kitty robots. The goal is to stand upright from an initial configuration. """ import abc import collections from typing import Dict, Optional, Sequence import numpy as np from robel.components.tracking import TrackerState from robel.dkitty.base_env import BaseDKittyUprightEnv from robel.simulation.randomize import SimRandomizer from robel.utils.configurable import configurable from robel.utils.resources import get_asset_path DKITTY_ASSET_PATH = 'robel/dkitty/assets/dkitty_stand-v0.xml' DEFAULT_OBSERVATION_KEYS = ( 'root_pos', 'root_euler', 'kitty_qpos', 'root_vel', 'root_angular_vel', 'kitty_qvel', 'last_action', 'upright', 'pose_error', ) class BaseDKittyStand(BaseDKittyUprightEnv, metaclass=abc.ABCMeta): """Shared logic for DKitty turn tasks.""" def __init__( self, asset_path: str = DKITTY_ASSET_PATH, observation_keys: Sequence[str] = DEFAULT_OBSERVATION_KEYS, frame_skip: int = 40, upright_threshold: float = 0, # cos(90deg) upright_reward: float = 2, falling_reward: float = -100, **kwargs): """Initializes the environment. Args: asset_path: The XML model file to load. observation_keys: The keys in `get_obs_dict` to concatenate as the observations returned by `step` and `reset`. device_path: The device path to Dynamixel hardware. torso_tracker_id: The device index or serial of the tracking device for the D'Kitty torso. frame_skip: The number of simulation steps per environment step. upright_threshold: The threshold (in [0, 1]) above which the D'Kitty is considered to be upright. If the cosine similarity of the D'Kitty's z-axis with the global z-axis is below this threshold, the D'Kitty is considered to have fallen. upright_reward: The reward multiplier for uprightedness. falling_reward: The reward multipler for falling. """ super().__init__( sim_model=get_asset_path(asset_path), observation_keys=observation_keys, frame_skip=frame_skip, upright_threshold=upright_threshold, upright_reward=upright_reward, falling_reward=falling_reward, **kwargs) self._desired_pose = np.zeros(12) self._initial_pose = np.zeros(12) def _reset(self): """Resets the environment.""" self._reset_dkitty_standing(kitty_pos=self._initial_pose,) self.tracker.set_state({ 'torso': TrackerState(pos=np.zeros(3), rot=np.identity(3)), }) # Let gravity pull the simulated robot to the ground before starting. if not self.robot.is_hardware: self.robot.step({'dkitty': self._initial_pose}, denormalize=False) self.sim_scene.advance(100) def _step(self, action: np.ndarray): """Applies an action to the robot.""" self.robot.step({ 'dkitty': action, }) def get_obs_dict(self) -> Dict[str, np.ndarray]: """Returns the current observation of the environment. Returns: A dictionary of observation values. This should be an ordered dictionary if `observation_keys` isn't set. """ robot_state = self.robot.get_state('dkitty') torso_track_state = self.tracker.get_state('torso') return collections.OrderedDict(( # Add observation terms relating to being upright. *self._get_upright_obs(torso_track_state).items(), ('root_pos', torso_track_state.pos), ('root_euler', torso_track_state.rot_euler), ('root_vel', torso_track_state.vel), ('root_angular_vel', torso_track_state.angular_vel), ('kitty_qpos', robot_state.qpos), ('kitty_qvel', robot_state.qvel), ('last_action', self._get_last_action()), ('pose_error', self._desired_pose - robot_state.qpos), )) def get_reward_dict( self, action: np.ndarray, obs_dict: Dict[str, np.ndarray], ) -> Dict[str, np.ndarray]: """Returns the reward for the given action and observation.""" pose_mean_error = np.abs(obs_dict['pose_error']).mean(axis=1) upright = obs_dict[self._upright_obs_key] center_dist = np.linalg.norm(obs_dict['root_pos'][:2], axis=1) reward_dict = collections.OrderedDict(( # Add reward terms for being upright. *self._get_upright_rewards(obs_dict).items(), # Reward for closeness to desired pose. ('pose_error_cost', -4 * pose_mean_error), # Reward for closeness to center; i.e. being stationary. ('center_distance_cost', -2 * center_dist), # Bonus when mean error < 30deg, scaled by uprightedness. ('bonus_small', 5 * (pose_mean_error < (np.pi / 6)) * upright), # Bonus when mean error < 15deg and upright within 30deg. ('bonus_big', 10 * (pose_mean_error < (np.pi / 12)) * (upright > 0.9)), )) return reward_dict def get_score_dict( self, obs_dict: Dict[str, np.ndarray], reward_dict: Dict[str, np.ndarray], ) -> Dict[str, np.ndarray]: """Returns a standardized measure of success for the environment.""" # Normalize pose error by 60deg. pose_points = (1 - np.maximum( np.abs(obs_dict['pose_error']).mean(axis=1) / (np.pi / 3), 1)) return collections.OrderedDict(( ('points', pose_points * obs_dict['upright']), ('success', reward_dict['bonus_big'] > 0.0), )) @configurable(pickleable=True) class DKittyStandFixed(BaseDKittyStand): """Stand up from a fixed position.""" def _reset(self): """Resets the environment.""" self._initial_pose[[0, 3, 6, 9]] = 0 self._initial_pose[[1, 4, 7, 10]] = np.pi / 4 self._initial_pose[[2, 5, 8, 11]] = -np.pi / 2 super()._reset() @configurable(pickleable=True) class DKittyStandRandom(BaseDKittyStand): """Stand up from a random position.""" def _reset(self): """Resets the environment.""" limits = self.robot.get_config('dkitty').qpos_range self._initial_pose = self.np_random.uniform( low=limits[:, 0], high=limits[:, 1]) super()._reset() @configurable(pickleable=True) class DKittyStandRandomDynamics(DKittyStandRandom): """Stand up from a random positon with randomized dynamics.""" def __init__(self, *args, sim_observation_noise: Optional[float] = 0.05, **kwargs): super().__init__( *args, sim_observation_noise=sim_observation_noise, **kwargs) self._randomizer = SimRandomizer(self) self._dof_indices = ( self.robot.get_config('dkitty').qvel_indices.tolist()) def _reset(self): """Resets the environment.""" # Randomize joint dynamics. self._randomizer.randomize_dofs( self._dof_indices, all_same=True, damping_range=(0.1, 0.2), friction_loss_range=(0.001, 0.005), ) self._randomizer.randomize_actuators( all_same=True, kp_range=(2, 4), ) # Randomize friction on all geoms in the scene. self._randomizer.randomize_geoms( all_same=True, friction_slide_range=(0.8, 1.2), friction_spin_range=(0.003, 0.007), friction_roll_range=(0.00005, 0.00015), ) # Generate a random height field. self._randomizer.randomize_global( total_mass_range=(1.6, 2.0), height_field_range=(0, 0.05), ) self.sim_scene.upload_height_field(0) super()._reset()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/dkitty/base_env.py
robel/dkitty/base_env.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Shared logic for all DKitty environments.""" import abc from typing import Dict, Optional, Sequence, Union import gym import numpy as np from robel.components.robot import RobotComponentBuilder, RobotState from robel.components.robot.dynamixel_utils import CalibrationMap from robel.components.tracking import (TrackerComponentBuilder, TrackerState, TrackerType) from robel.dkitty.utils.manual_reset import ManualAutoDKittyResetProcedure from robel.dkitty.utils.scripted_reset import ScriptedDKittyResetProcedure from robel.robot_env import make_box_space, RobotEnv from robel.utils.reset_procedure import ManualResetProcedure # Convenience constants. PI = np.pi # Mapping of motor ID to (scale, offset). DEFAULT_DKITTY_CALIBRATION_MAP = CalibrationMap({ # Front right leg. 10: (1, -3. * PI / 2), 11: (-1, PI), 12: (-1, PI), # Front left leg. 20: (1, -PI / 2), 21: (1, -PI), 22: (1, -PI), # Back left leg. 30: (-1, 3. * PI / 2), 31: (1, -PI), 32: (1, -PI), # Back right leg. 40: (-1, PI / 2), 41: (-1, PI), 42: (-1, PI), }) class BaseDKittyEnv(RobotEnv, metaclass=abc.ABCMeta): """Base environment for all DKitty robot tasks.""" def __init__(self, *args, device_path: Optional[str] = None, sim_observation_noise: Optional[float] = None, reset_type: Optional[str] = None, plot_tracking: bool = False, phasespace_server: Optional[str] = None, **kwargs): """Initializes the environment. Args: device_path: The device path to Dynamixel hardware. sim_observation_noise: If given, configures the RobotComponent to add noise to observations. manual_reset: If True, waits for the user to reset the robot instead of performing the automatic reset procedure. plot_tracking: If True, displays a plot that shows the tracked positions. NOTE: Currently this causes the environment to run more slowly. phasespace_server: The PhaseSpace server to connect to. If given, PhaseSpace is used as the tracking provider instead of OpenVR. """ super().__init__(*args, **kwargs) self._device_path = device_path self._sim_observation_noise = sim_observation_noise # Configure the robot component. robot_builder = RobotComponentBuilder() self._configure_robot(robot_builder) # Configure the tracker component. tracker_builder = TrackerComponentBuilder() self._configure_tracker(tracker_builder) if phasespace_server: tracker_builder.set_tracker_type( TrackerType.PHASESPACE, server_address=phasespace_server) # Configure the hardware reset procedure. self._hardware_reset = None if self._device_path is not None: if reset_type is None or reset_type == 'scripted': self._hardware_reset = ScriptedDKittyResetProcedure() elif reset_type == 'manual-auto': self._hardware_reset = ManualAutoDKittyResetProcedure() elif reset_type == 'manual': self._hardware_reset = ManualResetProcedure() else: raise NotImplementedError(reset_type) for builder in (robot_builder, tracker_builder): self._hardware_reset.configure_reset_groups(builder) # Create the components. self.robot = self._add_component(robot_builder) self.tracker = self._add_component(tracker_builder) # Disable the constraint solver in hardware so that mimicked positions # do not participate in contact calculations. if self.robot.is_hardware: self.sim_scene.disable_option(constraint_solver=True) if plot_tracking and self.tracker.is_hardware: self.tracker.show_plot() def get_state(self) -> Dict[str, np.ndarray]: """Returns the current state of the environment.""" kitty_state = self.robot.get_state('dkitty') torso_state = self.tracker.get_state('torso') return { 'root_pos': torso_state.pos, 'root_euler': torso_state.rot_euler, 'root_vel': torso_state.vel, 'root_angular_vel': torso_state.angular_vel, 'kitty_qpos': kitty_state.qpos, 'kitty_qvel': kitty_state.qvel, } def set_state(self, state: Dict[str, np.ndarray]): """Sets the state of the environment.""" self.robot.set_state({ 'dkitty': RobotState( qpos=state['kitty_qpos'], qvel=state['kitty_qvel']), }) self.tracker.set_state({ 'torso': TrackerState( pos=state['root_pos'], rot_euler=state['root_euler'], vel=state['root_vel'], angular_vel=state['root_angular_vel']) }) def _configure_robot(self, builder: RobotComponentBuilder): """Configures the robot component.""" builder.add_group( 'dkitty', actuator_indices=range(12), qpos_indices=range(6, 18), qpos_range=[ # FR (-0.5, 0.279), (0.0, PI / 2), (-2.0, 0.0), # FL (-0.279, 0.5), (0.0, PI / 2), (-2.0, 0.0), # BL (-0.279, 0.5), (0.0, PI / 2), (-2.0, 0.0), # BR (-0.5, 0.279), (0.0, PI / 2), (-2.0, 0.0), ], qvel_range=[(-PI, PI)] * 12, ) if self._sim_observation_noise is not None: builder.update_group( 'dkitty', sim_observation_noise=self._sim_observation_noise) # If a device path is given, set the motor IDs and calibration map. if self._device_path is not None: builder.set_dynamixel_device_path(self._device_path) builder.set_hardware_calibration_map(DEFAULT_DKITTY_CALIBRATION_MAP) builder.update_group( 'dkitty', motor_ids=[10, 11, 12, 20, 21, 22, 30, 31, 32, 40, 41, 42]) def _configure_tracker(self, builder: TrackerComponentBuilder): """Configures the tracker component.""" def _initialize_action_space(self) -> gym.Space: """Returns the observation space to use for this environment.""" qpos_indices = self.robot.get_config('dkitty').qpos_indices return make_box_space(-1.0, 1.0, shape=(qpos_indices.size,)) def _reset_dkitty_standing(self, kitty_pos: Optional[Sequence[float]] = None, kitty_vel: Optional[Sequence[float]] = None): """Resets the D'Kitty to a standing position. Args: kitty_pos: The joint positions (radians). kitty_vel: The joint velocities (radians/second). """ # Set defaults if parameters are not given. kitty_pos = np.zeros(12) if kitty_pos is None else np.asarray(kitty_pos) kitty_vel = np.zeros(12) if kitty_vel is None else np.asarray(kitty_vel) # Perform the scripted reset if we're not doing manual resets. if self._hardware_reset: self._hardware_reset.reset(robot=self.robot, tracker=self.tracker) # Reset the robot state. self.robot.set_state({ 'dkitty': RobotState(qpos=kitty_pos, qvel=kitty_vel), }) # Complete the hardware reset. if self._hardware_reset: self._hardware_reset.finish() # Reset the clock to 0 for hardware. if self.robot.is_hardware: self.robot.reset_time() class BaseDKittyUprightEnv(BaseDKittyEnv): """Base environment for D'Kitty tasks where the D'Kitty must be upright.""" def __init__( self, *args, torso_tracker_id: Optional[Union[str, int]] = None, upright_obs_key: str = 'upright', upright_threshold: float = 0, # cos(90deg). upright_reward: float = 1, falling_reward: float = -100, **kwargs): """Initializes the environment. Args: torso_tracker_id: The device index or serial of the tracking device for the D'Kitty torso. upright_obs_key: The observation key for uprightnedness. upright_threshold: The threshold (in [0, 1]) above which the D'Kitty is considered to be upright. If the cosine similarity of the D'Kitty's z-axis with the global z-axis is below this threshold, the D'Kitty is considered to have fallen. upright_reward: The reward multiplier for uprightedness. falling_reward: The reward multipler for falling. **kwargs: Arguemnts to pass to BaseDKittyEnv. """ self._torso_tracker_id = torso_tracker_id super().__init__(*args, **kwargs) self._upright_obs_key = upright_obs_key self._upright_threshold = upright_threshold self._upright_reward = upright_reward self._falling_reward = falling_reward def _configure_tracker(self, builder: TrackerComponentBuilder): """Configures the tracker component.""" super()._configure_tracker(builder) builder.add_tracker_group( 'torso', hardware_tracker_id=self._torso_tracker_id, sim_params=dict( element_name='torso', element_type='joint', qpos_indices=range(6), ), hardware_params=dict( is_origin=True, # tracked_rotation_offset=(-1.57, 0, 1.57), )) def _get_upright_obs(self, torso_track_state: TrackerState) -> Dict[str, float]: """Returns a dictionary of uprightedness observations.""" return {self._upright_obs_key: torso_track_state.rot[2, 2]} def _get_upright_rewards( self, obs_dict: Dict[str, np.ndarray], ) -> Dict[str, np.ndarray]: """Returns the reward for the given action and observation.""" upright = obs_dict[self._upright_obs_key] return { 'upright': ( self._upright_reward * (upright - self._upright_threshold) / (1 - self._upright_threshold)), 'falling': self._falling_reward * (upright < self._upright_threshold), } def get_done( self, obs_dict: Dict[str, np.ndarray], reward_dict: Dict[str, np.ndarray], ) -> np.ndarray: """Returns whether the episode should terminate.""" return obs_dict[self._upright_obs_key] < self._upright_threshold
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/dkitty/walk.py
robel/dkitty/walk.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Walk tasks with DKitty robots. This is a single movement from an initial position to a target position. """ import abc import collections from typing import Dict, Optional, Sequence, Tuple, Union import numpy as np from robel.components.tracking import TrackerComponentBuilder, TrackerState from robel.dkitty.base_env import BaseDKittyUprightEnv from robel.simulation.randomize import SimRandomizer from robel.utils.configurable import configurable from robel.utils.math_utils import calculate_cosine from robel.utils.resources import get_asset_path DKITTY_ASSET_PATH = 'robel/dkitty/assets/dkitty_walk-v0.xml' DEFAULT_OBSERVATION_KEYS = ( 'root_pos', 'root_euler', 'kitty_qpos', 'root_vel', 'root_angular_vel', 'kitty_qvel', 'last_action', 'upright', 'heading', 'target_error', ) class BaseDKittyWalk(BaseDKittyUprightEnv, metaclass=abc.ABCMeta): """Shared logic for DKitty walk tasks.""" def __init__(self, asset_path: str = DKITTY_ASSET_PATH, observation_keys: Sequence[str] = DEFAULT_OBSERVATION_KEYS, target_tracker_id: Optional[Union[str, int]] = None, heading_tracker_id: Optional[Union[str, int]] = None, frame_skip: int = 40, upright_threshold: float = 0.9, upright_reward: float = 1, falling_reward: float = -500, **kwargs): """Initializes the environment. Args: asset_path: The XML model file to load. observation_keys: The keys in `get_obs_dict` to concatenate as the observations returned by `step` and `reset`. target_tracker_id: The device index or serial of the tracking device for the target location. heading_tracker_id: The device index or serial of the tracking device for the heading direction. This defaults to the target tracker. frame_skip: The number of simulation steps per environment step. upright_threshold: The threshold (in [0, 1]) above which the D'Kitty is considered to be upright. If the cosine similarity of the D'Kitty's z-axis with the global z-axis is below this threshold, the D'Kitty is considered to have fallen. upright_reward: The reward multiplier for uprightedness. falling_reward: The reward multipler for falling. """ self._target_tracker_id = target_tracker_id self._heading_tracker_id = heading_tracker_id if self._heading_tracker_id is None: self._heading_tracker_id = self._target_tracker_id super().__init__( sim_model=get_asset_path(asset_path), observation_keys=observation_keys, frame_skip=frame_skip, upright_threshold=upright_threshold, upright_reward=upright_reward, falling_reward=falling_reward, **kwargs) self._initial_target_pos = np.zeros(3) self._initial_heading_pos = None def _configure_tracker(self, builder: TrackerComponentBuilder): """Configures the tracker component.""" super()._configure_tracker(builder) builder.add_tracker_group( 'target', hardware_tracker_id=self._target_tracker_id, sim_params=dict( element_name='target', element_type='site', ), mimic_xy_only=True) builder.add_tracker_group( 'heading', hardware_tracker_id=self._heading_tracker_id, sim_params=dict( element_name='heading', element_type='site', ), mimic_xy_only=True) def _reset(self): """Resets the environment.""" self._reset_dkitty_standing() # If no heading is provided, head towards the target. target_pos = self._initial_target_pos heading_pos = self._initial_heading_pos if heading_pos is None: heading_pos = target_pos # Set the tracker locations. self.tracker.set_state({ 'torso': TrackerState(pos=np.zeros(3), rot=np.identity(3)), 'target': TrackerState(pos=target_pos), 'heading': TrackerState(pos=heading_pos), }) def _step(self, action: np.ndarray): """Applies an action to the robot.""" # Apply action. self.robot.step({ 'dkitty': action, }) def get_obs_dict(self) -> Dict[str, np.ndarray]: """Returns the current observation of the environment. Returns: A dictionary of observation values. This should be an ordered dictionary if `observation_keys` isn't set. """ robot_state = self.robot.get_state('dkitty') target_state, heading_state, torso_track_state = self.tracker.get_state( ['target', 'heading', 'torso']) target_xy = target_state.pos[:2] kitty_xy = torso_track_state.pos[:2] # Get the heading of the torso (the y-axis). current_heading = torso_track_state.rot[:2, 1] # Get the direction towards the heading location. desired_heading = heading_state.pos[:2] - kitty_xy # Calculate the alignment of the heading with the desired direction. heading = calculate_cosine(current_heading, desired_heading) return collections.OrderedDict(( # Add observation terms relating to being upright. *self._get_upright_obs(torso_track_state).items(), ('root_pos', torso_track_state.pos), ('root_euler', torso_track_state.rot_euler), ('root_vel', torso_track_state.vel), ('root_angular_vel', torso_track_state.angular_vel), ('kitty_qpos', robot_state.qpos), ('kitty_qvel', robot_state.qvel), ('last_action', self._get_last_action()), ('heading', heading), ('target_pos', target_xy), ('target_error', target_xy - kitty_xy), )) def get_reward_dict( self, action: np.ndarray, obs_dict: Dict[str, np.ndarray], ) -> Dict[str, np.ndarray]: """Returns the reward for the given action and observation.""" target_xy_dist = np.linalg.norm(obs_dict['target_error']) heading = obs_dict['heading'] reward_dict = collections.OrderedDict(( # Add reward terms for being upright. *self._get_upright_rewards(obs_dict).items(), # Reward for proximity to the target. ('target_dist_cost', -4 * target_xy_dist), # Heading - 1 @ cos(0) to 0 @ cos(25deg). ('heading', 2 * (heading - 0.9) / 0.1), # Bonus ('bonus_small', 5 * ((target_xy_dist < 0.5) + (heading > 0.9))), ('bonus_big', 10 * (target_xy_dist < 0.5) * (heading > 0.9)), )) return reward_dict def get_score_dict( self, obs_dict: Dict[str, np.ndarray], reward_dict: Dict[str, np.ndarray], ) -> Dict[str, np.ndarray]: """Returns a standardized measure of success for the environment.""" return collections.OrderedDict(( ('points', -np.linalg.norm(obs_dict['target_error'])), ('success', reward_dict['bonus_big'] > 0.0), )) @configurable(pickleable=True) class DKittyWalkFixed(BaseDKittyWalk): """Walk straight towards a fixed location.""" def _reset(self): """Resets the environment.""" target_dist = 2.0 target_theta = np.pi / 2 # Point towards y-axis self._initial_target_pos = target_dist * np.array([ np.cos(target_theta), np.sin(target_theta), 0 ]) super()._reset() @configurable(pickleable=True) class DKittyWalkRandom(BaseDKittyWalk): """Walk straight towards a random location.""" def __init__( self, *args, target_distance_range: Tuple[float, float] = (1.0, 2.0), # +/- 60deg target_angle_range: Tuple[float, float] = (-np.pi / 3, np.pi / 3), **kwargs): """Initializes the environment. Args: target_distance_range: The range in which to sample the target distance. target_angle_range: The range in which to sample the angle between the initial D'Kitty heading and the target. """ super().__init__(*args, **kwargs) self._target_distance_range = target_distance_range self._target_angle_range = target_angle_range def _reset(self): """Resets the environment.""" target_dist = self.np_random.uniform(*self._target_distance_range) # Offset the angle by 90deg since D'Kitty looks towards +y-axis. target_theta = np.pi / 2 + self.np_random.uniform( *self._target_angle_range) self._initial_target_pos = target_dist * np.array([ np.cos(target_theta), np.sin(target_theta), 0 ]) super()._reset() @configurable(pickleable=True) class DKittyWalkRandomDynamics(DKittyWalkRandom): """Walk straight towards a random location.""" def __init__(self, *args, sim_observation_noise: Optional[float] = 0.05, **kwargs): super().__init__( *args, sim_observation_noise=sim_observation_noise, **kwargs) self._randomizer = SimRandomizer(self) self._dof_indices = ( self.robot.get_config('dkitty').qvel_indices.tolist()) def _reset(self): """Resets the environment.""" # Randomize joint dynamics. self._randomizer.randomize_dofs( self._dof_indices, all_same=True, damping_range=(0.1, 0.2), friction_loss_range=(0.001, 0.005), ) self._randomizer.randomize_actuators( all_same=True, kp_range=(2.8, 3.2), ) # Randomize friction on all geoms in the scene. self._randomizer.randomize_geoms( all_same=True, friction_slide_range=(0.8, 1.2), friction_spin_range=(0.003, 0.007), friction_roll_range=(0.00005, 0.00015), ) # Generate a random height field. self._randomizer.randomize_global( total_mass_range=(1.6, 2.0), height_field_range=(0, 0.05), ) self.sim_scene.upload_height_field(0) super()._reset()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/dkitty/__init__.py
robel/dkitty/__init__.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Gym environment registration for DKitty environments.""" from robel.utils.registration import register #=============================================================================== # Stand tasks #=============================================================================== # Default number of steps per episode. _STAND_EPISODE_LEN = 80 # 80*40*2.5ms = 8s register( env_id='DKittyStandFixed-v0', class_path='robel.dkitty.stand:DKittyStandFixed', max_episode_steps=_STAND_EPISODE_LEN) register( env_id='DKittyStandRandom-v0', class_path='robel.dkitty.stand:DKittyStandRandom', max_episode_steps=_STAND_EPISODE_LEN) register( env_id='DKittyStandRandomDynamics-v0', class_path='robel.dkitty.stand:DKittyStandRandomDynamics', max_episode_steps=_STAND_EPISODE_LEN) #=============================================================================== # Orient tasks #=============================================================================== # Default number of steps per episode. _ORIENT_EPISODE_LEN = 80 # 80*40*2.5ms = 8s register( env_id='DKittyOrientFixed-v0', class_path='robel.dkitty.orient:DKittyOrientFixed', max_episode_steps=_ORIENT_EPISODE_LEN) register( env_id='DKittyOrientRandom-v0', class_path='robel.dkitty.orient:DKittyOrientRandom', max_episode_steps=_ORIENT_EPISODE_LEN) register( env_id='DKittyOrientRandomDynamics-v0', class_path='robel.dkitty.orient:DKittyOrientRandomDynamics', max_episode_steps=_ORIENT_EPISODE_LEN) #=============================================================================== # Walk tasks #=============================================================================== # Default number of steps per episode. _WALK_EPISODE_LEN = 160 # 160*40*2.5ms = 16s register( env_id='DKittyWalkFixed-v0', class_path='robel.dkitty.walk:DKittyWalkFixed', max_episode_steps=_WALK_EPISODE_LEN) register( env_id='DKittyWalkRandom-v0', class_path='robel.dkitty.walk:DKittyWalkRandom', max_episode_steps=_WALK_EPISODE_LEN) register( env_id='DKittyWalkRandomDynamics-v0', class_path='robel.dkitty.walk:DKittyWalkRandomDynamics', max_episode_steps=_WALK_EPISODE_LEN)
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/dkitty/orient_test.py
robel/dkitty/orient_test.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for DKitty walk tasks.""" from absl.testing import absltest from absl.testing import parameterized import gym import numpy as np from robel.dkitty.orient import (DKittyOrientFixed, DKittyOrientRandom, DKittyOrientRandomDynamics) # pylint: disable=no-member @parameterized.parameters( ('DKittyOrientFixed-v0', DKittyOrientFixed), ('DKittyOrientRandom-v0', DKittyOrientRandom), ('DKittyOrientRandomDynamics-v0', DKittyOrientRandomDynamics), ) class DKittyOrientTest(absltest.TestCase): """Unit test class for RobotEnv.""" def test_gym_make(self, env_id, env_cls): """Accesses the sim, model, and data properties.""" env = gym.make(env_id) self.assertIsInstance(env.unwrapped, env_cls) def test_spaces(self, _, env_cls): """Checks the observation, action, and state spaces.""" env = env_cls() observation_size = np.sum([ 3, # root_pos 3, # root_euler 12, # kitty_qpos 3, # root_vel 3, # root_angular_vel 12, # kitty_qvel 12, # last_action 1, # upright 2, # current_facing 2, # desired_facing ]) self.assertEqual(env.observation_space.shape, (observation_size,)) self.assertEqual(env.action_space.shape, (12,)) self.assertEqual(env.state_space['root_pos'].shape, (3,)) self.assertEqual(env.state_space['root_euler'].shape, (3,)) self.assertEqual(env.state_space['root_vel'].shape, (3,)) self.assertEqual(env.state_space['root_angular_vel'].shape, (3,)) self.assertEqual(env.state_space['kitty_qpos'].shape, (12,)) self.assertEqual(env.state_space['kitty_qvel'].shape, (12,)) def test_reset_step(self, _, env_cls): """Checks that resetting and stepping works.""" env = env_cls() env.reset() env.step(env.action_space.sample()) if __name__ == '__main__': absltest.main()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/dkitty/utils/manual_reset.py
robel/dkitty/utils/manual_reset.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Hardware reset functions for the D'Kitty.""" import time from robel.components.builder import ComponentBuilder from robel.components.robot import RobotComponentBuilder from robel.components.robot.dynamixel_robot import DynamixelRobotComponent from robel.components.tracking import TrackerComponentBuilder from robel.components.tracking.tracker import TrackerComponent from robel.utils.reset_procedure import ResetProcedure class ManualAutoDKittyResetProcedure(ResetProcedure): """Manual reset procedure for D'Kitty. This waits until the D'Kitty is placed upright and automatically starts the episode. """ def __init__(self, upright_threshold: float = 0.9, max_height: float = 0.35, min_successful_checks: int = 5, check_interval_sec: float = 0.1, print_interval_sec: float = 1.0, episode_start_delay_sec: float = 1.0): super().__init__() self._upright_threshold = upright_threshold self._max_height = max_height self._min_successful_checks = min_successful_checks self._check_interval_sec = check_interval_sec self._print_interval_sec = print_interval_sec self._episode_start_delay_sec = episode_start_delay_sec self._last_print_time = 0 self._robot = None self._tracker = None def configure_reset_groups(self, builder: ComponentBuilder): """Configures the component groups needed for reset.""" if isinstance(builder, RobotComponentBuilder): assert 'dkitty' in builder.group_configs elif isinstance(builder, TrackerComponentBuilder): assert 'torso' in builder.group_configs def reset(self, robot: DynamixelRobotComponent, tracker: TrackerComponent): """Performs the reset procedure.""" self._robot = robot self._tracker = tracker def finish(self): """Called when the reset is complete.""" # Wait until the robot is sufficiently upright. self._wait_until_upright() def _wait_until_upright(self): """Waits until the D'Kitty is upright.""" upright_checks = 0 self._last_print_time = 0 # Start at 0 so print happens first time. while True: if self._is_dkitty_upright(): upright_checks += 1 else: upright_checks = 0 if upright_checks > self._min_successful_checks: break time.sleep(self._check_interval_sec) print('Reset complete, starting episode...') time.sleep(self._episode_start_delay_sec) def _is_dkitty_upright(self) -> bool: """Checks if the D'Kitty is currently upright.""" state = self._tracker.get_state('torso') height = state.pos[2] upright = state.rot[2, 2] cur_time = time.time() if cur_time - self._last_print_time >= self._print_interval_sec: self._last_print_time = cur_time print(('Waiting for D\'Kitty to be upright (upright: {:.2f}, ' 'height: {:.2f})').format(upright, height)) if upright < self._upright_threshold: return False if height > self._max_height: return False return True
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/dkitty/utils/scripted_reset.py
robel/dkitty/utils/scripted_reset.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Hardware reset functions for the D'Kitty.""" import numpy as np from robel.components.builder import ComponentBuilder from robel.components.robot import RobotComponentBuilder, RobotState from robel.components.robot.dynamixel_robot import DynamixelRobotComponent from robel.components.tracking import TrackerComponentBuilder from robel.components.tracking.tracker import TrackerComponent from robel.utils.reset_procedure import ResetProcedure # Maximum values for each joint. BASEMAX = .8 MIDMAX = 2.4 FOOTMAX = 2.5 # Common parameters for all `set_state` commands. SET_PARAMS = dict( error_tol=5 * np.pi / 180, # 5 degrees last_diff_tol=.1 * np.pi / 180, # 5 degrees ) # Convenience constants. PI = np.pi PI2 = np.pi / 2 PI4 = np.pi / 4 PI6 = np.pi / 6 OUTWARD_TUCK_POSE = np.array([0, -MIDMAX, FOOTMAX, 0, MIDMAX, -FOOTMAX]) INWARD_TUCK_POSE = np.array([0, MIDMAX, -FOOTMAX, 0, -MIDMAX, FOOTMAX]) class ScriptedDKittyResetProcedure(ResetProcedure): """Scripted reset procedure for D'Kitty. This resets the D'Kitty to a standing position. """ def __init__(self, upright_threshold: float = 0.9, standing_height: float = 0.35, height_tolerance: float = 0.05, max_attempts: int = 5): super().__init__() self._upright_threshold = upright_threshold self._standing_height = standing_height self._height_tolerance = height_tolerance self._max_attempts = max_attempts self._robot = None self._tracker = None def configure_reset_groups(self, builder: ComponentBuilder): """Configures the component groups needed for reset.""" if isinstance(builder, RobotComponentBuilder): builder.add_group('left', motor_ids=[20, 21, 22, 30, 31, 32]) builder.add_group('right', motor_ids=[10, 11, 12, 40, 41, 42]) builder.add_group('front', motor_ids=[10, 11, 12, 20, 21, 22]) builder.add_group('back', motor_ids=[30, 31, 32, 40, 41, 42]) elif isinstance(builder, TrackerComponentBuilder): assert 'torso' in builder.group_configs def reset(self, robot: DynamixelRobotComponent, tracker: TrackerComponent): """Performs the reset procedure.""" self._robot = robot self._tracker = tracker attempts = 0 while not self._is_standing(): attempts += 1 if attempts > self._max_attempts: break if self._is_upside_down(): self._perform_flip_over() self._perform_tuck_under() self._perform_stand_up() def _is_standing(self) -> bool: """Returns True if the D'Kitty is fully standing.""" state = self._tracker.get_state('torso', raw_states=True) height = state.pos[2] upright = state.rot[2, 2] print('Upright: {:2f}, height: {:2f}'.format(upright, height)) if upright < self._upright_threshold: return False if (np.abs(height - self._standing_height) > self._height_tolerance): return False return True def _get_uprightedness(self) -> float: """Returns the uprightedness of the D'Kitty.""" return self._tracker.get_state('torso', raw_states=True).rot[2, 2] def _is_upside_down(self) -> bool: """Returns whether the D'Kitty is upside-down.""" return self._get_uprightedness() < 0 def _perform_flip_over(self): """Attempts to flip the D'Kitty over.""" while self._is_upside_down(): print('Is upside down {}; attempting to flip over...'.format( self._get_uprightedness())) # Spread flat and extended. self._perform_flatten() # If we somehow flipped over from that, we're done. if not self._is_upside_down(): return # Tuck in one side while pushing down on the other side. self._robot.set_state( { 'left': RobotState(qpos=np.array([-PI4, -MIDMAX, FOOTMAX] * 2)), 'right': RobotState(qpos=np.array([-PI - PI4, 0, 0] * 2)), }, timeout=4, **SET_PARAMS, ) # Straighten out the legs that were pushing down. self._robot.set_state( { 'left': RobotState(qpos=np.array([PI2, 0, 0] * 2)), 'right': RobotState(qpos=np.array([-PI2, 0, 0] * 2)), }, timeout=4, **SET_PARAMS, ) def _perform_tuck_under(self): """Tucks the D'Kitty's legs so that they're under itself.""" # Bring in both sides of the D'Kitty while remaining flat. self._perform_flatten() # Tuck one side at a time. for side in ('left', 'right'): self._robot.set_state( {side: RobotState(qpos=np.array(INWARD_TUCK_POSE))}, timeout=4, **SET_PARAMS, ) def _perform_flatten(self): """Makes the D'Kitty go into a flat pose.""" left_pose = INWARD_TUCK_POSE.copy() left_pose[[0, 3]] = PI2 right_pose = INWARD_TUCK_POSE.copy() right_pose[[0, 3]] = -PI2 self._robot.set_state( { 'left': RobotState(qpos=left_pose), 'right': RobotState(qpos=right_pose), }, timeout=4, **SET_PARAMS, ) def _perform_stand_up(self): """Makes the D'Kitty stand up.""" # Flip the back and front. self._robot.set_state( { 'back': RobotState( qpos=np.array(OUTWARD_TUCK_POSE[3:].tolist() * 2)), }, timeout=4, **SET_PARAMS, ) self._robot.set_state( { 'front': RobotState( qpos=np.array(OUTWARD_TUCK_POSE[:3].tolist() * 2)), }, timeout=4, **SET_PARAMS, ) # Stand straight up. self._robot.set_state( { 'dkitty': RobotState(qpos=np.zeros(12)), }, timeout=3, **SET_PARAMS, ) # Tuck a bit. self._robot.set_state( { 'dkitty': RobotState(qpos=np.array([0, PI6, -PI6] * 4)), }, timeout=1, **SET_PARAMS, ) # Stand straight up. self._robot.set_state( { 'dkitty': RobotState(qpos=np.zeros(12)), }, timeout=3, **SET_PARAMS, )
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/dkitty/utils/__init__.py
robel/dkitty/utils/__init__.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/simulation/mjpy_sim_scene.py
robel/simulation/mjpy_sim_scene.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Simulation using DeepMind Control Suite.""" import logging import os from typing import Any import mujoco_py from mujoco_py.builder import cymj, user_warning_raise_exception from robel.simulation.mjpy_renderer import MjPyRenderer from robel.simulation.sim_scene import SimScene # Custom handler for MuJoCo exceptions. def _mj_warning_fn(warn_data: bytes): """Warning function override for mujoco_py.""" try: user_warning_raise_exception(warn_data) except mujoco_py.MujocoException as e: logging.error('MuJoCo Exception: %s', str(e)) cymj.set_warning_callback(_mj_warning_fn) class MjPySimScene(SimScene): """Encapsulates a MuJoCo robotics simulation using mujoco_py.""" def _load_simulation(self, model_handle: Any) -> Any: """Loads the simulation from the given model handle. Args: model_handle: Path to the Mujoco XML file to load. Returns: A mujoco_py MjSim object. """ if isinstance(model_handle, str): if not os.path.isfile(model_handle): raise ValueError( '[MjPySimScene] Invalid model file path: {}'.format( model_handle)) model = mujoco_py.load_model_from_path(model_handle) sim = mujoco_py.MjSim(model) else: raise NotImplementedError(model_handle) return sim def _create_renderer(self, sim: Any) -> MjPyRenderer: """Creates a renderer for the given simulation.""" return MjPyRenderer(sim) def copy_model(self) -> Any: """Returns a copy of the MjModel object.""" null_model = self.get_mjlib().PyMjModel() model_copy = self.get_mjlib().mj_copyModel(null_model, self.model) return model_copy def save_binary(self, path: str) -> str: """Saves the loaded model to a binary .mjb file. Returns: The file path that the binary was saved to. """ if not path.endswith('.mjb'): path = path + '.mjb' self.get_mjlib().mj_saveModel(self.model, path.encode(), None, 0) return path def upload_height_field(self, hfield_id: int): """Uploads the height field to the rendering context.""" if not self.sim.render_contexts: logging.warning('No rendering context; not uploading height field.') return self.get_mjlib().mjr_uploadHField( self.model, self.sim.render_contexts[0].con, hfield_id) def get_mjlib(self) -> Any: """Returns an interface to the low-level MuJoCo API.""" return _MjlibWrapper(mujoco_py.cymj) def get_handle(self, value: Any) -> Any: """Returns a handle that can be passed to mjlib methods.""" return value class _MjlibWrapper: """Wrapper that forwards mjlib calls.""" def __init__(self, lib): self._lib = lib def __getattr__(self, name: str): if name.startswith('mj'): return getattr(self._lib, '_' + name) return getattr(self._lib, name)
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/simulation/sim_scene.py
robel/simulation/sim_scene.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Simulated robot API backed by MuJoCo.""" import abc import contextlib import enum from typing import Any, Union from robel.simulation.renderer import Renderer class SimBackend(enum.Enum): """Simulation library types.""" MUJOCO_PY = 0 DM_CONTROL = 1 class SimScene(metaclass=abc.ABCMeta): """Encapsulates a MuJoCo robotics simulation.""" @staticmethod def create(*args, backend: Union[SimBackend, int], **kwargs) -> 'SimScene': """Creates a new simulation scene. Args: *args: Positional arguments to pass to the simulation. backend: The simulation backend to use to load the simulation. **kwargs: Keyword arguments to pass to the simulation. Returns: A SimScene object. """ backend = SimBackend(backend) if backend == SimBackend.MUJOCO_PY: from robel.simulation import mjpy_sim_scene # type: ignore return mjpy_sim_scene.MjPySimScene(*args, **kwargs) elif backend == SimBackend.DM_CONTROL: from robel.simulation import dm_sim_scene # type: ignore return dm_sim_scene.DMSimScene(*args, **kwargs) else: raise NotImplementedError(backend) def __init__( self, model_handle: Any, frame_skip: int = 1, ): """Initializes a new simulation. Args: model_handle: The simulation model to load. This can be a XML file, or a format/object specific to the simulation backend. frame_skip: The number of simulation steps per environment step. This multiplied by the timestep defined in the model file is the step duration. """ self.frame_skip = frame_skip self.sim = self._load_simulation(model_handle) self.model = self.sim.model self.data = self.sim.data self.renderer = self._create_renderer(self.sim) # Save initial values. self.init_qpos = self.data.qpos.ravel().copy() self.init_qvel = self.data.qvel.ravel().copy() @property def step_duration(self): """Returns the simulation step duration in seconds.""" return self.model.opt.timestep * self.frame_skip def close(self): """Cleans up any resources used by the simulation.""" self.renderer.close() def advance(self, substeps: int = None): """Advances the simulation for one step.""" # Step the simulation `frame_skip` times. if substeps is None: substeps = self.frame_skip for _ in range(substeps): self.sim.step() self.renderer.refresh_window() def disable_option(self, constraint_solver: bool = False, limits: bool = False, contact: bool = False, gravity: bool = False, clamp_ctrl: bool = False, actuation: bool = False): """Disables option(s) in the simulation.""" # http://www.mujoco.org/book/APIreference.html#mjtDisableBit if constraint_solver: self.model.opt.disableflags |= (1 << 0) if limits: self.model.opt.disableflags |= (1 << 3) if contact: self.model.opt.disableflags |= (1 << 4) if gravity: self.model.opt.disableflags |= (1 << 6) if clamp_ctrl: self.model.opt.disableflags |= (1 << 7) if actuation: self.model.opt.disableflags |= (1 << 10) @contextlib.contextmanager def disable_option_context(self, **kwargs): """Disables options(s) in the simulation for the context.""" original_flags = self.model.opt.disableflags self.disable_option(**kwargs) yield self.model.opt.disableflags = original_flags @abc.abstractmethod def copy_model(self) -> Any: """Returns a copy of the MjModel object.""" @abc.abstractmethod def save_binary(self, path: str) -> str: """Saves the loaded model to a binary .mjb file. Returns: The file path that the binary was saved to. """ @abc.abstractmethod def upload_height_field(self, hfield_id: int): """Uploads the height field to the rendering context.""" @abc.abstractmethod def get_handle(self, value: Any) -> Any: """Returns a handle that can be passed to mjlib methods.""" @abc.abstractmethod def get_mjlib(self) -> Any: """Returns an interface to the low-level MuJoCo API.""" @abc.abstractmethod def _load_simulation(self, model_handle: Any) -> Any: """Loads the simulation from the given model handle.""" @abc.abstractmethod def _create_renderer(self, sim: Any) -> Renderer: """Creates a renderer for the given simulation."""
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/simulation/mjpy_renderer.py
robel/simulation/mjpy_renderer.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Rendering simulation using mujoco_py.""" import mujoco_py import numpy as np from robel.simulation.renderer import Renderer, RenderMode class MjPyRenderer(Renderer): """Class for rendering mujoco_py simulations.""" def __init__(self, sim): assert isinstance(sim, mujoco_py.MjSim), \ 'MjPyRenderer takes a mujoco_py MjSim object.' super().__init__(sim) self._onscreen_renderer = None self._offscreen_renderer = None def render_to_window(self): """Renders the simulation to a window.""" if not self._onscreen_renderer: self._onscreen_renderer = mujoco_py.MjViewer(self._sim) self._update_camera_properties(self._onscreen_renderer.cam) self._onscreen_renderer.render() def refresh_window(self): """Refreshes the rendered window if one is present.""" if self._onscreen_renderer is None: return self._onscreen_renderer.render() def render_offscreen(self, width: int, height: int, mode: RenderMode = RenderMode.RGB, camera_id: int = -1) -> np.ndarray: """Renders the camera view as a numpy array of pixels. Args: width: The viewport width (pixels). height: The viewport height (pixels). mode: The rendering mode. camera_id: The ID of the camera to render from. By default, uses the free camera. Returns: A numpy array of the pixels. """ assert width > 0 and height > 0 if not self._offscreen_renderer: self._offscreen_renderer = mujoco_py \ .MjRenderContextOffscreen(self._sim, device_id=-1) # Update the camera configuration for the free-camera. if camera_id == -1: self._update_camera_properties(self._offscreen_renderer.cam) self._offscreen_renderer.render(width, height, camera_id) if mode == RenderMode.RGB: data = self._offscreen_renderer.read_pixels( width, height, depth=False) # Original image is upside-down, so flip it return data[::-1, :, :] elif mode == RenderMode.DEPTH: data = self._offscreen_renderer.read_pixels( width, height, depth=True)[1] # Original image is upside-down, so flip it return data[::-1, :] else: raise NotImplementedError(mode)
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/simulation/randomize.py
robel/simulation/randomize.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Domain-randomization for simulations.""" from typing import Iterable, Optional, Sequence, Tuple, Union import numpy as np from robel.robot_env import RobotEnv # Define types. Bound = Union[float, Sequence[float]] Range = Tuple[Bound, Bound] class SimRandomizer: """Randomizes simulation properties.""" def __init__(self, env: RobotEnv): """Initializes a new randomizer. Args: env: The environment to randomize. """ self.env = env self.sim_scene = env.sim_scene self.model = self.sim_scene.model self.orig_model = self.sim_scene.copy_model() @property def rand(self) -> np.random.RandomState: """Returns the random state.""" return self.env.np_random def randomize_global(self, total_mass_range: Optional[Range] = None, height_field_range: Optional[Range] = None): """Randomizes global options in the scene. Args: total_mass_range: A range of mass values to which all bodies and inertias should be scaled to achieve. height_field_range: A range of values to generate a noise map for the height field. """ if total_mass_range is not None: self.sim_scene.get_mjlib().mj_setTotalmass( self.sim_scene.get_handle(self.model), self.rand.uniform(*total_mass_range)) if height_field_range is not None: self.model.hfield_data[:] = self.rand.uniform( *height_field_range, size=np.shape(self.model.hfield_data)) def randomize_bodies(self, names: Optional[Iterable[str]] = None, all_same: bool = False, position_perturb_range: Optional[Range] = None): """Randomizes the bodies in the scene. Args: names: The body names to randomize. If this is not provided, all bodies are randomized. all_same: If True, the bodies are assigned the same random value. position_perturb_range: A range to perturb the position of the body relative to its original position. """ if names is None: body_ids = list(range(self.model.nbody)) else: body_ids = [self.model.body_name2id(name) for name in names] body_ids = sorted(set(body_ids)) num_bodies = len(body_ids) # Randomize the position relative to the original position. if position_perturb_range is not None: original_pos = self.orig_model.body_pos[body_ids] self.model.body_pos[body_ids] = original_pos + self.rand.uniform( *position_perturb_range, size=(3,) if all_same else (num_bodies, 3)) def randomize_geoms(self, names: Optional[Iterable[str]] = None, parent_body_names: Optional[Iterable[str]] = None, all_same: bool = False, size_perturb_range: Optional[Range] = None, color_range: Optional[Range] = None, friction_slide_range: Optional[Range] = None, friction_spin_range: Optional[Range] = None, friction_roll_range: Optional[Range] = None): """Randomizes the geoms in the scene. Args: names: The geom names to randomize. If this nor `parent_body_names` is provided, all geoms are randomized. parent_body_names: A list of body names whose child geoms should be randomized. all_same: If True, the geoms are assigned the same random value. size_perturb_range: A range to perturb the size of the geom relative to its original size. color_range: A color range to assign an RGB color to the geom. friction_slide_range: The sliding friction that acts along both axes of the tangent plane. friction_spin_range: The torsional friction acting around the contact normal. friction_roll_range: The rolling friction acting around both axes of the tangent plane. """ if names is None and parent_body_names is None: # Address all geoms if no names are given. geom_ids = list(range(self.model.ngeom)) else: geom_ids = [] if names is not None: geom_ids.extend(self.model.geom_name2id(name) for name in names) # Add child geoms of parent bodies. if parent_body_names is not None: for name in parent_body_names: body_id = self.model.body_name2id(name) geom_id_start = self.model.body_geomadr[body_id] for i in range(self.model.body_geomnum[body_id]): geom_ids.append(geom_id_start + i) geom_ids = sorted(set(geom_ids)) num_geoms = len(geom_ids) # Randomize the size of the geoms relative to the original size. if size_perturb_range is not None: original_size = self.orig_model.geom_size[geom_ids] self.model.geom_size[geom_ids] = original_size + self.rand.uniform( *size_perturb_range, size=(3,) if all_same else (num_geoms, 3)) # Randomize the color of the geoms. if color_range is not None: self.model.geom_rgba[geom_ids, :3] = self.rand.uniform( *color_range, size=(3,) if all_same else (num_geoms, 3)) # Randomize the friction parameters. if friction_slide_range is not None: self.model.geom_friction[geom_ids, 0] = self.rand.uniform( *friction_slide_range, size=1 if all_same else num_geoms) if friction_spin_range is not None: self.model.geom_friction[geom_ids, 1] = self.rand.uniform( *friction_spin_range, size=1 if all_same else num_geoms) if friction_roll_range is not None: self.model.geom_friction[geom_ids, 2] = self.rand.uniform( *friction_roll_range, size=1 if all_same else num_geoms) def randomize_dofs(self, indices: Optional[Iterable[int]] = None, all_same: bool = False, damping_range: Optional[Range] = None, friction_loss_range: Optional[Range] = None): """Randomizes the DoFs in the scene. Args: indices: The DoF indices to randomize. If not provided, randomizes all DoFs. all_same: If True, the DoFs are assigned the same random value. damping_range: The range to assign a damping for the DoF. friction_loss_range: The range to assign a friction loss for the DoF. """ if indices is None: dof_ids = list(range(self.model.nv)) else: nv = self.model.nv assert all(-nv <= i < nv for i in indices), \ 'All DoF indices must be in [-{}, {}]'.format(nv, nv-1) dof_ids = sorted(set(indices)) num_dofs = len(dof_ids) # Randomize the damping for each DoF. if damping_range is not None: self.model.dof_damping[dof_ids] = self.rand.uniform( *damping_range, size=1 if all_same else num_dofs) # Randomize the friction loss for each DoF. if friction_loss_range is not None: self.model.dof_frictionloss[dof_ids] = self.rand.uniform( *friction_loss_range, size=1 if all_same else num_dofs) def randomize_actuators(self, indices: Optional[Iterable[int]] = None, all_same: bool = False, kp_range: Optional[Range] = None, kv_range: Optional[Range] = None): """Randomizes the actuators in the scene. Args: indices: The actuator indices to randomize. If not provided, randomizes all actuators. all_same: If True, the actuators are assigned the same random value. kp_range: The position feedback gain range for the actuators. This assumes position control actuators. kv_range: The velocity feedback gain range for the actuators. This assumes velocity control actuators. """ if indices is None: act_ids = list(range(self.model.nu)) else: nu = self.model.nu assert all(-nu <= i < nu for i in indices), \ 'All actuator indices must be in [-{}, {}]'.format(nu, nu-1) act_ids = sorted(set(indices)) num_acts = len(act_ids) # NOTE: For the values below, refer to: # http://mujoco.org/book/XMLreference.html#actuator # Randomize the Kp for each actuator. if kp_range is not None: kp = self.rand.uniform(*kp_range, size=1 if all_same else num_acts) self.model.actuator_gainprm[:, 0] = kp self.model.actuator_biasprm[:, 1] = -kp # Randomize the Kv for each actuator. if kv_range is not None: kv = self.rand.uniform(*kv_range, size=1 if all_same else num_acts) self.model.actuator_gainprm[:, 0] = kv self.model.actuator_biasprm[:, 2] = -kv
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/simulation/dm_renderer.py
robel/simulation/dm_renderer.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Rendering simulation using dm_control.""" import sys import numpy as np import dm_control.mujoco as dm_mujoco import dm_control.viewer as dm_viewer import dm_control._render as dm_render from robel.simulation.renderer import Renderer, RenderMode # Default window dimensions. DEFAULT_WINDOW_WIDTH = 640 DEFAULT_WINDOW_HEIGHT = 480 # Default window title. DEFAULT_WINDOW_TITLE = 'MuJoCo Viewer' # Internal renderbuffer size, in pixels. _MAX_RENDERBUFFER_SIZE = 2048 class DMRenderer(Renderer): """Renders DM Control Physics objects.""" def __init__(self, sim: dm_mujoco.Physics): super().__init__(sim) self._window = None def render_to_window(self): """Renders the Physics object to a window. The window continuously renders the Physics in a separate thread. This function is a no-op if the window was already created. """ if not self._window: self._window = DMRenderWindow() self._window.load_model(self._sim) self._update_camera_properties(self._window.camera) self._window.run_frame() def refresh_window(self): """Refreshes the rendered window if one is present.""" if self._window is None: return self._window.run_frame() def render_offscreen(self, width: int, height: int, mode: RenderMode = RenderMode.RGB, camera_id: int = -1) -> np.ndarray: """Renders the camera view as a numpy array of pixels. Args: width: The viewport width (pixels). height: The viewport height (pixels). mode: The rendering mode. camera_id: The ID of the camera to render from. By default, uses the free camera. Returns: A numpy array of the pixels. """ assert width > 0 and height > 0 # TODO(michaelahn): Consider caching the camera. camera = dm_mujoco.Camera( physics=self._sim, height=height, width=width, camera_id=camera_id) # Update the camera configuration for the free-camera. if camera_id == -1: self._update_camera_properties(camera._render_camera) # pylint: disable=protected-access image = camera.render( depth=(mode == RenderMode.DEPTH), segmentation=(mode == RenderMode.SEGMENTATION)) camera._scene.free() # pylint: disable=protected-access return image def close(self): """Cleans up any resources being used by the renderer.""" if self._window: self._window.close() self._window = None class DMRenderWindow: """Class that encapsulates a graphical window.""" def __init__(self, width: int = DEFAULT_WINDOW_WIDTH, height: int = DEFAULT_WINDOW_HEIGHT, title: str = DEFAULT_WINDOW_TITLE): """Creates a graphical render window. Args: width: The width of the window. height: The height of the window. title: The title of the window. """ self._viewport = dm_viewer.renderer.Viewport(width, height) self._window = dm_viewer.gui.RenderWindow(width, height, title) self._viewer = dm_viewer.viewer.Viewer( self._viewport, self._window.mouse, self._window.keyboard) self._draw_surface = None self._renderer = dm_viewer.renderer.NullRenderer() @property def camera(self): return self._viewer._camera._camera # pylint: disable=protected-access def close(self): self._viewer.deinitialize() self._renderer.release() self._draw_surface.free() self._window.close() def load_model(self, physics): """Loads the given Physics object to render.""" self._viewer.deinitialize() self._draw_surface = dm_render.Renderer( max_width=_MAX_RENDERBUFFER_SIZE, max_height=_MAX_RENDERBUFFER_SIZE) self._renderer = dm_viewer.renderer.OffScreenRenderer( physics.model, self._draw_surface) self._viewer.initialize(physics, self._renderer, touchpad=False) def run_frame(self): """Renders one frame of the simulation. NOTE: This is extremely slow at the moment. """ # pylint: disable=protected-access glfw = dm_viewer.gui.glfw_gui.glfw glfw_window = self._window._context.window if glfw.window_should_close(glfw_window): sys.exit(0) self._viewport.set_size(*self._window.shape) self._viewer.render() pixels = self._renderer.pixels with self._window._context.make_current() as ctx: ctx.call(self._window._update_gui_on_render_thread, glfw_window, pixels) self._window._mouse.process_events() self._window._keyboard.process_events() # pylint: enable=protected-access
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/simulation/sim_scene_test.py
robel/simulation/sim_scene_test.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for SimScene.""" import contextlib import tempfile from typing import Generator from absl.testing import absltest from robel.simulation.sim_scene import SimBackend, SimScene # Simple MuJoCo model XML. TEST_MODEL_XML = """ <mujoco model="test"> <compiler coordinate="global"/> <worldbody> <light pos="0 1 1" dir="0 -1 -1" diffuse="1 1 1"/> <body name="main"> <geom name="base" type="capsule" fromto="0 0 1 0 0 0.6" size="0.06"/> <body> <geom type="capsule" fromto="0 0 0.6 0.3 0 0.6" size="0.04"/> <joint name="j1" type="hinge" pos="0 0 0.6" axis="0 1 0"/> <joint name="j2" type="hinge" pos="0 0 0.6" axis="1 0 0"/> <body> <geom type="ellipsoid" pos="0.4 0 0.6" size="0.1 0.08 0.02"/> <site name="end" pos="0.5 0 0.6" type="sphere" size="0.01"/> <joint type="hinge" pos="0.3 0 0.6" axis="0 1 0"/> <joint type="hinge" pos="0.3 0 0.6" axis="0 0 1"/> </body> </body> </body> </worldbody> </mujoco> """ @contextlib.contextmanager def test_model_file() -> Generator[str, None, None]: """Context manager that yields a temporary MuJoCo XML file.""" with tempfile.NamedTemporaryFile(mode='w+t', suffix='.xml') as f: f.write(TEST_MODEL_XML) f.flush() f.seek(0) yield f.name def mjpy_and_dm(fn): """Decorator that tests for both mujoco_py and dm_control.""" def test_fn(self: absltest.TestCase): with test_model_file() as test_file_path: with self.subTest('mujoco_py'): fn( self, SimScene.create( test_file_path, backend=SimBackend.MUJOCO_PY)) with self.subTest('dm_control'): fn( self, SimScene.create( test_file_path, backend=SimBackend.DM_CONTROL)) return test_fn class SimSceneTest(absltest.TestCase): """Unit test class for SimScene.""" @mjpy_and_dm def test_load(self, robot: SimScene): self.assertIsNotNone(robot.sim) self.assertIsNotNone(robot.model) self.assertIsNotNone(robot.data) @mjpy_and_dm def test_step(self, robot: SimScene): robot.sim.reset() robot.sim.forward() robot.sim.step() @mjpy_and_dm def test_accessors(self, robot: SimScene): self.assertTrue(robot.model.body_name2id('main') >= 0) self.assertTrue(robot.model.geom_name2id('base') >= 0) self.assertTrue(robot.model.site_name2id('end') >= 0) self.assertTrue(robot.model.joint_name2id('j1') >= 0) self.assertIsNotNone(robot.data.body_xpos[0]) self.assertIsNotNone(robot.data.body_xquat[0]) @mjpy_and_dm def test_copy_model(self, robot: SimScene): initial_pos = robot.model.body_pos[0].copy().tolist() model_copy = robot.copy_model() robot.model.body_pos[0, :] = [0.1, 0.2, 0.3] self.assertListEqual(model_copy.body_pos[0].tolist(), initial_pos) self.assertListEqual(robot.model.body_pos[0].tolist(), [0.1, 0.2, 0.3]) if __name__ == '__main__': absltest.main()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/simulation/__init__.py
robel/simulation/__init__.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/simulation/renderer.py
robel/simulation/renderer.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Rendering API for MuJoCo simulations.""" import abc import enum from typing import Any, Optional, Sequence import numpy as np class RenderMode(enum.Enum): """Rendering modes for offscreen rendering.""" RGB = 0 DEPTH = 1 SEGMENTATION = 2 class Renderer(abc.ABC): """Base interface for rendering simulations.""" def __init__(self, sim): """Initializes a new renderer. Args: sim: A handle to the simulation. """ self._sim = sim self._camera_settings = {} @abc.abstractmethod def render_to_window(self): """Renders the simulation to a window.""" @abc.abstractmethod def refresh_window(self): """Refreshes the rendered window if one is present.""" @abc.abstractmethod def render_offscreen(self, width: int, height: int, mode: RenderMode = RenderMode.RGB, camera_id: int = -1) -> np.ndarray: """Renders the camera view as a numpy array of pixels. Args: width: The viewport width (pixels). height: The viewport height (pixels). mode: The rendering mode. camera_id: The ID of the camera to render from. By default, uses the free camera. Returns: A numpy array of the pixels. """ def set_free_camera_settings( self, distance: Optional[float] = None, azimuth: Optional[float] = None, elevation: Optional[float] = None, lookat: Sequence[float] = None, center: bool = True, ): """Sets the free camera parameters. Args: distance: The distance of the camera from the target. azimuth: Horizontal angle of the camera, in degrees. elevation: Vertical angle of the camera, in degrees. lookat: The (x, y, z) position in world coordinates to target. center: If True and `lookat` is not given, targets the camera at the median position of the simulation geometry. """ settings = {} if distance is not None: settings['distance'] = distance if azimuth is not None: settings['azimuth'] = azimuth if elevation is not None: settings['elevation'] = elevation if lookat is not None: settings['lookat'] = np.array(lookat, dtype=np.float32) elif center: # Calculate the center of the simulation geometry. settings['lookat'] = np.array( [np.median(self._sim.data.geom_xpos[:, i]) for i in range(3)], dtype=np.float32) self._camera_settings = settings def close(self): """Cleans up any resources being used by the renderer.""" def _update_camera_properties(self, camera: Any): """Updates the given camera object with the current camera settings.""" for key, value in self._camera_settings.items(): if key == 'lookat': getattr(camera, key)[:] = value else: setattr(camera, key, value) def __del__(self): """Automatically clean up when out of scope.""" self.close()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/simulation/dm_sim_scene.py
robel/simulation/dm_sim_scene.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Simulation using DeepMind Control Suite.""" import copy import logging from typing import Any import dm_control.mujoco as dm_mujoco from robel.simulation.dm_renderer import DMRenderer from robel.simulation.sim_scene import SimScene class DMSimScene(SimScene): """Encapsulates a MuJoCo robotics simulation using dm_control.""" def _load_simulation(self, model_handle: Any) -> Any: """Loads the simulation from the given model handle. Args: model_handle: This can be a path to a Mujoco XML file, or an MJCF object. Returns: A dm_control Physics object. """ if isinstance(model_handle, str): if model_handle.endswith('.xml'): sim = dm_mujoco.Physics.from_xml_path(model_handle) else: sim = dm_mujoco.Physics.from_binary_path(model_handle) else: raise NotImplementedError(model_handle) self._patch_mjmodel_accessors(sim.model) self._patch_mjdata_accessors(sim.data) return sim def _create_renderer(self, sim: Any) -> DMRenderer: """Creates a renderer for the given simulation.""" return DMRenderer(sim) def copy_model(self) -> Any: """Returns a copy of the MjModel object.""" # dm_control's MjModel defines __copy__. model_copy = copy.copy(self.model) self._patch_mjmodel_accessors(model_copy) return model_copy def save_binary(self, path: str) -> str: """Saves the loaded model to a binary .mjb file. Returns: The file path that the binary was saved to. """ if not path.endswith('.mjb'): path = path + '.mjb' self.model.save_binary(path) return path def upload_height_field(self, hfield_id: int): """Uploads the height field to the rendering context.""" if not self.sim.contexts: logging.warning('No rendering context; not uploading height field.') return with self.sim.contexts.gl.make_current() as ctx: ctx.call(self.get_mjlib().mjr_uploadHField, self.model.ptr, self.sim.contexts.mujoco.ptr, hfield_id) def get_mjlib(self) -> Any: """Returns an interface to the low-level MuJoCo API.""" return dm_mujoco.wrapper.mjbindings.mjlib def get_handle(self, value: Any) -> Any: """Returns a handle that can be passed to mjlib methods.""" return value.ptr def _patch_mjmodel_accessors(self, model): """Adds accessors to MjModel objects to support mujoco_py API. This adds `*_name2id` methods to a Physics object to have API consistency with mujoco_py. TODO(michaelahn): Deprecate this in favor of dm_control's named methods. """ mjlib = self.get_mjlib() def name2id(type_name, name): obj_id = mjlib.mj_name2id(model.ptr, mjlib.mju_str2Type(type_name.encode()), name.encode()) if obj_id < 0: raise ValueError('No {} with name "{}" exists.'.format( type_name, name)) return obj_id if not hasattr(model, 'body_name2id'): model.body_name2id = lambda name: name2id('body', name) if not hasattr(model, 'geom_name2id'): model.geom_name2id = lambda name: name2id('geom', name) if not hasattr(model, 'site_name2id'): model.site_name2id = lambda name: name2id('site', name) if not hasattr(model, 'joint_name2id'): model.joint_name2id = lambda name: name2id('joint', name) if not hasattr(model, 'actuator_name2id'): model.actuator_name2id = lambda name: name2id('actuator', name) if not hasattr(model, 'camera_name2id'): model.camera_name2id = lambda name: name2id('camera', name) def _patch_mjdata_accessors(self, data): """Adds accessors to MjData objects to support mujoco_py API.""" if not hasattr(data, 'body_xpos'): data.body_xpos = data.xpos if not hasattr(data, 'body_xquat'): data.body_xquat = data.xquat
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/builder_test.py
robel/components/builder_test.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for ComponentBuilder.""" from absl.testing import absltest from robel.components.builder import ComponentBuilder class DummyBuilder(ComponentBuilder): """Mock component for testing ComponentBuilder.""" def build(self, *args, **kwargs): """Builds the component.""" class ComponentBuilderTest(absltest.TestCase): """Unit test class for ComponentBuilder.""" def test_add_group(self): """Tests adding a group.""" builder = DummyBuilder() builder.add_group('test', a=1, b=2) self.assertDictEqual(builder.group_configs, {'test': dict(a=1, b=2)}) self.assertListEqual(builder.group_names, ['test']) def test_add_multiple_groups(self): """Tests adding multiple groups.""" builder = DummyBuilder() builder.add_group('test1', a=1, b=2) builder.add_group('test2', b=2, c=3) self.assertDictEqual(builder.group_configs, { 'test1': dict(a=1, b=2), 'test2': dict(b=2, c=3), }) self.assertListEqual(builder.group_names, ['test1', 'test2']) def test_add_group_conflict(self): """Tests adding a duplicate group.""" builder = DummyBuilder() builder.add_group('test') with self.assertRaises(ValueError): builder.add_group('test') self.assertListEqual(builder.group_names, ['test']) def test_update_group(self): """Tests updating an existing group.""" builder = DummyBuilder() builder.add_group('test', a=1, b=2) builder.update_group('test', b=3, c=4) self.assertDictEqual(builder.group_configs, {'test': dict(a=1, b=3, c=4)}) def test_update_nonexistent_group(self): """Tests updating an non-existing group.""" builder = DummyBuilder() builder.add_group('test', a=1, b=2) with self.assertRaises(ValueError): builder.update_group('nottest', b=3, c=4) self.assertDictEqual(builder.group_configs, {'test': dict(a=1, b=2)}) if __name__ == '__main__': absltest.main()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/base_test.py
robel/components/base_test.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for BaseComponent.""" from typing import Any from absl.testing import absltest from robel.components.base import BaseComponent from robel.utils.testing.mock_sim_scene import MockSimScene class DummyComponent(BaseComponent): """Mock component for testing BaseComponent.""" def __init__(self, **kwargs): sim_scene = MockSimScene(nq=1) # type: Any super().__init__(sim_scene=sim_scene, **kwargs) def _process_group(self, **config_kwargs): return {} def _get_group_states(self, configs): return [0 for group in configs] class BaseComponentTest(absltest.TestCase): """Unit test class for BaseComponent.""" def test_get_state(self): """Tests retrieving state from a single group.""" component = DummyComponent(groups={'foo': {}}) state = component.get_state('foo') self.assertEqual(state, 0) def test_get_states(self): """Tests retrieving state from multiple groups.""" component = DummyComponent(groups={'foo': {}, 'bar': {}}) foo_state, bar_state = component.get_state(['foo', 'bar']) self.assertEqual(foo_state, 0) self.assertEqual(bar_state, 0) if __name__ == '__main__': absltest.main()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/__init__.py
robel/components/__init__.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/base.py
robel/components/base.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Base API for Components. A Component provides a unified API between simulation and hardware. """ import abc import logging import sys from typing import Any, Dict, Optional, Sequence, Union import numpy as np from robel.simulation.sim_scene import SimScene # Type definition for a group configuration. GroupConfig = Any # pylint: disable=invalid-name GroupState = Any # pylint: disable=invalid-name class BaseComponent(abc.ABC): """Base class for all components.""" def __init__( self, sim_scene: SimScene, groups: Dict[str, Dict], random_state: Optional[np.random.RandomState] = None, ): """Initializes a new component. Args: sim_scene: The simulation to control. groups: Group configurations for reading/writing state. random_state: A random state to use for generating noise. """ self.sim_scene = sim_scene self.random_state = random_state if self.random_state is None: logging.info( 'Random state not given; observation noise will be ignored') # Process all groups. self.groups = {} for group_name, group_config in groups.items(): try: config = self._process_group(**group_config) except Exception as e: raise type(e)('[{}] Error parsing group "{}": {}'.format( self.__class__.__name__, group_name, str(e), )).with_traceback(sys.exc_info()[2]) self.groups[group_name] = config @property def is_hardware(self) -> bool: """Returns True if this is a hardware component.""" return False def close(self): """Cleans up any resources used by the component.""" def get_state(self, groups: Union[str, Sequence[str]], **kwargs) -> Union[GroupState, Sequence[GroupState]]: """Returns the state of the given groups. Args: groups: Either a single group name or a list of group names of the groups to retrieve the state of. Returns: If `groups` is a string, returns a single state object. Otherwise, returns a list of state objects. """ if isinstance(groups, str): states = self._get_group_states([self.get_config(groups)], **kwargs) else: states = self._get_group_states( [self.get_config(name) for name in groups], **kwargs) if isinstance(groups, str): return states[0] return states def get_config(self, group_name: str) -> GroupConfig: """Returns the configuration for a group.""" if group_name not in self.groups: raise ValueError( 'Group "{}" is not in the configured groups: {}'.format( group_name, sorted(self.groups.keys()))) return self.groups[group_name] @abc.abstractmethod def _process_group(self, **config_kwargs) -> GroupConfig: """Processes the configuration for a group. This should be overridden by subclasses to define and validate the group configuration. Args: **config_kwargs: Keyword arguments from the group configuration. Returns: An object that defines the group. e.g. A class that stores the group parameters. """ @abc.abstractmethod def _get_group_states(self, configs: Sequence[GroupConfig], **kwargs) -> Sequence[GroupState]: """Returns the states for the given group configurations."""
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/builder.py
robel/components/builder.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Shared logic for a component builder. """ import abc from typing import List from robel.components.base import BaseComponent class ComponentBuilder(metaclass=abc.ABCMeta): """Base class for a component configuration. This wraps a dictionary of parameters that is used to initialize a Component. """ def __init__(self): self.group_configs = {} @property def group_names(self) -> List[str]: """Returns the sorted list of current group names.""" return sorted(self.group_configs.keys()) @abc.abstractmethod def build(self, *args, **kwargs) -> BaseComponent: """Builds the component.""" def add_group(self, group_name: str, **group_kwargs): """Adds a group configuration. Args: group_name: The name of the group. **group_kwargs: Key-value pairs to configure the group with. """ if group_name in self.group_configs: raise ValueError( 'Group with name `{}` already exists in component config.' .format(group_name)) self.group_configs[group_name] = group_kwargs def update_group(self, group_name: str, **group_kwargs): """Updates a group configuration. Args: group_name: The name of the group. **group_kwargs: Key-value pairs to configure the group with. """ self._check_group_exists(group_name) self.group_configs[group_name].update(group_kwargs) def _check_group_exists(self, name: str): """Raises an error if a group with the given name doesn't exist.""" if name not in self.group_configs: raise ValueError( ('No group with name "{}" was added to the builder. Currently ' 'added groups: {}').format(name, self.group_names))
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/tracking/tracker.py
robel/components/tracking/tracker.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Component implementation for interfacing with a Tracker.""" import logging from typing import Dict, Optional, Sequence import numpy as np from transforms3d.euler import euler2mat, mat2euler from transforms3d.quaternions import mat2quat from robel.components.base import BaseComponent from robel.components.tracking.group_config import TrackerGroupConfig class TrackerState: """Data class that represents the state of the tracker.""" def __init__(self, pos: Optional[np.ndarray] = None, rot: Optional[np.ndarray] = None, rot_euler: Optional[np.ndarray] = None, vel: Optional[np.ndarray] = None, angular_vel: Optional[np.ndarray] = None): """Initializes a new state object. Args: pos: The (x, y, z) position of the tracked position. The z-axis points upwards. rot: The (3x3) rotation matrix of the tracked position. rot_euler: The (rx, ry, rz) Euler rotation of the tracked position. vel: The (x, y, z) velocity of the tracked position. This is only available for tracked joints. angular_vel: The (rx, ry, rz) angular velocity of the tracked position. This is only available for tracked joints. """ self.pos = pos self.vel = vel self.angular_vel = angular_vel self._rot_mat = rot self._rot_euler = rot_euler @property def rot(self): """Returns the 3x3 rotation matrix.""" if self._rot_mat is not None: return self._rot_mat if self._rot_euler is not None: self._rot_mat = euler2mat(*self._rot_euler, axes='rxyz') return self._rot_mat @rot.setter def rot(self, value): self._rot_mat = value @property def rot_euler(self): """Returns the (rx, ry, rz) Euler rotations.""" if self._rot_euler is not None: return self._rot_euler if self._rot_mat is not None: self._rot_euler = mat2euler(self.rot, axes='rxyz') return self._rot_euler @rot_euler.setter def rot_euler(self, value): self._rot_euler = value @property def rot_quat(self): """Returns the rotation as a quaternion.""" return mat2quat(self.rot) class TrackerComponent(BaseComponent): """Component for reading tracking data.""" def _process_group(self, **config_kwargs): """Processes the configuration for a group.""" return TrackerGroupConfig(self.sim_scene, **config_kwargs) def set_state(self, state_groups: Dict[str, TrackerState]): """Sets the tracker to the given initial state. Args: state_groups: A mapping of control group name to desired position and velocity. """ changed_elements = [] for group_name, state in state_groups.items(): config = self.get_config(group_name) if self._set_element_state(state, config): changed_elements.append((config, state.pos)) if changed_elements: self.sim_scene.sim.forward() # Verify that changes occured. for config, pos in changed_elements: new_pos = self._get_element_state(config).pos if new_pos is None or not np.allclose(new_pos, pos): logging.error( 'Element #%d is immutable (modify the XML with a non-zero ' 'starting position).', config.element_name) def _get_group_states( self, configs: Sequence[TrackerGroupConfig], ) -> Sequence[TrackerState]: """Returns the TrackerState for the given groups. Args: configs: The group configurations to retrieve the states for. Returns: A list of TrackerState(timestamp, pos, quat, euler). """ return [self._get_element_state(config) for config in configs] def _get_element_state(self, config: TrackerGroupConfig) -> TrackerState: """Returns the simulation element state for the given group config.""" state = TrackerState() if config.element_id is None and config.qpos_indices is None: return state state.pos = config.get_pos(self.sim_scene) state.rot = config.get_rot(self.sim_scene) if config.qpos_indices is not None: state.vel = config.get_vel(self.sim_scene) state.angular_vel = config.get_angular_vel(self.sim_scene) if (config.sim_observation_noise is not None and self.random_state is not None): amplitude = config.sim_observation_noise / 2.0 state.pos += self.random_state.uniform( low=-amplitude, high=amplitude, size=state.pos.shape) return state def _set_element_state(self, state: TrackerState, config: TrackerGroupConfig, ignore_z_axis: bool = False) -> bool: """Sets the simulation state for the given element.""" changed = False if config.element_id is None and config.qpos_indices is None: return changed if state.pos is not None: if ignore_z_axis: config.set_pos(self.sim_scene, state.pos[:2]) else: config.set_pos(self.sim_scene, state.pos) changed = True if state.rot is not None: rot_quat = mat2quat(state.rot) config.set_rot_quat(self.sim_scene, rot_quat) changed = True return changed
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/tracking/hardware_tracker.py
robel/components/tracking/hardware_tracker.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of TrackerComponent using OpenVR to track devices.""" import abc import logging from typing import Dict, Optional, Sequence, Union import numpy as np from transforms3d.euler import euler2quat, euler2mat, quat2euler from transforms3d.quaternions import quat2mat, qconjugate from robel.components.tracking.tracker import ( TrackerComponent, TrackerGroupConfig, TrackerState) from robel.components.tracking.utils.coordinate_system import ( CoordinateSystem) from robel.utils.math_utils import average_quaternions DeviceId = Union[int, str] class HardwareTrackerGroupConfig(TrackerGroupConfig): """Stores group configuration for a VrTrackerComponent.""" def __init__(self, *args, device_identifier: Optional[DeviceId] = None, is_origin: bool = False, tracked_position_offset: Optional[Sequence[float]] = None, tracked_rotation_offset: Optional[Sequence[float]] = None, mimic_in_sim: bool = False, mimic_ignore_z_axis: bool = False, mimic_ignore_rotation: bool = False, **kwargs): """Initializes a new configuration for a HardwareTrackerComponent group. Args: device_identifier: The device index or device serial string of the tracking device. is_origin: If True, the (0, 0, 0) world position is inferred to be at this group's location. tracked_position_offset: The offset to add to the tracked positions. tracked_rotation_offset: The offset to add to the tracked rotations. mimic_in_sim: If True, updates the simulation sites with the tracked positions. mimic_ignore_z_axis: If True, the simulation site is only updated with the x and y position. mimic_ignore_rotation: If True, the simulation site is not updated with the rotation. """ super().__init__(*args, **kwargs) self.device_identifier = device_identifier self.is_origin = is_origin self.mimic_in_sim = mimic_in_sim self.mimic_ignore_z_axis = mimic_ignore_z_axis self.mimic_ignore_rotation = mimic_ignore_rotation self.tracked_position_offset = None if tracked_position_offset is not None: tracked_position_offset = np.array( tracked_position_offset, dtype=np.float32) assert tracked_position_offset.shape == ( 3,), tracked_position_offset.shape self.tracked_position_offset = tracked_position_offset self.tracked_rotation_offset = None if tracked_rotation_offset is not None: tracked_rotation_offset = np.array( tracked_rotation_offset, dtype=np.float32) assert tracked_rotation_offset.shape == ( 3,), tracked_rotation_offset.shape self.tracked_rotation_offset = euler2quat( *tracked_rotation_offset, axes='rxyz') class HardwareTrackerComponent(TrackerComponent): """Component for reading tracking data from a HTC Vive.""" def __init__(self, *args, **kwargs): """Create a new hardware tracker component.""" super().__init__(*args, **kwargs) self._coord_system = CoordinateSystem() self._plot = None @property def is_hardware(self) -> bool: """Returns True if this is a hardware component.""" return True def _process_group(self, **config_kwargs): """Processes the configuration for a group.""" return HardwareTrackerGroupConfig(self.sim_scene, **config_kwargs) def _get_group_states( self, configs: Sequence[HardwareTrackerGroupConfig], raw_states: bool = False, ) -> Sequence[TrackerState]: """Returns the TrackerState for the given groups. Args: configs: The group configurations to retrieve the states for. Returns: A list of TrackerState(timestamp, pos, quat, euler). """ self._refresh_poses() simulation_changed = False states = [] for config in configs: if config.device_identifier is None: # Fall back to simulation site. states.append(self._get_element_state(config)) continue state = self._get_tracker_state( config.device_identifier, ignore_device_transform=raw_states) # Mimic the site in simulation if needed. if config.mimic_in_sim: mimic_state = TrackerState( pos=state.pos, rot=None if config.mimic_ignore_rotation else state.rot) simulation_changed |= self._set_element_state( mimic_state, config, ignore_z_axis=config.mimic_ignore_z_axis) states.append(state) if simulation_changed: self.sim_scene.sim.forward() return states def set_state(self, state_groups: Dict[str, TrackerState]): """Sets the tracker to the given initial state. Args: state_groups: A mapping of control group name to desired position and velocity. """ origin_device_id = None device_positions = {} device_rotations = {} ignored_group_positions = [] for group_name, state in state_groups.items(): config = self.get_config(group_name) device_id = config.device_identifier if device_id is None: continue pos_offset = config.tracked_position_offset quat_offset = config.tracked_rotation_offset # Only respect the set position for the origin device. if state.pos is not None: assert state.pos.shape == (3,), state.pos if config.is_origin: if origin_device_id is not None: raise ValueError('Cannot have more than one origin.') origin_device_id = device_id if pos_offset is None: pos_offset = state.pos else: pos_offset = pos_offset + state.pos else: ignored_group_positions.append( (group_name, device_id, state.pos)) if state.rot is not None: logging.warning('Ignoring setting rotation for group: "%s"', group_name) device_positions[device_id] = pos_offset device_rotations[device_id] = quat_offset # Set the coordinate system. self._update_coordinate_system(origin_device_id, device_positions, device_rotations) # Log any ignored positions. if ignored_group_positions: self._refresh_poses() for group_name, device_id, desired_pos in ignored_group_positions: state = self._get_tracker_state(device_id) logging.warning( 'Ignored setting position for group: "%s" - ' 'Desired position: %s, Actual position: %s', group_name, str(desired_pos.tolist()), str(state.pos.tolist())) def _update_coordinate_system(self, origin_device_id: Optional[DeviceId], device_positions: Dict[DeviceId, np.ndarray], device_rotations: Dict[DeviceId, np.ndarray], num_samples: int = 10): """Updates the coordinate system origin.""" if origin_device_id: # Collect samples for the devices. pos_samples = [] quat_samples = [] for _ in range(num_samples): self._refresh_poses() state = self._get_tracker_state( origin_device_id, ignore_device_transform=True) pos_samples.append(state.pos) quat_samples.append(state.rot_quat) global_translation = -np.mean(pos_samples, axis=0) global_rotation = qconjugate(average_quaternions(quat_samples)) origin_rx, origin_ry, origin_rz = quat2euler( global_rotation, axes='rxyz') logging.info('Have origin rotation: %1.2f %1.2f %1.2f', origin_rx, origin_ry, origin_rz) self._coord_system.set_global_transform(global_translation, euler2mat(0, 0, origin_rz)) for device_id, position in device_positions.items(): self._coord_system.set_local_transform( device_id, translation=position) for device_id, rotation in device_rotations.items(): self._coord_system.set_local_transform(device_id, rotation=rotation) def _get_tracker_state( self, device_id: DeviceId, ignore_device_transform: bool = False, ) -> TrackerState: """Returns the tracker state in the coordinate system.""" state = self._get_raw_tracker_state(device_id) state = self._coord_system.record_state( device_id, state, ignore_object_transform=ignore_device_transform) return state def show_plot(self, auto_update: bool = False, frame_rate: int = 10): """Displays a plot that shows the current tracked positions. Args: auto_update: If True, queries and updates the plot with new pose data at the given frame rate. frame_rate: The frequency at which the plot is refreshed. """ if self._plot and self._plot.is_open: return from robel.utils.plotting import AnimatedPlot self._plot = AnimatedPlot(bounds=[-5, 5, -5, 5]) device_ids = [(name, config.device_identifier) for name, config in self.groups.items()] data = np.zeros((len(device_ids), 2), dtype=np.float32) scatter = self._plot.ax.scatter( data[:, 0], data[:, 1], cmap='jet', edgecolor='k') self._plot.add(scatter) # Make annotations labels = [] for i, (name, device_id) in enumerate(device_ids): text = '{} ({})'.format(name, device_id) label = self._plot.ax.annotate(text, xy=(data[i, 0], data[i, 1])) labels.append(label) self._plot.add(label) def update(): if auto_update: self._refresh_poses() for i, (name, device_id) in enumerate(device_ids): info = ['{} ({})'.format(name, device_id)] state = self._get_tracker_state(device_id) pos = state.pos euler = state.rot_euler if pos is not None: data[i, 0] = pos[0] data[i, 1] = pos[1] labels[i].set_position((pos[0], pos[1] + 0.2)) info.append('Tx:{:.2f} Ty:{:.2f} Tz:{:.2f}'.format(*pos)) if euler is not None: info.append('Rx:{:.2f} Ry:{:.2f} Rz:{:.2f}'.format(*euler)) labels[i].set_text('\n'.join(info)) scatter.set_offsets(data) self._plot.update_fn = update self._plot.show(frame_rate=frame_rate) @abc.abstractmethod def _refresh_poses(self): """Refreshes the pose state.""" @abc.abstractmethod def _get_raw_tracker_state(self, device_id: DeviceId) -> TrackerState: """Returns the tracker state."""
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/tracking/vr_tracker.py
robel/components/tracking/vr_tracker.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of TrackerComponent using OpenVR to track devices.""" import numpy as np from robel.components.tracking.hardware_tracker import ( DeviceId, HardwareTrackerComponent, HardwareTrackerGroupConfig, TrackerState) class VrTrackerGroupConfig(HardwareTrackerGroupConfig): """Stores group configuration for a VrTrackerComponent.""" class VrTrackerComponent(HardwareTrackerComponent): """Component for reading tracking data from a HTC Vive.""" # Cached VR client that is shared for the application lifetime. _VR_CLIENT = None # Transform from OpenVR space (y upwards) to simulation space (z upwards). GLOBAL_TRANSFORM = np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]], dtype=np.float32) def __init__(self, *args, **kwargs): """Initializes a VrTrackerComponent.""" super().__init__(*args, **kwargs) self._coord_system.set_coordinate_transform(self.GLOBAL_TRANSFORM) self._poses = None if self._VR_CLIENT is None: from robel.components.tracking.virtual_reality.client import ( VrClient) self._VR_CLIENT = VrClient() # Check that all devices exist. for name, group in self.groups.items(): if group.device_identifier is None: continue device = self._VR_CLIENT.get_device(group.device_identifier) print('Assigning group "{}" with device: {}'.format( name, device.get_summary())) def _process_group(self, **config_kwargs): """Processes the configuration for a group.""" return VrTrackerGroupConfig(self.sim_scene, **config_kwargs) def _refresh_poses(self): """Refreshes the pose state.""" self._poses = self._VR_CLIENT.get_poses() def _get_raw_tracker_state(self, device_id: DeviceId) -> TrackerState: """Returns the tracker state.""" device = self._VR_CLIENT.get_device(device_id) return self._poses.get_state(device)
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/tracking/group_config.py
robel/components/tracking/group_config.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Configuration for a tracker component group.""" from typing import Iterable, Optional import numpy as np from transforms3d.euler import euler2mat, quat2euler from transforms3d.quaternions import quat2mat from robel.simulation.sim_scene import SimScene class TrackerGroupConfig: """Group configuration for a TrackerComponent.""" def __init__(self, sim_scene: SimScene, element_name: Optional[str] = None, element_type: Optional[str] = None, qpos_indices: Optional[Iterable[int]] = None, qvel_indices: Optional[Iterable[int]] = None, sim_observation_noise: Optional[float] = None): """Initializes a group configuration for a TrackerComponent. Args: sim_scene: The simulation, used for validation purposes. element_name: The name of the element to use for tracking in simulation. element_type: The type of the element as defined in the XML. Should be one of `site`, `body`, `geom`, or `joint`. If this is `joint`, `qpos_indices` and `qvel_indices` should be provided. qpos_indices: The indices into `MjData.qpos` to read for the joint element position and rotation. qvel_indices: The indices into `MjData.qvel` to read for the joint element velocity. This defaults to `qpos_indices`. sim_observation_noise: The range of the observation noise (in meters) to apply to the state in simulation. """ self.element_type = element_type if self.element_type not in ['site', 'body', 'geom', 'joint']: raise ValueError('Unknown element type %s' % self.element_type) self.element_name = element_name self.element_id = None self.element_attr = None self.qpos_indices = None self.qvel_indices = None self._is_euler = False if self.element_type == 'joint': if qpos_indices is None: raise ValueError('Must provided qpos_indices for joints.') # Ensure that the qpos indices are valid. nq = sim_scene.model.nq assert all(-nq <= i < nq for i in qpos_indices), \ 'All qpos indices must be in [-{}, {}]'.format(nq, nq - 1) self.qpos_indices = np.array(qpos_indices, dtype=int) if len(self.qpos_indices) == 6: self._is_euler = True elif len(self.qpos_indices) != 7: raise ValueError('qpos_indices must be 6 or 7 elements.') if qvel_indices is None: if not self._is_euler: raise ValueError( 'qvel_indices must be provided for free joints.') qvel_indices = qpos_indices # Ensure that the qvel indices are valid. nv = sim_scene.model.nv assert all(-nv <= i < nv for i in qvel_indices), \ 'All qvel indices must be in [-{}, {}]'.format(nv, nv - 1) self.qvel_indices = np.array(qvel_indices, dtype=int) else: self.element_attr = (lambda obj, attr_name: getattr( obj, self.element_type + '_' + attr_name)) self.element_id = self.element_attr(sim_scene.model, 'name2id')( element_name) self.sim_observation_noise = sim_observation_noise def get_pos(self, sim_scene: SimScene) -> np.ndarray: """Returns the cartesian position of the element.""" if self.qpos_indices is not None: return sim_scene.data.qpos[self.qpos_indices[:3]] return self.element_attr(sim_scene.data, 'xpos')[self.element_id, :] def get_rot(self, sim_scene: SimScene) -> np.ndarray: """Returns the (3x3) rotation matrix of the element.""" if self.qpos_indices is not None: qpos = sim_scene.data.qpos[self.qpos_indices[3:]] if self._is_euler: return euler2mat(*qpos, axes='rxyz') return quat2mat(qpos) return self.element_attr(sim_scene.data, 'xmat')[self.element_id].reshape((3, 3)) def get_vel(self, sim_scene: SimScene) -> np.ndarray: """Returns the cartesian velocity of the element.""" if self.qvel_indices is not None: return sim_scene.data.qvel[self.qvel_indices[:3]] raise NotImplementedError('Cartesian velocity is not supported for ' + self.element_type) def get_angular_vel(self, sim_scene: SimScene) -> np.ndarray: """Returns the angular velocity (x, y, z) of the element.""" if self.qvel_indices is not None: return sim_scene.data.qvel[self.qvel_indices[3:]] raise NotImplementedError('Angular velocity is not supported for ' + self.element_type) def set_pos(self, sim_scene: SimScene, pos: np.ndarray): """Sets the cartesian position of the element.""" if self.qpos_indices is not None: sim_scene.data.qpos[self.qpos_indices[:len(pos)]] = pos return self.element_attr(sim_scene.model, 'pos')[self.element_id, :len(pos)] = pos def set_rot_quat(self, sim_scene: SimScene, quat: np.ndarray): """Sets the cartesian position of the element.""" if self.qpos_indices is not None: qpos = quat if self._is_euler: qpos = quat2euler(quat, axes='rxyz') sim_scene.data.qpos[self.qpos_indices[3:]] = qpos return self.element_attr(sim_scene.model, 'quat')[self.element_id, :] = quat
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/tracking/phasespace_tracker.py
robel/components/tracking/phasespace_tracker.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of TrackerComponent using OpenVR to track devices.""" import time import numpy as np from transforms3d.quaternions import quat2mat from robel.components.tracking.hardware_tracker import ( DeviceId, HardwareTrackerComponent, HardwareTrackerGroupConfig, TrackerState) # Seconds to sleep to ensure PhaseSpace can start getting data. PHASESPACE_INIT_TIME = 4 class PhaseSpaceTrackerGroupConfig(HardwareTrackerGroupConfig): """Stores group configuration for a PhaseSpaceTrackerComponent.""" class PhaseSpaceTrackerComponent(HardwareTrackerComponent): """Component for reading tracking data from PhaseSpace.""" # Cached client that is shared for the application lifetime. _PS_CLIENT = None def __init__(self, *args, server_address: str, **kwargs): """Initializes a VrTrackerComponent.""" super().__init__(*args, **kwargs) if self._PS_CLIENT is None: import phasespace print('Connecting to PhaseSpace at: {}'.format(server_address)) self._PS_CLIENT = phasespace.PhaseSpaceClient(server_address) print('Connected! Waiting for initialization...') time.sleep(PHASESPACE_INIT_TIME) self._position_scale = 1e-3 self._poses = None self._state_cache = {} def _process_group(self, **config_kwargs): """Processes the configuration for a group.""" return PhaseSpaceTrackerGroupConfig(self.sim_scene, **config_kwargs) def _refresh_poses(self): """Refreshes the pose state.""" self._poses = self._PS_CLIENT.get_state() def _get_raw_tracker_state(self, device_id: DeviceId): """Returns the tracker state.""" try: rigid_data = self._poses.get_rigid(device_id) state = TrackerState( pos=rigid_data.position * self._position_scale, rot=quat2mat(rigid_data.rotation), vel=np.zeros(3), angular_vel=np.zeros(3)) self._state_cache[device_id] = state except: if device_id not in self._state_cache: raise state = self._state_cache[device_id] return state
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/tracking/__init__.py
robel/components/tracking/__init__.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tracking component module.""" from .tracker import TrackerState from .builder import TrackerComponentBuilder, TrackerType
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/tracking/builder.py
robel/components/tracking/builder.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Builder-specific logic for creating TrackerComponents.""" import enum from typing import Any, Dict, Optional, Union from robel.components.builder import ComponentBuilder from robel.components.tracking.tracker import TrackerComponent from robel.components.tracking.vr_tracker import VrTrackerComponent from robel.components.tracking.phasespace_tracker import PhaseSpaceTrackerComponent class TrackerType(enum.Enum): """The type of the tracker.""" SIMULATED = 0 OPENVR = 1 PHASESPACE = 2 class TrackerComponentBuilder(ComponentBuilder): """Builds a RobotComponent.""" def __init__(self): super().__init__() self._hardware_tracker_ids = set() self._tracker_type = None self._tracker_kwargs = {} def build(self, *args, **kwargs): """Builds the component.""" kwargs = {**kwargs, **self._tracker_kwargs} tracker_type = self._tracker_type if tracker_type is None: # Default to OpenVR if tracker IDs were added. if self._hardware_tracker_ids: tracker_type = TrackerType.OPENVR else: tracker_type = TrackerType.SIMULATED if tracker_type == TrackerType.OPENVR: return VrTrackerComponent( *args, groups=self.group_configs, **kwargs) elif tracker_type == TrackerType.PHASESPACE: return PhaseSpaceTrackerComponent( *args, groups=self.group_configs, **kwargs) elif tracker_type == TrackerType.SIMULATED: return TrackerComponent( *args, groups=self.group_configs, **kwargs) else: raise NotImplementedError(self._tracker_type) def set_tracker_type(self, tracker_type: Union[TrackerType, str], **kwargs): """Sets the tracker type.""" if isinstance(tracker_type, str): tracker_type = TrackerType[tracker_type.upper()] self._tracker_type = tracker_type self._tracker_kwargs = kwargs def set_hardware_tracker_id(self, group_name: str, tracker_id: Union[str, int]): """Sets the hardware tracker ID for the given group. Args: group_name: The group to set the tracker ID for. tracker_id: Either the device serial number string, or the device index of the tracking device. """ self._check_group_exists(group_name) self._hardware_tracker_ids.add(tracker_id) self.group_configs[group_name]['device_identifier'] = tracker_id def add_tracker_group( self, group_name: str, hardware_tracker_id: Optional[Union[str, int]], sim_params: Optional[Dict[str, Any]] = None, hardware_params: Optional[Dict[str, Any]] = None, mimic_sim: bool = True, mimic_xy_only: bool = False, ): """Convenience method for adding a tracking group. Args: group_name: The group name to create. hardware_tracker_id: Either the device serial number string, or the device index of the hardware tracking device. sim_params: The group parameters for simulation tracking. hardware_params: The group parameters for hardware tracking. mimic_sim: If True, adds parameters so that simulation mimics the hardware. mimic_xy_only: If True, adds parameters so that only the XY plane movement is mimicked to the simulation. """ self.add_group(group_name, **sim_params) if hardware_tracker_id is not None: self.set_hardware_tracker_id(group_name, hardware_tracker_id) hardware_params = hardware_params or {} if mimic_sim: hardware_params['mimic_in_sim'] = True if mimic_xy_only: hardware_params.update({ 'mimic_ignore_z_axis': True, 'mimic_ignore_rotation': True, }) if hardware_params: self.update_group(group_name, **hardware_params)
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/tracking/virtual_reality/client.py
robel/components/tracking/virtual_reality/client.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Client to communicate with a VR device using OpenVR. Example usage: >>> client = VrClient() >>> client.set_devices({'tracker': 1}) """ from typing import List, Union import openvr from robel.components.tracking.virtual_reality.device import VrDevice from robel.components.tracking.virtual_reality.poses import VrPoseBatch class VrClient: """Communicates with a VR device.""" def __init__(self): self._vr_system = None self._devices = [] self._device_serial_lookup = {} self._device_index_lookup = {} self._last_pose_batch = None self._plot = None # Attempt to start OpenVR. if not openvr.isRuntimeInstalled(): raise OSError('OpenVR runtime not installed.') self._vr_system = openvr.init(openvr.VRApplication_Other) def close(self): """Cleans up any resources used by the client.""" if self._vr_system is not None: openvr.shutdown() self._vr_system = None def get_device(self, identifier: Union[int, str]) -> VrDevice: """Returns the device with the given name.""" identifier = str(identifier) if identifier in self._device_index_lookup: return self._device_index_lookup[identifier] if identifier in self._device_serial_lookup: return self._device_serial_lookup[identifier] self.discover_devices() if (identifier not in self._device_index_lookup and identifier not in self._device_serial_lookup): raise ValueError( 'Could not find device with name or index: {} (Available: {})' .format(identifier, sorted(self._device_serial_lookup.keys()))) if identifier in self._device_index_lookup: return self._device_index_lookup[identifier] return self._device_serial_lookup[identifier] def discover_devices(self) -> List[VrDevice]: """Returns and caches all connected devices.""" self._device_index_lookup.clear() self._device_serial_lookup.clear() devices = [] for device_index in range(openvr.k_unMaxTrackedDeviceCount): device = VrDevice(self._vr_system, device_index) if not device.is_connected(): continue devices.append(device) self._device_index_lookup[str(device.index)] = device self._device_serial_lookup[device.get_serial()] = device self._devices = devices return devices def get_poses(self, time_from_now: float = 0.0, update_plot: bool = True) -> VrPoseBatch: """Returns a batch of poses that can be queried per device. Args: time_from_now: The seconds into the future to read poses. update_plot: If True, updates an existing plot. """ pose_batch = VrPoseBatch(self._vr_system, time_from_now) self._last_pose_batch = pose_batch if update_plot and self._plot and self._plot.is_open: self._plot.refresh() return pose_batch def __enter__(self): """Enables use as a context manager.""" return self def __exit__(self, *args): """Enables use as a context manager.""" self.close() def __del__(self): """Automatically disconnect on destruction.""" self.close()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/tracking/virtual_reality/__init__.py
robel/components/tracking/virtual_reality/__init__.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/tracking/virtual_reality/poses.py
robel/components/tracking/virtual_reality/poses.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Pose-related logic for OpenVR devices.""" import numpy as np import openvr from robel.components.tracking.tracker import TrackerState from robel.components.tracking.virtual_reality.device import VrDevice class VrPoseBatch: """Represents a batch of poses calculated by the OpenVR system.""" def __init__(self, vr_system, time_from_now: float = 0.0): """Initializes a new pose batch.""" self._vr_system = vr_system # Query poses for all devices. self.poses = self._vr_system.getDeviceToAbsoluteTrackingPose( openvr.TrackingUniverseStanding, time_from_now, openvr.k_unMaxTrackedDeviceCount) def get_state(self, device: VrDevice) -> TrackerState: """Returns the tracking state for the given device.""" if not self.poses[device.index].bPoseIsValid: state = TrackerState() else: vr_pose = np.ctypeslib.as_array( self.poses[device.index].mDeviceToAbsoluteTracking[:], shape=(3, 4)) # Check that the pose is valid. # If all of the translations are 0, get from the cache. assert vr_pose.shape == (3, 4) state = TrackerState(pos=vr_pose[:, 3], rot=vr_pose[:, :3]) return state
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/tracking/virtual_reality/device.py
robel/components/tracking/virtual_reality/device.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Device-related logic from OpenVR devices.""" import openvr class VrDevice: """Represents an OpenVR device.""" def __init__(self, vr_system, index: int): """Initializes a new VrDevice with the given device index.""" self._vr_system = vr_system self._index = index self._value_cache = {} @property def index(self) -> int: """Returns the device index.""" return self._index def is_connected(self) -> bool: """Returns whether the device is connected.""" return self._vr_system.isTrackedDeviceConnected(self._index) def get_serial(self) -> str: """Returns the serial number of the device.""" return self._get_string(openvr.Prop_SerialNumber_String) def get_model(self) -> str: """Returns the model number of the device.""" return self._get_string(openvr.Prop_ModelNumber_String) def get_model_name(self) -> str: """Returns the model name of the device.""" return self._get_string(openvr.Prop_RenderModelName_String) def get_summary(self) -> str: """Returns a summary of information about the device.""" connected = self.is_connected() info = '[{} - {}]'.format(self._index, 'Connected' if connected else 'Disconnected') if connected: info += ' {} ({})'.format(self.get_model_name(), self.get_serial()) return info def _get_string(self, prop_type) -> str: """Returns a string property of the device.""" if prop_type in self._value_cache: return self._value_cache[prop_type] value = self._vr_system.getStringTrackedDeviceProperty( self._index, prop_type).decode('utf-8') self._value_cache[prop_type] = value return value def _get_bool(self, prop_type) -> bool: """Returns a boolean property of the device.""" if prop_type in self._value_cache: return self._value_cache[prop_type] value = self._vr_system.getBoolTrackedDeviceProperty( self._index, prop_type)[0] self._value_cache[prop_type] = value return value def _get_float(self, prop_type) -> float: """Returns a float property of the device.""" if prop_type in self._value_cache: return self._value_cache[prop_type] value = self._vr_system.getFloatTrackedDeviceProperty( self._index, prop_type)[0] self._value_cache[prop_type] = value return value
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/tracking/utils/coordinate_system.py
robel/components/tracking/utils/coordinate_system.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Coordinate system for pose-related logic.""" import collections from typing import Optional, Union import numpy as np from transforms3d.quaternions import quat2mat from robel.components.tracking.tracker import TrackerState ObjectId = Union[str, int] class CoordinateSystem: """Stores the most recently returned values for device poses.""" def __init__(self): # Coordinate system transformation to apply to all poses. self._coordinate_transform = None # Global transformation to apply to all poses. self._global_translation = None self._global_rotation = None # Per-object transforms. self._local_translations = {} self._local_rotations = {} # Per-object state cache. self._state_cache = collections.defaultdict(TrackerState) def set_coordinate_transform(self, transform: np.ndarray): """Sets the coordinate transform.""" if transform.shape != (3, 3): raise ValueError('') def set_global_transform(self, translation: np.ndarray, rotation: np.ndarray): """Sets the global transform.""" trans, rot = self._check_transform(translation, rotation) self._global_translation = trans self._global_rotation = rot def set_local_transform(self, object_id: ObjectId, translation: Optional[np.ndarray] = None, rotation: Optional[np.ndarray] = None): """Sets the local transform for the given object.""" trans, rot = self._check_transform(translation, rotation) if trans is not None: self._local_translations[object_id] = trans if rot is not None: self._local_rotations[object_id] = rot def record_state(self, object_id: ObjectId, state: TrackerState, ignore_object_transform: bool = False) -> TrackerState: """Records and transforms the given state.""" state = self.transform_raw_state(state) # Add to the state cache. cached_state = self._state_cache[object_id] for prop in ('pos', 'rot', 'vel', 'angular_vel'): new_value = getattr(state, prop) if new_value is not None: setattr(cached_state, prop, new_value) else: # Get the cached value. setattr(state, prop, getattr(cached_state, prop)) if not ignore_object_transform: state = self.transform_object_state(object_id, state) return state def get_cached_state(self, object_id: ObjectId) -> TrackerState: """Returns the cached state for the object.""" return self._state_cache[object_id] def transform_raw_state(self, state: TrackerState) -> TrackerState: """Transforms the given state to the coordinate system.""" pos = state.pos rot = state.rot vel = state.vel angular_vel = state.angular_vel if self._coordinate_transform: if pos is not None: pos = np.matmul(self._coordinate_transform, pos) if rot is not None: rot = np.matmul(self._coordinate_transform, rot) rot = np.matmul(rot, np.transpose(self._coordinate_transform)) if vel is not None: vel = np.matmul(self._coordinate_transform, vel) if angular_vel is not None: angular_vel = np.matmul(self._coordinate_transform, angular_vel) return TrackerState(pos=pos, rot=rot, vel=vel, angular_vel=angular_vel) def transform_object_state(self, object_id: ObjectId, state: TrackerState): """Transforms the given object state to the coordinate system.""" pos = state.pos rot = state.rot vel = state.vel angular_vel = state.angular_vel if pos is not None: if self._global_translation is not None: pos = pos + self._global_translation if object_id in self._local_translations: pos = pos + self._local_translations[object_id] rotations = [ self._global_rotation, self._local_rotations.get(object_id) ] for rotation in rotations: if rotation is None: continue if pos is not None: pos = np.matmul(rotation, pos) if rot is not None: rot = np.matmul(rotation, rot) if vel is not None: vel = np.matmul(rotation, vel) if angular_vel is not None: angular_vel = np.matmul(rotation, angular_vel) return TrackerState(pos=pos, rot=rot, vel=vel, angular_vel=angular_vel) def _check_transform(self, translation: Optional[np.ndarray], rotation: Optional[np.ndarray]): """Checks that the given translation and rotation are valid.""" if translation is None: pass elif translation.shape != (3,): raise ValueError('Expected translation to have shape 3') else: translation = translation.copy() if rotation is None: pass elif rotation.shape == (4,): rotation = quat2mat(rotation) elif rotation.shape == (3, 3): rotation = rotation.copy() else: raise ValueError('Expected rotation to have shape (3, 3)') return translation, rotation
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/tracking/utils/__init__.py
robel/components/tracking/utils/__init__.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/robot/dynamixel_robot.py
robel/components/robot/dynamixel_robot.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of HardwareRobotComponent using the DynamixelSDK.""" from typing import Dict, Iterable, Optional, Sequence, Tuple, Union import numpy as np from robel.components.robot import ControlMode from robel.components.robot.dynamixel_client import DynamixelClient from robel.components.robot.hardware_robot import ( HardwareRobotComponent, HardwareRobotGroupConfig, RobotState) class DynamixelRobotState(RobotState): """Data class that represents the state of a Dynamixel robot.""" def __init__(self, *args, current: Optional[np.ndarray] = None, **kwargs): """Initializes a new state object. Args: current: The present current reading for the motors, in mA. """ super().__init__(*args, **kwargs) self.current = current class DynamixelGroupConfig(HardwareRobotGroupConfig): """Stores group configuration for a DynamixelRobotComponent.""" def __init__(self, *args, motor_ids: Optional[Iterable[int]] = None, **kwargs): """Initializes a new configuration for a HardwareRobotComponent group. Args: motor_ids: The Dynamixel motor identifiers to associate with this group. """ super().__init__(*args, **kwargs) self.motor_ids = None if motor_ids is not None: self.motor_ids = np.array(motor_ids, dtype=int) if self.calib_scale is not None: assert self.motor_ids.shape == self.calib_scale.shape if self.calib_offset is not None: assert self.motor_ids.shape == self.calib_offset.shape self.motor_id_indices = None @property def is_active(self) -> bool: """Returns True if the group is not in use.""" return self.motor_ids is not None def set_all_motor_ids(self, all_motor_ids: Sequence[int]): """Sets this group's motor ID mask from the given total list of IDs.""" assert np.all(np.diff(all_motor_ids) > 0), \ 'all_motor_ids must be sorted.' assert np.all(np.isin(self.motor_ids, all_motor_ids)) self.motor_id_indices = np.searchsorted(all_motor_ids, self.motor_ids) class DynamixelRobotComponent(HardwareRobotComponent): """Component for hardware robots using Dynamixel motors.""" # Cache dynamixel_py instances by device path. DEVICE_CLIENTS = {} def __init__(self, *args, groups: Dict[str, Dict], device_path: str, **kwargs): """Initializes the component. Args: groups: Group configurations for reading/writing state. device_path: The path to the Dynamixel device to open. """ self._combined_motor_ids = set() super().__init__(*args, groups=groups, **kwargs) self._all_motor_ids = np.array( sorted(self._combined_motor_ids), dtype=int) for group_config in self.groups.values(): if group_config.is_active: group_config.set_all_motor_ids(self._all_motor_ids) if device_path not in self.DEVICE_CLIENTS: hardware = DynamixelClient( self._all_motor_ids, port=device_path, lazy_connect=True) self.DEVICE_CLIENTS[device_path] = hardware self._hardware = self.DEVICE_CLIENTS[device_path] def _process_group(self, **config_kwargs) -> DynamixelGroupConfig: """Processes the configuration for a group.""" config = DynamixelGroupConfig(self.sim_scene, **config_kwargs) if config.is_active: self._combined_motor_ids.update(config.motor_ids) return config def set_motors_engaged(self, groups: Union[str, Sequence[str], None], engaged: bool): """Enables the motors in the given group name.""" # Interpret None as all motors. if groups is None: self._hardware.set_torque_enabled(self._all_motor_ids, engaged) return if isinstance(groups, str): group_configs = [self.get_config(groups)] else: group_configs = [self.get_config(name) for name in groups] total_motor_id_mask = np.zeros_like(self._all_motor_ids, dtype=bool) for config in group_configs: if config.is_active: total_motor_id_mask[config.motor_id_indices] = True self._hardware.set_torque_enabled( self._all_motor_ids[total_motor_id_mask], engaged) def _get_group_states( self, configs: Sequence[DynamixelGroupConfig], ) -> Sequence[DynamixelRobotState]: """Returns the states for the given group configurations.""" # Make one call to the hardware to get all of the positions/velocities, # and extract each individual groups' subset from them. all_qpos, all_qvel, all_cur = self._hardware.read_pos_vel_cur() states = [] for config in configs: state = DynamixelRobotState() # Return a blank state if this is a sim-only group. if config.motor_ids is None: states.append(state) continue state.qpos = all_qpos[config.motor_id_indices] state.qvel = all_qvel[config.motor_id_indices] state.current = all_cur[config.motor_id_indices] self._calibrate_state(state, config) states.append(state) self._copy_to_simulation_state(zip(configs, states)) return states def _set_group_states( self, group_states: Sequence[Tuple[DynamixelGroupConfig, RobotState]], block: bool = True, **block_kwargs): """Sets the robot joints to the given states. Args: group_states: The states to set for each group. block: If True, blocks the current thread until completion. **block_kwargs: Arguments to pass to `_wait_for_desired_states`. """ # Filter out sim-only groups. group_states = [(config, state) for config, state in group_states if config.is_active and state.qpos is not None] if not group_states: return # Only write the qpos for the state. group_control = [(config, state.qpos) for config, state in group_states] self._set_hardware_control(group_control) # Block until we've reached the given states. if block: self._wait_for_desired_states(group_states, **block_kwargs) # Reset the step time. self.reset_time() def _perform_timestep( self, group_controls: Sequence[Tuple[DynamixelGroupConfig, np.ndarray]]): """Applies the given control values to the robot.""" self._set_hardware_control(group_controls) self._synchronize_timestep() def _set_hardware_control( self, group_control: Sequence[Tuple[DynamixelGroupConfig, np.ndarray]]): """Sets the desired hardware positions. Args: group_control: A list of (group config, control) pairs to write to the hardware. """ total_motor_id_mask = np.zeros_like(self._all_motor_ids, dtype=bool) total_qpos = np.zeros_like(self._all_motor_ids, dtype=np.float32) for config, control in group_control: if config.motor_ids is None: continue if control is not None: # TODO(michaelahn): Consider if other control modes need # decalibration. if config.control_mode == ControlMode.JOINT_POSITION: control = self._decalibrate_qpos(control, config) total_motor_id_mask[config.motor_id_indices] = True total_qpos[config.motor_id_indices] = control if np.any(total_motor_id_mask): # TODO(michaeahn): Need to switch control mode if we're not in joint # position control. self._hardware.write_desired_pos( self._all_motor_ids[total_motor_id_mask], total_qpos[total_motor_id_mask])
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/robot/dynamixel_utils.py
robel/components/robot/dynamixel_utils.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Helper classes and methods for working with Dynamixel robots.""" from typing import Any, Dict, Iterable, Tuple class CalibrationMap: """Mapping of motor ID to (scale, offset) tuples.""" def __init__(self, mapping: Dict[int, Tuple[float, float]]): """Initializes a new calibration mapping.""" self.mapping = mapping def get_parameters(self, motor_ids: Iterable[int]) -> Dict[str, Any]: """Returns a dictionary of calibration parameters. Args: motor_ids: The motor IDs to get calibration parameters for. """ return { 'calib_scale': [self.mapping[i][0] for i in motor_ids], 'calib_offset': [self.mapping[i][1] for i in motor_ids], } def make_group_config(self, motor_ids: Iterable[int], **group_kwargs) -> Dict[str, Any]: """Creates a Dynamixel group configuration for the given motor IDs. Args: motor_ids: The motor IDs to create a group for. **group_kwargs: Additional configuration to set for the group. """ return { 'motor_ids': motor_ids, **self.get_parameters(motor_ids), **group_kwargs } def update_group_configs(self, configs: Dict[str, Any]): """Updates the calibration values for groups in the configuration. Args: config: The component configuration to update. *group_names: One or more group names to update. """ for group_config in configs.values(): if 'motor_ids' not in group_config: continue group_config.update(self.get_parameters(group_config['motor_ids']))
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/robot/dynamixel_robot_test.py
robel/components/robot/dynamixel_robot_test.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for RobotComponent and RobotGroupConfig.""" from typing import Any, Sequence from absl.testing import absltest from absl.testing.absltest import mock import numpy as np from robel.components.robot.dynamixel_robot import ( DynamixelRobotComponent, RobotState) from robel.utils.testing.mock_sim_scene import MockSimScene from robel.utils.testing.mock_time import patch_time class MockDynamixelClient: """Mock class for dynamixel_py.""" def __init__(self, all_motor_ids: Sequence[int], **unused_kwargs): self.motor_ids = np.array(sorted(all_motor_ids), dtype=int) self.qpos = np.zeros_like(self.motor_ids, dtype=np.float32) self.qvel = np.zeros_like(self.motor_ids, dtype=np.float32) self.current = np.zeros_like(self.motor_ids, dtype=np.float32) self.enabled = np.zeros_like(self.motor_ids, dtype=bool) self.is_connected = True def set_torque_enabled(self, motor_ids: Sequence[int], enabled: bool): assert self.is_connected indices = np.searchsorted(self.motor_ids, motor_ids) self.enabled[indices] = enabled def read_pos_vel_cur(self): assert self.is_connected return self.qpos, self.qvel, self.current def write_desired_pos(self, motor_ids: Sequence[int], qpos: Sequence[float]): assert self.is_connected indices = np.searchsorted(self.motor_ids, motor_ids) self.qpos[indices] = qpos def patch_dynamixel(test_fn): """Decorator to patch dynamixel_py with a mock.""" def patched_fn(self): DynamixelRobotComponent.DEVICE_CLIENTS.clear() with mock.patch( 'robel.components.robot.dynamixel_robot.DynamixelClient', new=MockDynamixelClient): test_fn(self) return patched_fn class RobotComponentTest(absltest.TestCase): """Unit test class for RobotComponent.""" @patch_dynamixel def test_get_state(self): """Tests querying the state of multiple groups.""" sim_scene = MockSimScene(nq=10) # type: Any robot = DynamixelRobotComponent( sim_scene, groups={ 'a': { 'qpos_indices': [0, 1, 3, 5], 'motor_ids': [10, 20, 12, 21], 'calib_scale': [0.5] * 4, 'calib_offset': [1] * 4, }, 'b': { 'qpos_indices': [2, 6], }, 'c': { 'motor_ids': [22, 24], }, }, device_path='test') dxl = DynamixelRobotComponent.DEVICE_CLIENTS['test'] dxl.write_desired_pos([10, 12, 20, 21, 22, 24], [1, 2, 3, 4, 5, 6]) a_state, b_state, c_state = robot.get_state(['a', 'b', 'c']) np.testing.assert_allclose(a_state.qpos, [1.5, 2.5, 2., 3.]) np.testing.assert_allclose(a_state.qvel, [0., 0., 0., 0.]) self.assertIsNone(b_state.qpos) self.assertIsNone(b_state.qvel) np.testing.assert_allclose(c_state.qpos, [5., 6.]) np.testing.assert_allclose(c_state.qvel, [0., 0.]) np.testing.assert_allclose(sim_scene.data.qpos, [1.5, 2.5, 0, 2., 0, 3., 0, 0, 0, 0]) @patch_dynamixel def test_step(self): """Tests stepping with an action for multiple groups.""" sim_scene = MockSimScene(nq=10, ctrl_range=[-1, 1]) # type: Any robot = DynamixelRobotComponent( sim_scene, groups={ 'a': { 'qpos_indices': [0, 1, 2], 'motor_ids': [10, 11, 12], 'calib_offset': [1] * 3, 'calib_scale': [-1] * 3, 'qpos_range': [(-0.5, 0.5)] * 3, }, 'b': { 'qpos_indices': [2, 3], }, }, device_path='test') with patch_time('robel.components.robot.hardware_robot.time'): robot.step({ 'a': np.array([.2, .4, .6]), 'b': np.array([.1, .3]), }) dxl = DynamixelRobotComponent.DEVICE_CLIENTS['test'] # type: Any np.testing.assert_allclose(dxl.qpos, [.9, .8, .7]) @patch_dynamixel def test_set_state(self): """Tests stepping with an action for multiple groups.""" sim_scene = MockSimScene(nq=10) # type: Any robot = DynamixelRobotComponent( sim_scene, groups={ 'a': { 'qpos_indices': [0, 1, 2], 'motor_ids': [10, 11, 12], 'calib_offset': [-1] * 3, 'qpos_range': [(-2.5, 2.5)] * 3, }, }, device_path='test') with patch_time('robel.components.robot.hardware_robot.time'): robot.set_state({ 'a': RobotState(qpos=np.array([1, 2, 3])), }) dxl = DynamixelRobotComponent.DEVICE_CLIENTS['test'] # type: Any np.testing.assert_allclose(dxl.qpos, [2, 3, 3.5]) @patch_dynamixel def test_engage_motors(self): """Tests engaging/disengaging subsets of motors.""" sim_scene = MockSimScene(nq=10) # type: Any robot = DynamixelRobotComponent( sim_scene, groups={ 'a': { 'motor_ids': [10, 11, 12], }, 'b': { 'motor_ids': [13, 14, 15], }, 'c': { 'motor_ids': [12, 15], } }, device_path='test') dxl = DynamixelRobotComponent.DEVICE_CLIENTS['test'] # type: Any np.testing.assert_array_equal(dxl.enabled, [False] * 6) robot.set_motors_engaged('a', True) np.testing.assert_array_equal(dxl.enabled, [True] * 3 + [False] * 3) robot.set_motors_engaged('c', False) np.testing.assert_array_equal(dxl.enabled, [True, True, False, False, False, False]) robot.set_motors_engaged(['a', 'b'], True) np.testing.assert_array_equal(dxl.enabled, [True] * 6) if __name__ == '__main__': absltest.main()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/robot/hardware_robot.py
robel/components/robot/hardware_robot.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Base logic for hardware robots.""" import abc import logging import time from typing import Iterable, Optional, Tuple import numpy as np from robel.components.robot.group_config import RobotGroupConfig from robel.components.robot.robot import RobotComponent, RobotState # Default tolerance for determining if the hardware has reached a state. DEFAULT_ERROR_TOL = 1. * np.pi / 180 class HardwareRobotGroupConfig(RobotGroupConfig): """Stores group configuration for a HardwareRobotComponent.""" def __init__(self, *args, calib_scale: Optional[Iterable[float]] = None, calib_offset: Optional[Iterable[float]] = None, **kwargs): """Initializes a new configuration for a HardwareRobotComponent group. Args: calib_scale: A scaling factor that is multipled with state to convert from component state space to hardware state space, and divides control to convert from hardware control space to component control space. calib_offset: An offset that is added to state to convert from component state space to hardware state space, and subtracted from control to convert from hardware control space to component control space. """ super().__init__(*args, **kwargs) self.calib_scale = None if calib_scale is not None: self.calib_scale = np.array(calib_scale, dtype=np.float32) self.calib_offset = None if calib_offset is not None: self.calib_offset = np.array(calib_offset, dtype=np.float32) class HardwareRobotComponent(RobotComponent, metaclass=abc.ABCMeta): """Base component for hardware robots.""" def __init__(self, *args, **kwargs): """Initializes the component.""" super().__init__(*args, **kwargs) self.reset_time() @property def is_hardware(self) -> bool: """Returns True if this is a hardware component.""" return True @property def time(self) -> float: """Returns the time (total sum of timesteps) since the last reset.""" return self._time def reset_time(self): """Resets the timer for the component.""" self._last_reset_time = time.time() self._time = 0 def _process_group(self, **config_kwargs) -> HardwareRobotGroupConfig: """Processes the configuration for a group.""" return HardwareRobotGroupConfig(self.sim_scene, **config_kwargs) def _calibrate_state(self, state: RobotState, group_config: HardwareRobotGroupConfig): """Converts the given state from hardware space to component space.""" # Calculate qpos' = qpos * scale + offset, and qvel' = qvel * scale. if group_config.calib_scale is not None: assert state.qpos.shape == group_config.calib_scale.shape assert state.qvel.shape == group_config.calib_scale.shape state.qpos *= group_config.calib_scale state.qvel *= group_config.calib_scale if group_config.calib_offset is not None: assert state.qpos.shape == group_config.calib_offset.shape # Only apply the offset to positions. state.qpos += group_config.calib_offset def _decalibrate_qpos(self, qpos: np.ndarray, group_config: HardwareRobotGroupConfig) -> np.ndarray: """Converts the given position from component to hardware space.""" # Calculate qpos' = (qpos - offset) / scale. if group_config.calib_offset is not None: assert qpos.shape == group_config.calib_offset.shape qpos = qpos - group_config.calib_offset if group_config.calib_scale is not None: assert qpos.shape == group_config.calib_scale.shape qpos = qpos / group_config.calib_scale return qpos def _synchronize_timestep(self, minimum_sleep: float = 1e-4): """Waits for one timestep to elapse.""" # Block the thread such that we've waited at least `step_duration` time # since the last call to `_synchronize_timestep`. time_since_reset = time.time() - self._last_reset_time elapsed_time = time_since_reset - self._time remaining_step_time = self.sim_scene.step_duration - elapsed_time if remaining_step_time > minimum_sleep: time.sleep(remaining_step_time) elif remaining_step_time < 0: logging.warning('Exceeded timestep by %0.4fs', -remaining_step_time) # Update the current time, relative to the last reset time. self._time = time.time() - self._last_reset_time def _wait_for_desired_states( self, desired_states: Iterable[Tuple[RobotGroupConfig, RobotState]], error_tol: float = DEFAULT_ERROR_TOL, timeout: float = 3.0, poll_interval: float = 0.25, initial_sleep: Optional[float] = 0.25, last_diff_tol: Optional[float] = DEFAULT_ERROR_TOL, last_diff_ticks: int = 2, ): """Polls the current state until it reaches the desired state. Args: desired_states: The desired states to wait for. error_tol: The maximum position difference within which the desired state is considered to have been reached. timeout: The maximum amount of time to wait, in seconds. poll_interval: The interval in seconds to poll the current state. initial_sleep: The initial time to sleep before polling. last_diff_tol: The maximum position difference between the current state and the last state at which motion is considered to be stopped, thus waiting will terminate early. last_diff_ticks: The number of cycles where the last difference tolerance check must pass for waiting to terminate early. """ # Define helper function to compare two state sets. def all_states_close(states_a, states_b, tol): all_close = True for state_a, state_b in zip(states_a, states_b): if not np.allclose(state_a.qpos, state_b.qpos, atol=tol): all_close = False break return all_close # Poll for the hardware move command to complete. configs, desired_states = zip(*desired_states) previous_states = None ticks_until_termination = last_diff_ticks start_time = time.time() if initial_sleep is not None and initial_sleep > 0: time.sleep(initial_sleep) while True: cur_states = self._get_group_states(configs) # Terminate if the current states have reached the desired states. if all_states_close(cur_states, desired_states, tol=error_tol): return # Terminate if the current state and previous state are the same. # i.e. the robot is unable to move further. if previous_states is not None and all_states_close( cur_states, previous_states, tol=last_diff_tol): if not ticks_until_termination: logging.warning( 'Robot stopped motion; terminating wait early.') return ticks_until_termination -= 1 else: ticks_until_termination = last_diff_ticks if time.time() - start_time > timeout: logging.warning('Reset timed out after %1.1fs', timeout) return previous_states = cur_states time.sleep(poll_interval) def _copy_to_simulation_state( self, group_states: Iterable[Tuple[RobotGroupConfig, RobotState]]): """Copies the given states to the simulation.""" for config, state in group_states: # Skip if this is a hardware-only group. if config.qpos_indices is None: continue if state.qpos is not None: self.sim_scene.data.qpos[config.qpos_indices] = state.qpos if state.qvel is not None: self.sim_scene.data.qvel[config.qvel_indices] = state.qvel # Recalculate forward dynamics. self.sim_scene.sim.forward() self.sim_scene.renderer.refresh_window()
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/robot/robot.py
robel/components/robot/robot.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Component implementation for reading and writing data to/from robots. This abstracts differences between a MuJoCo simulation and a hardware robot. """ from typing import Dict, Optional, Sequence, Tuple, Union import numpy as np from robel.components.base import BaseComponent from robel.components.robot.group_config import (ControlMode, RobotGroupConfig) class RobotState: """Data class that represents the state of the robot.""" def __init__(self, qpos: Optional[np.ndarray] = None, qvel: Optional[np.ndarray] = None, qacc: Optional[np.ndarray] = None): """Initializes a new state object. Args: qpos: The joint positions, in generalized joint coordinates. qvel: The velocities for each degree of freedom. qacc: The acceleration for each degree of freedom. This is returned by `get_state`. `reset` will ignore this property. """ self.qpos = qpos self.qvel = qvel self.qacc = qacc class RobotComponent(BaseComponent): """Component for reading sensor data and actuating robots.""" @property def time(self) -> float: """Returns the time (total sum of timesteps) since the last reset.""" return self.sim_scene.data.time def _process_group(self, **config_kwargs) -> RobotGroupConfig: """Processes the configuration for a group.""" return RobotGroupConfig(self.sim_scene, **config_kwargs) def step(self, control_groups: Dict[str, np.ndarray], denormalize: bool = True): """Runs one timestep of the robot for the given control. Examples: >>> robot.step({'dclaw': np.zeros(9)}) Args: control_groups: A dictionary of control group name to desired control value to command the robot for a single timestep. e.g. for a control group with position control, the control value is an array of joint positions (in radians). denormalize: If True, denormalizes the action from normalized action space [-1, 1] to the robot's control space. """ group_controls = [] for group_name, control_values in control_groups.items(): config = self.get_config(group_name) # Ignore if this is a hardware-only group. if not config.is_active: continue # Denormalize and enforce action bounds. if denormalize and not config.use_raw_actions: control_values = self._denormalize_action( control_values, config) control_values = self._apply_action_bounds(control_values, config) group_controls.append((config, control_values)) # Perform the control for all groups simultaneously. self._perform_timestep(group_controls) def set_state(self, state_groups: Dict[str, RobotState], **kwargs): """Moves the robot to the given initial state. Example: >>> robot.set_state({ ... 'dclaw': RobotState(qpos=np.zeros(9), qvel=np.zeros(9)), ... }) Args: state_groups: A mapping of control group name to desired position and velocity. **kwargs: Implementation-specific arguments. """ group_states = [] for group_name, state in state_groups.items(): config = self.get_config(group_name) # Clip the position and velocity to the configured bounds. clipped_state = RobotState(qpos=state.qpos, qvel=state.qvel) if clipped_state.qpos is not None and config.qpos_range is not None: clipped_state.qpos = np.clip(clipped_state.qpos, config.qpos_range[:, 0], config.qpos_range[:, 1]) if clipped_state.qvel is not None and config.qvel_range is not None: clipped_state.qvel = np.clip(clipped_state.qvel, config.qvel_range[:, 0], config.qvel_range[:, 1]) group_states.append((config, clipped_state)) # Set all states at once. self._set_group_states(group_states, **kwargs) def get_initial_state( self, groups: Union[str, Sequence[str]], ) -> Union[RobotState, Sequence[RobotState]]: """Returns the initial states for the given groups.""" if isinstance(groups, str): configs = [self.get_config(groups)] else: configs = [self.get_config(name) for name in groups] states = [] for config in configs: state = RobotState() # Return a blank state if this is a hardware-only group. if config.qpos_indices is None: states.append(state) continue state.qpos = self.sim_scene.init_qpos[config.qpos_indices].copy() state.qvel = self.sim_scene.init_qvel[config.qvel_indices].copy() states.append(state) if isinstance(groups, str): return states[0] return states def _get_group_states( self, configs: Sequence[RobotGroupConfig]) -> Sequence[RobotState]: """Returns the states for the given group configurations.""" states = [] for config in configs: state = RobotState() # Return a blank state if this is a hardware-only group. if config.qpos_indices is None: states.append(state) continue state.qpos = self.sim_scene.data.qpos[config.qpos_indices] state.qvel = self.sim_scene.data.qvel[config.qvel_indices] # qacc has the same dimensionality as qvel. state.qacc = self.sim_scene.data.qacc[config.qvel_indices] # Add observation noise to the state. self._apply_observation_noise(state, config) states.append(state) return states def _set_group_states( self, group_states: Sequence[Tuple[RobotGroupConfig, RobotState]]): """Sets the robot joints to the given states.""" for config, state in group_states: if config.qpos_indices is None: continue if state.qpos is not None: self.sim_scene.data.qpos[config.qpos_indices] = state.qpos if state.qvel is not None: self.sim_scene.data.qvel[config.qvel_indices] = state.qvel self.sim_scene.sim.forward() def _perform_timestep( self, group_controls: Sequence[Tuple[RobotGroupConfig, np.ndarray]]): """Applies the given control values to the robot.""" for config, control in group_controls: indices = config.actuator_indices assert len(indices) == len(control) self.sim_scene.data.ctrl[indices] = control # Advance the simulation by one timestep. self.sim_scene.advance() def _apply_observation_noise(self, state: RobotState, config: RobotGroupConfig): """Applies observation noise to the given state.""" if config.sim_observation_noise is None or self.random_state is None: return # Define the noise calculation. def noise(value_range: np.ndarray): amplitude = config.sim_observation_noise * np.ptp( value_range, axis=1) return amplitude * self.random_state.uniform( low=-0.5, high=0.5, size=value_range.shape[0]) if config.qpos_range is not None: state.qpos += noise(config.qpos_range) if config.qvel_range is not None: state.qvel += noise(config.qvel_range) def _denormalize_action(self, action: np.ndarray, config: RobotGroupConfig) -> np.ndarray: """Denormalizes the given action.""" if config.denormalize_center.shape != action.shape: raise ValueError( 'Action shape ({}) does not match actuator shape: ({})'.format( action.shape, config.denormalize_center.shape)) assert config.denormalize_range is not None action = np.clip(action, -1.0, 1.0) return config.denormalize_center + (action * config.denormalize_range) def _apply_action_bounds(self, action: np.ndarray, config: RobotGroupConfig) -> np.ndarray: """Clips the action using the given configuration. Args: action: The action to be applied to the robot. config: The group configuration that defines how the action is clipped. Returns: The clipped action. """ if config.control_mode == ControlMode.JOINT_POSITION: # Apply position bounds. if config.qpos_range is not None: action = np.clip(action, config.qpos_range[:, 0], config.qpos_range[:, 1]) # Apply velocity bounds. # NOTE: This uses the current simulation state to get the current # position. For hardware, this expects the hardware to update the # simulation state. if (config.qpos_indices is not None and config.qvel_range is not None): # Calculate the desired velocity using the current position. cur_pos = self.sim_scene.data.qpos[config.qpos_indices] desired_vel = ( (action - cur_pos) / self.sim_scene.step_duration) # Clip with the velocity bounds. desired_vel = np.clip(desired_vel, config.qvel_range[:, 0], config.qvel_range[:, 1]) action = cur_pos + desired_vel * self.sim_scene.step_duration elif config.control_mode == ControlMode.JOINT_VELOCITY: # Apply velocity bounds. if config.qvel_range is not None: action = np.clip(action, config.qvel_range[:, 0], config.qvel_range[:, 1]) return action
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/robot/group_config.py
robel/components/robot/group_config.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Configuration for a robot component group.""" import enum from typing import Iterable, Optional, Tuple import numpy as np from robel.simulation.sim_scene import SimScene class ControlMode(enum.Enum): """Control modes for a group.""" JOINT_TORQUE = 0 JOINT_POSITION = 1 JOINT_VELOCITY = 2 class RobotGroupConfig: """Stores group configuration for a RobotComponent.""" def __init__(self, sim_scene: SimScene, control_mode: ControlMode = ControlMode.JOINT_POSITION, qpos_indices: Optional[Iterable[int]] = None, qvel_indices: Optional[Iterable[int]] = None, actuator_indices: Optional[Iterable[int]] = None, qpos_range: Optional[Iterable[Tuple[float, float]]] = None, qvel_range: Optional[Iterable[Tuple[float, float]]] = None, actuator_range: Optional[Iterable[Tuple[float, float]]] = None, sim_observation_noise: float = 0.0, use_raw_actions: bool = False): """Initializes a new configuration for a RobotComponent group. Args: sim_scene: The simulation, used for validation purposes. control_mode: The control mode for the actuators. qpos_indices: The joint position indices that this group reads and writes to for the robot state. qvel_indices: The joint velocity indices that this group reads and writes to for the robot state. If not given, this defaults to `qpos_indices`. actuator_indices: The MuJoCo actuator indices that this group writes to for actions. If not provided, then will default one of the following depending on the control mode: - joint torque: None - joint position: `qpos_indices` - joint velocity: `qvel_indices` If None, this group will not write actions to the simulation. qpos_range: The position range, as a (lower, upper) tuple in generalized joint position space. This clamps the writable values for position state. e.g. For a hinge joint, this is measured in radians. qvel_range: The velocity range, as a (lower, upper) tuple in generalized joint velocity space. This bounds the writable values for position commands based on the difference from the current position. e.g. For a hinge joint, this is measured in radians/second. actuator_range: The actuator control range, as a (lower, upper) tuple in control space. The bounds the writable values for commands and defines the normalization range. If not provided, then will default to one of the following depending on control mode: - joint torque: None - joint position: `qpos_range` - joint velocity: `qvel_range` If None, the default range from the simulation is used. sim_observation_noise: The relative noise amplitude to add to state read from simulation. use_raw_actions: If True, doesn't denormalize actions from `step()`. """ self.control_mode = control_mode self.use_raw_actions = use_raw_actions # Ensure that the qpos indices are valid. self.qpos_indices = None if qpos_indices is not None: nq = sim_scene.model.nq assert all(-nq <= i < nq for i in qpos_indices), \ 'All qpos indices must be in [-{}, {}]'.format(nq, nq - 1) self.qpos_indices = np.array(qpos_indices, dtype=int) if qvel_indices is None: qvel_indices = qpos_indices # Ensure that the qvel indices are valid. self.qvel_indices = None if qvel_indices is not None: nv = sim_scene.model.nv assert all(-nv <= i < nv for i in qvel_indices), \ 'All qvel indices must be in [-{}, {}]'.format(nv, nv - 1) self.qvel_indices = np.array(qvel_indices, dtype=int) self.sim_observation_noise = sim_observation_noise # Convert the ranges to matrices. self.qpos_range = None if qpos_range is not None: assert all(lower < upper for lower, upper in qpos_range), \ 'Items in qpos_range must follow (lower, upper)' self.qpos_range = np.array(qpos_range, dtype=np.float32) assert self.qpos_range.shape == (len(self.qpos_indices), 2), \ 'qpos_range must match the length of qpos_indices' self.qvel_range = None if qvel_range is not None: assert all(lower < upper for lower, upper in qvel_range), \ 'Items in qvel_range must follow (lower, upper)' self.qvel_range = np.array(qvel_range, dtype=np.float32) assert self.qvel_range.shape == (len(self.qvel_indices), 2), \ 'qvel_range must match the length of qpos_indices' if actuator_indices is None: if self.control_mode == ControlMode.JOINT_POSITION: actuator_indices = self.qpos_indices elif self.control_mode == ControlMode.JOINT_VELOCITY: actuator_indices = self.qvel_indices # Ensure that the actuator indices are valid. self.actuator_indices = None if actuator_indices is not None: nu = sim_scene.model.nu assert all(-nu <= i < nu for i in actuator_indices), \ 'All actuator indices must be in [-{}, {}]'.format( nu, nu - 1) self.actuator_indices = np.array(actuator_indices, dtype=int) if actuator_range is None: if self.control_mode == ControlMode.JOINT_POSITION: actuator_range = self.qpos_range elif self.control_mode == ControlMode.JOINT_VELOCITY: actuator_range = self.qvel_range # Default to use the simulation's control range. if actuator_range is None and actuator_indices is not None: actuator_range = sim_scene.model.actuator_ctrlrange[ actuator_indices, :] self.actuator_range = None if actuator_range is not None: assert all(lower < upper for lower, upper in actuator_range), \ 'Items in actuator_range must follow (lower, upper)' self.actuator_range = np.array(actuator_range, dtype=np.float32) assert (self.actuator_range.shape == (len(self.actuator_indices), 2)), \ 'actuator_range must match the length of actuator_indices' # Calculate the denormalization center and range from the sim model. self.denormalize_center = None self.denormalize_range = None if self.actuator_range is not None: self.denormalize_center = np.mean(self.actuator_range, axis=1) self.denormalize_range = 0.5 * ( self.actuator_range[:, 1] - self.actuator_range[:, 0]) @property def is_active(self) -> bool: """Returns True if the group is not in use.""" return self.actuator_indices is not None
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/robot/dynamixel_client.py
robel/components/robot/dynamixel_client.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Communication using the DynamixelSDK.""" import atexit import logging import time from typing import Optional, Sequence, Union, Tuple import numpy as np PROTOCOL_VERSION = 2.0 # The following addresses assume XH motors. ADDR_TORQUE_ENABLE = 64 ADDR_GOAL_POSITION = 116 ADDR_PRESENT_POSITION = 132 ADDR_PRESENT_VELOCITY = 128 ADDR_PRESENT_CURRENT = 126 ADDR_PRESENT_POS_VEL_CUR = 126 # Data Byte Length LEN_PRESENT_POSITION = 4 LEN_PRESENT_VELOCITY = 4 LEN_PRESENT_CURRENT = 2 LEN_PRESENT_POS_VEL_CUR = 10 LEN_GOAL_POSITION = 4 DEFAULT_POS_SCALE = 2.0 * np.pi / 4096 # 0.088 degrees # See http://emanual.robotis.com/docs/en/dxl/x/xh430-v210/#goal-velocity DEFAULT_VEL_SCALE = 0.229 * 2.0 * np.pi / 60.0 # 0.229 rpm DEFAULT_CUR_SCALE = 1.34 def dynamixel_cleanup_handler(): """Cleanup function to ensure Dynamixels are disconnected properly.""" open_clients = list(DynamixelClient.OPEN_CLIENTS) for open_client in open_clients: if open_client.port_handler.is_using: logging.warning('Forcing client to close.') open_client.port_handler.is_using = False open_client.disconnect() def signed_to_unsigned(value: int, size: int) -> int: """Converts the given value to its unsigned representation.""" if value < 0: bit_size = 8 * size max_value = (1 << bit_size) - 1 value = max_value + value return value def unsigned_to_signed(value: int, size: int) -> int: """Converts the given value from its unsigned representation.""" bit_size = 8 * size if (value & (1 << (bit_size - 1))) != 0: value = -((1 << bit_size) - value) return value class DynamixelClient: """Client for communicating with Dynamixel motors. NOTE: This only supports Protocol 2. """ # The currently open clients. OPEN_CLIENTS = set() def __init__(self, motor_ids: Sequence[int], port: str = '/dev/ttyUSB0', baudrate: int = 1000000, lazy_connect: bool = False, pos_scale: Optional[float] = None, vel_scale: Optional[float] = None, cur_scale: Optional[float] = None): """Initializes a new client. Args: motor_ids: All motor IDs being used by the client. port: The Dynamixel device to talk to. e.g. - Linux: /dev/ttyUSB0 - Mac: /dev/tty.usbserial-* - Windows: COM1 baudrate: The Dynamixel baudrate to communicate with. lazy_connect: If True, automatically connects when calling a method that requires a connection, if not already connected. pos_scale: The scaling factor for the positions. This is motor-dependent. If not provided, uses the default scale. vel_scale: The scaling factor for the velocities. This is motor-dependent. If not provided uses the default scale. cur_scale: The scaling factor for the currents. This is motor-dependent. If not provided uses the default scale. """ import dynamixel_sdk self.dxl = dynamixel_sdk self.motor_ids = list(motor_ids) self.port_name = port self.baudrate = baudrate self.lazy_connect = lazy_connect self.port_handler = self.dxl.PortHandler(port) self.packet_handler = self.dxl.PacketHandler(PROTOCOL_VERSION) self._pos_vel_cur_reader = DynamixelPosVelCurReader( self, self.motor_ids, pos_scale=pos_scale if pos_scale is not None else DEFAULT_POS_SCALE, vel_scale=vel_scale if vel_scale is not None else DEFAULT_VEL_SCALE, cur_scale=cur_scale if cur_scale is not None else DEFAULT_CUR_SCALE, ) self._sync_writers = {} self.OPEN_CLIENTS.add(self) @property def is_connected(self) -> bool: return self.port_handler.is_open def connect(self): """Connects to the Dynamixel motors. NOTE: This should be called after all DynamixelClients on the same process are created. """ assert not self.is_connected, 'Client is already connected.' if self.port_handler.openPort(): logging.info('Succeeded to open port: %s', self.port_name) else: raise OSError( ('Failed to open port at {} (Check that the device is powered ' 'on and connected to your computer).').format(self.port_name)) if self.port_handler.setBaudRate(self.baudrate): logging.info('Succeeded to set baudrate to %d', self.baudrate) else: raise OSError( ('Failed to set the baudrate to {} (Ensure that the device was ' 'configured for this baudrate).').format(self.baudrate)) # Start with all motors enabled. self.set_torque_enabled(self.motor_ids, True) def disconnect(self): """Disconnects from the Dynamixel device.""" if not self.is_connected: return if self.port_handler.is_using: logging.error('Port handler in use; cannot disconnect.') return # Ensure motors are disabled at the end. self.set_torque_enabled(self.motor_ids, False, retries=0) self.port_handler.closePort() if self in self.OPEN_CLIENTS: self.OPEN_CLIENTS.remove(self) def set_torque_enabled(self, motor_ids: Sequence[int], enabled: bool, retries: int = -1, retry_interval: float = 0.25): """Sets whether torque is enabled for the motors. Args: motor_ids: The motor IDs to configure. enabled: Whether to engage or disengage the motors. retries: The number of times to retry. If this is <0, will retry forever. retry_interval: The number of seconds to wait between retries. """ remaining_ids = list(motor_ids) while remaining_ids: remaining_ids = self.write_byte( remaining_ids, int(enabled), ADDR_TORQUE_ENABLE, ) if remaining_ids: logging.error('Could not set torque %s for IDs: %s', 'enabled' if enabled else 'disabled', str(remaining_ids)) if retries == 0: break time.sleep(retry_interval) retries -= 1 def read_pos_vel_cur(self) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """Returns the current positions and velocities.""" return self._pos_vel_cur_reader.read() def write_desired_pos(self, motor_ids: Sequence[int], positions: np.ndarray): """Writes the given desired positions. Args: motor_ids: The motor IDs to write to. positions: The joint angles in radians to write. """ assert len(motor_ids) == len(positions) # Convert to Dynamixel position space. positions = positions / self._pos_vel_cur_reader.pos_scale self.sync_write(motor_ids, positions, ADDR_GOAL_POSITION, LEN_GOAL_POSITION) def write_byte( self, motor_ids: Sequence[int], value: int, address: int, ) -> Sequence[int]: """Writes a value to the motors. Args: motor_ids: The motor IDs to write to. value: The value to write to the control table. address: The control table address to write to. Returns: A list of IDs that were unsuccessful. """ self.check_connected() errored_ids = [] for motor_id in motor_ids: comm_result, dxl_error = self.packet_handler.write1ByteTxRx( self.port_handler, motor_id, address, value) success = self.handle_packet_result( comm_result, dxl_error, motor_id, context='write_byte') if not success: errored_ids.append(motor_id) return errored_ids def sync_write(self, motor_ids: Sequence[int], values: Sequence[Union[int, float]], address: int, size: int): """Writes values to a group of motors. Args: motor_ids: The motor IDs to write to. values: The values to write. address: The control table address to write to. size: The size of the control table value being written to. """ self.check_connected() key = (address, size) if key not in self._sync_writers: self._sync_writers[key] = self.dxl.GroupSyncWrite( self.port_handler, self.packet_handler, address, size) sync_writer = self._sync_writers[key] errored_ids = [] for motor_id, desired_pos in zip(motor_ids, values): value = signed_to_unsigned(int(desired_pos), size=size) value = value.to_bytes(size, byteorder='little') success = sync_writer.addParam(motor_id, value) if not success: errored_ids.append(motor_id) if errored_ids: logging.error('Sync write failed for: %s', str(errored_ids)) comm_result = sync_writer.txPacket() self.handle_packet_result(comm_result, context='sync_write') sync_writer.clearParam() def check_connected(self): """Ensures the robot is connected.""" if self.lazy_connect and not self.is_connected: self.connect() if not self.is_connected: raise OSError('Must call connect() first.') def handle_packet_result(self, comm_result: int, dxl_error: Optional[int] = None, dxl_id: Optional[int] = None, context: Optional[str] = None): """Handles the result from a communication request.""" error_message = None if comm_result != self.dxl.COMM_SUCCESS: error_message = self.packet_handler.getTxRxResult(comm_result) elif dxl_error is not None: error_message = self.packet_handler.getRxPacketError(dxl_error) if error_message: if dxl_id is not None: error_message = '[Motor ID: {}] {}'.format( dxl_id, error_message) if context is not None: error_message = '> {}: {}'.format(context, error_message) logging.error(error_message) return False return True def convert_to_unsigned(self, value: int, size: int) -> int: """Converts the given value to its unsigned representation.""" if value < 0: max_value = (1 << (8 * size)) - 1 value = max_value + value return value def __enter__(self): """Enables use as a context manager.""" if not self.is_connected: self.connect() return self def __exit__(self, *args): """Enables use as a context manager.""" self.disconnect() def __del__(self): """Automatically disconnect on destruction.""" self.disconnect() class DynamixelReader: """Reads data from Dynamixel motors. This wraps a GroupBulkRead from the DynamixelSDK. """ def __init__(self, client: DynamixelClient, motor_ids: Sequence[int], address: int, size: int): """Initializes a new reader.""" self.client = client self.motor_ids = motor_ids self.address = address self.size = size self._initialize_data() self.operation = self.client.dxl.GroupBulkRead(client.port_handler, client.packet_handler) for motor_id in motor_ids: success = self.operation.addParam(motor_id, address, size) if not success: raise OSError( '[Motor ID: {}] Could not add parameter to bulk read.' .format(motor_id)) def read(self, retries: int = 1): """Reads data from the motors.""" self.client.check_connected() success = False while not success and retries >= 0: comm_result = self.operation.txRxPacket() success = self.client.handle_packet_result( comm_result, context='read') retries -= 1 # If we failed, send a copy of the previous data. if not success: return self._get_data() errored_ids = [] for i, motor_id in enumerate(self.motor_ids): # Check if the data is available. available = self.operation.isAvailable(motor_id, self.address, self.size) if not available: errored_ids.append(motor_id) continue self._update_data(i, motor_id) if errored_ids: logging.error('Bulk read data is unavailable for: %s', str(errored_ids)) return self._get_data() def _initialize_data(self): """Initializes the cached data.""" self._data = np.zeros(len(self.motor_ids), dtype=np.float32) def _update_data(self, index: int, motor_id: int): """Updates the data index for the given motor ID.""" self._data[index] = self.operation.getData(motor_id, self.address, self.size) def _get_data(self): """Returns a copy of the data.""" return self._data.copy() class DynamixelPosVelCurReader(DynamixelReader): """Reads positions and velocities.""" def __init__(self, client: DynamixelClient, motor_ids: Sequence[int], pos_scale: float = 1.0, vel_scale: float = 1.0, cur_scale: float = 1.0): super().__init__( client, motor_ids, address=ADDR_PRESENT_POS_VEL_CUR, size=LEN_PRESENT_POS_VEL_CUR, ) self.pos_scale = pos_scale self.vel_scale = vel_scale self.cur_scale = cur_scale def _initialize_data(self): """Initializes the cached data.""" self._pos_data = np.zeros(len(self.motor_ids), dtype=np.float32) self._vel_data = np.zeros(len(self.motor_ids), dtype=np.float32) self._cur_data = np.zeros(len(self.motor_ids), dtype=np.float32) def _update_data(self, index: int, motor_id: int): """Updates the data index for the given motor ID.""" cur = self.operation.getData(motor_id, ADDR_PRESENT_CURRENT, LEN_PRESENT_CURRENT) vel = self.operation.getData(motor_id, ADDR_PRESENT_VELOCITY, LEN_PRESENT_VELOCITY) pos = self.operation.getData(motor_id, ADDR_PRESENT_POSITION, LEN_PRESENT_POSITION) cur = unsigned_to_signed(cur, size=2) vel = unsigned_to_signed(vel, size=4) pos = unsigned_to_signed(pos, size=4) self._pos_data[index] = float(pos) * self.pos_scale self._vel_data[index] = float(vel) * self.vel_scale self._cur_data[index] = float(cur) * self.cur_scale def _get_data(self): """Returns a copy of the data.""" return (self._pos_data.copy(), self._vel_data.copy(), self._cur_data.copy()) # Register global cleanup function. atexit.register(dynamixel_cleanup_handler) if __name__ == '__main__': import argparse import itertools parser = argparse.ArgumentParser() parser.add_argument( '-m', '--motors', required=True, help='Comma-separated list of motor IDs.') parser.add_argument( '-d', '--device', default='/dev/ttyUSB0', help='The Dynamixel device to connect to.') parser.add_argument( '-b', '--baud', default=1000000, help='The baudrate to connect with.') parsed_args = parser.parse_args() motors = [int(motor) for motor in parsed_args.motors.split(',')] way_points = [np.zeros(len(motors)), np.full(len(motors), np.pi)] with DynamixelClient(motors, parsed_args.device, parsed_args.baud) as dxl_client: for step in itertools.count(): if step > 0 and step % 50 == 0: way_point = way_points[(step // 100) % len(way_points)] print('Writing: {}'.format(way_point.tolist())) dxl_client.write_desired_pos(motors, way_point) read_start = time.time() pos_now, vel_now, cur_now = dxl_client.read_pos_vel_cur() if step % 5 == 0: print('[{}] Frequency: {:.2f} Hz'.format( step, 1.0 / (time.time() - read_start))) print('> Pos: {}'.format(pos_now.tolist())) print('> Vel: {}'.format(vel_now.tolist())) print('> Cur: {}'.format(cur_now.tolist()))
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false
google-research/robel
https://github.com/google-research/robel/blob/5b0fd3704629931712c6e0f7268ace1c2154dc83/robel/components/robot/__init__.py
robel/components/robot/__init__.py
# Copyright 2019 The ROBEL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Robot component module.""" from .robot import ControlMode, RobotState from .builder import RobotComponentBuilder
python
Apache-2.0
5b0fd3704629931712c6e0f7268ace1c2154dc83
2026-01-05T07:14:22.487637Z
false