Linear Temporal Logic (LTL) Safety Constraint¶
Monitor API¶
masa.common.constraints.ltl_safety.LTLSafety ¶
Bases: Constraint
DFA-based safety monitor.
This monitor uses masa.common.ltl.dfa_to_costfn to obtain a stateful
cost function that:
- tracks the current DFA state,
- returns a scalar cost indicating safety violation.
A common convention is binary step cost:
The episode is considered satisfied iff no unsafe event occurs:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dfa
|
DFA
|
DFA describing the safety property. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
cost_fn |
Stateful cost object derived from the DFA (exposes DFA state). |
|
safe |
Boolean flag tracking whether any violation has occurred. |
|
step_cost |
Most recent step cost. |
|
total_unsafe |
Count of unsafe steps (as floats, per current code). |
Source code in masa/common/constraints/ltl_safety.py
reset ¶
update ¶
Update the DFA-cost state and safety flags.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
Iterable[str]
|
Iterable of atomic propositions true at the current step. |
required |
Source code in masa/common/constraints/ltl_safety.py
get_automaton_state ¶
get_dfa ¶
satisfied ¶
episode_metric ¶
End-of-episode metrics.
Returns:
| Type | Description |
|---|---|
Dict[str, float]
|
Dict containing: |
Dict[str, float]
|
|
Dict[str, float]
|
|
Source code in masa/common/constraints/ltl_safety.py
step_metric ¶
Per-step metrics.
Returns:
| Type | Description |
|---|---|
Dict[str, float]
|
Dict containing: |
Dict[str, float]
|
|
Dict[str, float]
|
|
Source code in masa/common/constraints/ltl_safety.py
masa.common.constraints.ltl_safety.LTLSafetyEnv ¶
Bases: BaseConstraintEnv
Gymnasium wrapper that monitors LTL safety and augments observations.
This wrapper attaches LTLSafety to the environment and augments the
observation space to include the current DFA state, enabling model-free
learning over the product.
The representation of the product observation is controlled by obs_type:
obs_type="discrete": Requires the underlying observation space to begymnasium.spaces.Discrete. The observation becomes a single discrete index encoding both base state and automaton state:
$$ \text{obs}_\otimes = q_\text{idx} \cdot n + s. $$
-
obs_type="box": Produces agymnasium.spaces.Boxobservation by concatenating a one-hot encoding of the automaton state. -
If the base space is
Box(1-D only), the result isconcat([obs, one_hot(q)]). -
If the base space is
Discrete, the result isconcat([one_hot(s), one_hot(q)]). -
obs_type="dict": Produces agymnasium.spaces.Dictobservation with keys:"orig"and"automaton"."automaton"is always Discrete;"orig"matches the original observation (forDiscrete) or the original vector (for 1-DBox). For originalDict, this wrapper adds an"automaton"key to the existing dict.
The wrapper also writes info["automaton_state"] each step/reset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
Env
|
Base environment (must be a |
required |
dfa
|
'DFA'
|
DFA for safety monitoring. Defaults to a dummy DFA. |
make_dfa()
|
obs_type
|
str
|
One of |
'discrete'
|
**kw
|
Any
|
Extra keyword arguments forwarded to |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ValueError
|
If |
TypeError
|
If an incompatible configuration is requested (e.g.
|
TypeError
|
If |
Source code in masa/common/constraints/ltl_safety.py
_automaton_states_idx
instance-attribute
¶
observation_space
instance-attribute
¶
_make_augmented_obs_space ¶
Construct the augmented observation space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
orig
|
Space
|
Original observation space of the wrapped environment. |
required |
Returns:
| Type | Description |
|---|---|
Space
|
A new observation space that includes the automaton state. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the observation space type is unsupported, or if a Box space is not 1-D. |
Source code in masa/common/constraints/ltl_safety.py
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 | |
_one_hot ¶
One-hot encode an index into a vector of length dim.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx
|
int
|
index to encomde. |
required |
dim
|
int
|
length of one-hot encoding. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A 1-D numpy array of shape |
ndarray
|
one-hot encoding. If |
Source code in masa/common/constraints/ltl_safety.py
_augment_obs ¶
Augment a base observation with the current automaton state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obs
|
Any
|
Base observation returned by the wrapped environment. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Augmented observation matching |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the base observation does not match the expected type/shape implied by the observation space. |
RuntimeError
|
If the wrapper is in an unexpected observation-space state. |
Source code in masa/common/constraints/ltl_safety.py
reset ¶
Source code in masa/common/constraints/ltl_safety.py
step ¶
Source code in masa/common/constraints/ltl_safety.py
Helpers¶
masa.common.constraints.ltl_safety.create_product_transition_matrix ¶
create_product_transition_matrix(n_states: int, n_actions: int, transition_matrix: ndarray, dfa: DFA, label_fn: LabelFn) -> np.ndarray
Create the dense product transition tensor for (MDP × DFA).
Given a dense base transition tensor of shape (n_states, n_states, n_actions),
this constructs the corresponding dense product transition tensor of shape
(n_states * n_aut, n_states * n_aut, n_actions).
The DFA transition is computed from labels of the current base state s
(i.e., it applies \(q' = \delta(q, L(s))\)), which matches the product
formulation used in the code:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_states
|
int
|
Number of base MDP states. |
required |
n_actions
|
int
|
Number of actions. |
required |
transition_matrix
|
ndarray
|
Dense base transition tensor with shape
|
required |
dfa
|
DFA
|
Deterministic finite automaton. |
required |
label_fn
|
LabelFn
|
Labelling function |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Dense product transition tensor with shape |
ndarray
|
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the provided transition matrix does not have the expected shape. |
Source code in masa/common/constraints/ltl_safety.py
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | |
masa.common.constraints.ltl_safety.create_product_successor_states_and_probabilities ¶
create_product_successor_states_and_probabilities(n_states: int, n_actions: int, successor_states: Dict[State, List[State]], probabilities: Dict[Tuple[State, Action], ndarray], dfa: DFA, label_fn: LabelFn) -> Tuple[Dict[ProdState, List[ProdState]], Dict[Tuple[ProdState, Action], np.ndarray]]
Create a sparse product successor representation (MDP x DFA).
This constructs:
prod_successor_states: mappingprod_state -> list[prod_state_next]prod_probabilities: mapping(prod_state, action) -> probs
where probability vectors are copied from the base representation and the automaton transition is determined by the current base state labels.
Product state indexing ~~~~~~~~~~~~~~~~~~~~~~ The code uses the encoding:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_states
|
int
|
Number of base MDP states. |
required |
n_actions
|
int
|
Number of actions. |
required |
successor_states
|
Dict[State, List[State]]
|
Mapping |
required |
probabilities
|
Dict[Tuple[State, Action], ndarray]
|
Mapping |
required |
dfa
|
DFA
|
Deterministic finite automaton. |
required |
label_fn
|
LabelFn
|
Labelling function |
required |
Returns:
| Type | Description |
|---|---|
Dict[ProdState, List[ProdState]]
|
A tuple |
Dict[Tuple[ProdState, Action], ndarray]
|
product dynamics. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If |
Source code in masa/common/constraints/ltl_safety.py
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 | |
masa.common.constraints.ltl_safety.create_product_label_fn ¶
Create a label function on product states indicating DFA acceptance.
The returned labelling function maps a product-state index to {"accepting"}
if the embedded DFA state is accepting, and to the empty set otherwise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_states
|
int
|
Number of base states used in product encoding. |
required |
dfa
|
DFA
|
DFA defining which automaton indices are accepting. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[ProdState], Set[str]]
|
A callable |
Callable[[ProdState], Set[str]]
|
such as:: cost = 1.0 if "accepting" in labels else 0.0 |
Source code in masa/common/constraints/ltl_safety.py
Monitoring versus enforcement¶
LTLSafetyEnv monitors a safety DFA and augments the observation with the DFA
state.
It does not itself restrict the agent's actions.
In MASA's safety interface, accepting DFA states recognize bad prefixes: entering an accepting state means that the safety property has been violated, rather than that a task has been successfully completed.
For enforcement, wrap
with either:
or:
Both wrappers use the same winning region.
- Preemptive shielding exposes a safe-action mask before the policy chooses.
- Postposed shielding checks a proposed action and replaces it only when the proposal is unsafe.
See Winning-region safety-game shielding for the safety-game construction, guarantee assumptions, examples, replacement strategies, and API reference.
Monitor timing¶
The live LTL monitor consumes the initial state's labels during reset().
After each environment transition, it consumes the labels of the newly returned state.
Therefore, if the current product state is \((q,s)\), the next monitor state after a physical transition to \(s'\) is
The winning-region shield follows this timing when constructing its product successors.
When using the product-construction helpers below independently, check their documented label timing rather than assuming that every product representation uses the same convention.