Misc Wrappers¶
API Reference¶
masa.common.wrappers.RewardShapingWrapper ¶
Bases: ConstraintPersistentWrapper
Potential-based reward shaping wrapper for DFA-based safety constraints.
If the wrapped environment's constraint exposes a DFACostFn,
this wrapper constructs a shaped cost function ShapedCostFn
and updates the step cost entry inside info["constraint"]["step"] using:
The potential \(\Phi\) depends on impl:
"none": \(\Phi(q)=0\) (no shaping)"vi": approximate value iteration over DFA graph to derive potentials"cycle": graph-distance based shaping using a reverse-reachability BFS
Notes
This wrapper assumes the wrapped environment is already producing
info["automaton_state"] and a constraint monitor-like structure
info["constraint"]["step"]["cost"]. If these keys are absent, the
wrapper will fall back to default values (state 0 and cost 0.0).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
Env
|
Base environment to wrap. |
required |
gamma
|
float
|
Discount used in the shaping term \(\gamma \Phi(q_{t+1})\). |
0.99
|
impl
|
str
|
Shaping implementation. One of |
'none'
|
Attributes:
| Name | Type | Description |
|---|---|---|
shaped_cost_fn |
The cost function exposed by |
|
potential_fn |
Callable \(\Phi(q)\) mapping DFA states to potentials. |
|
_last_potential |
Potential at the previous step's DFA state. |
|
_gamma |
Shaping discount factor. |
|
_impl |
Shaping implementation identifier. |
Source code in masa/common/wrappers.py
cost_fn
property
¶
Expose the shaped cost function.
Returns:
| Type | Description |
|---|---|
|
The shaped cost function constructed in |
_setup_cost_fn ¶
Create shaped_cost_fn if DFA-based constraints are available.
If the underlying constraint exposes a DFACostFn,
constructs a ShapedCostFn. Otherwise, uses a
trivial zero-cost function.
Returns:
| Type | Description |
|---|---|
|
|
Source code in masa/common/wrappers.py
_setup_potential_fn ¶
Construct the potential function potential_fn for shaping.
For impl="none", potential_fn is identically zero.
For impl="vi", a small fixed number of value-iteration steps are run
over DFA states, treating accepting states as having a constant terminal
value and propagating backward through reachable transitions.
For impl="cycle", a reverse-graph BFS is used to find a "furthest"
state from the accepting set and then compute distances to that target,
yielding a shaping potential based on distance.
Returns:
| Type | Description |
|---|---|
|
|
|
|
intermediate tables such as |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If |
Source code in masa/common/wrappers.py
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 | |
reset ¶
Reset the environment and initialize shaping state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int | None
|
Random seed forwarded to the underlying environment. |
None
|
options
|
Dict[str, Any] | None
|
Reset options forwarded to the underlying environment. |
None
|
Returns:
| Type | Description |
|---|---|
|
A tuple |
Notes
This wrapper reads info["automaton_state"] to initialize the
previous potential _last_potential. If the key is missing,
it assumes DFA state 0.
Source code in masa/common/wrappers.py
step ¶
Step the environment and apply potential-based shaping to the step cost.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
action
|
Any
|
Action forwarded to the underlying environment. |
required |
Returns:
| Type | Description |
|---|---|
|
A 5-tuple |
Side effects
Updates info["constraint"]["step"]["cost"] in-place with the shaped
cost and updates _last_potential.
Notes
If the underlying info does not contain constraint metrics,
this method assumes an unshaped step cost of 0.0 and will
still attempt to write back into info["constraint"]["step"].
Source code in masa/common/wrappers.py
masa.common.wrappers.NormWrapper ¶
NormWrapper(env: Env, norm_obs: bool = True, norm_rew: bool = True, training: bool = True, clip_obs: float = 10.0, clip_rew: float = 10.0, gamma: float = 0.99, eps: float = 1e-08)
Bases: ConstraintPersistentWrapper
Normalize observations and/or rewards for a single (non-vectorized) environment.
This wrapper maintains running mean/variance estimates and applies:
- Observation normalization (elementwise): \((x - \mu) / \sqrt{\sigma^2 + \varepsilon}\)
- Reward normalization using a running variance estimate over discounted returns.
This wrapper is intended for non-vectorized environments. For vectorized
environments, use VecNormWrapper.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
Env
|
Base (non-vectorized) environment. |
required |
norm_obs
|
bool
|
Whether to normalize observations. |
True
|
norm_rew
|
bool
|
Whether to normalize rewards. |
True
|
training
|
bool
|
If |
True
|
clip_obs
|
float
|
Clip normalized observations to |
10.0
|
clip_rew
|
float
|
Clip normalized rewards to |
10.0
|
gamma
|
float
|
Discount factor for the running return used in reward normalization. |
0.99
|
eps
|
float
|
Small constant \(\varepsilon\) for numerical stability. |
1e-08
|
Attributes:
| Name | Type | Description |
|---|---|---|
norm_obs |
See Args. |
|
norm_rew |
See Args. |
|
training |
See Args. |
|
clip_obs |
See Args. |
|
clip_rew |
See Args. |
|
gamma |
See Args. |
|
eps |
See Args. |
|
obs_rms |
|
|
rew_rms |
|
|
returns |
Discounted return accumulator used for reward normalization. |
Source code in masa/common/wrappers.py
_normalize_obs ¶
Normalize (and clip) a single observation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obs
|
ndarray
|
Raw observation. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Normalized observation. |
Source code in masa/common/wrappers.py
_normalize_rew ¶
Normalize (and clip) a single reward.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rew
|
float
|
Raw reward. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Normalized reward. |
Source code in masa/common/wrappers.py
reset ¶
Reset the environment and (optionally) update normalization statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int | None
|
Random seed forwarded to the underlying environment. |
None
|
options
|
Dict[str, Any] | None
|
Reset options forwarded to the underlying environment. |
None
|
Returns:
| Type | Description |
|---|---|
|
A tuple |
Source code in masa/common/wrappers.py
step ¶
Step the environment and apply observation/reward normalization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
action
|
Action forwarded to the underlying environment. |
required |
Returns:
| Type | Description |
|---|---|
|
A 5-tuple |
|
|
|
Source code in masa/common/wrappers.py
masa.common.wrappers.OneHotObsWrapper ¶
Bases: ConstraintPersistentObsWrapper
One-hot encode gymnasium.spaces.Discrete observations.
Supported input observation spaces:
gymnasium.spaces.Discrete: returns a 1D one-hot vector of lengthn.gymnasium.spaces.Dict: one-hot encodes any Discrete subspaces and passes through non-Discrete subspaces.- Otherwise: passes observations through unchanged.
The wrapper updates gymnasium.Env.observation_space accordingly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
Env
|
Base environment to wrap. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
_orig_obs_space |
The original observation space of the wrapped env. |
|
_mode |
One of |
Source code in masa/common/wrappers.py
observation_space
instance-attribute
¶
_one_hot_scalar
staticmethod
¶
One-hot encode an integer index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx
|
int
|
Index in |
required |
n
|
int
|
Vector length. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A float32 vector |
Source code in masa/common/wrappers.py
_get_obs ¶
Transform an observation according to the wrapper's configured mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obs
|
Union[int, Dict[str, Any], ndarray]
|
Raw observation. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
One-hot encoded observation (or dict containing one-hot fields) when applicable, |
ndarray
|
otherwise the original observation. |
Source code in masa/common/wrappers.py
masa.common.wrappers.FlattenDictObsWrapper ¶
Bases: ConstraintPersistentObsWrapper
Flatten a gymnasium.spaces.Dict observation into a 1D Box.
The wrapper creates a deterministic key ordering (alphabetical) and concatenates each sub-observation in that order.
Supported Dict subspaces:
gymnasium.spaces.Box: flattened viareshape(-1).gymnasium.spaces.Discrete: represented as a length-none-hot segment for the purposes of bounds (note: the current implementation of_get_obsexpects Box values; see Notes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
Env
|
Base environment with Dict observation space. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
_orig_obs_space |
Original Dict observation space. |
|
_key_slices |
dict[str, slice]
|
Mapping from key to slice in the flattened vector. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the underlying observation space is not a Dict, or contains unsupported subspaces. |
Source code in masa/common/wrappers.py
observation_space
instance-attribute
¶
_get_obs ¶
Flatten a Dict observation into a 1D vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obs
|
Dict[str, Any]
|
Dict observation keyed the same way as the original Dict space. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A 1D float32 array created by concatenating flattened sub-observations. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If any subspace is not a Box. |
Notes
Although the constructor supports Discrete subspaces when building bounds, this implementation currently enforces Box-only subspaces at runtime.
Source code in masa/common/wrappers.py
masa.common.pettingzoo_record_video.RecordVideoParallel ¶
RecordVideoParallel(env: ParallelEnv, video_folder: str, episode_trigger: Callable[[int], bool] | None = None, step_trigger: Callable[[int], bool] | None = None, video_length: int = 0, name_prefix: str = 'rl-video', fps: int | None = None, disable_logger: bool = True, gc_trigger: Callable[[int], bool] | None = lambda episode: True)
Bases: BaseParallelWrapper
Record videos from a PettingZoo parallel environment.
Source code in masa/common/pettingzoo_record_video.py
video_length
instance-attribute
¶
_capture_frame ¶
Source code in masa/common/pettingzoo_record_video.py
reset ¶
reset(seed: int | None = None, options: dict | None = None) -> tuple[dict[AgentID, ObsType], dict[AgentID, dict]]
Source code in masa/common/pettingzoo_record_video.py
step ¶
step(actions: dict[AgentID, ActionType]) -> tuple[dict[AgentID, ObsType], dict[AgentID, float], dict[AgentID, bool], dict[AgentID, bool], dict[AgentID, dict]]
Source code in masa/common/pettingzoo_record_video.py
render ¶
Source code in masa/common/pettingzoo_record_video.py
close ¶
start_recording ¶
stop_recording ¶
Source code in masa/common/pettingzoo_record_video.py
masa.common.pettingzoo_record_video.RecordVideoAEC ¶
RecordVideoAEC(env: AECEnv, video_folder: str, episode_trigger: Callable[[int], bool] | None = None, step_trigger: Callable[[int], bool] | None = None, video_length: int = 0, name_prefix: str = 'rl-video', fps: int | None = None, disable_logger: bool = True, gc_trigger: Callable[[int], bool] | None = lambda episode: True)
Bases: BaseWrapper
Record videos from a PettingZoo AEC environment.