Skip to content

unaiverse.hsm.state

This module holds State, a node of a HybridStateMachine. A state has a unique name and three optional properties that change how the machine behaves while it sits there: (1) an inner Action that runs at every pass of act(), (2) a blocking flag that decides whether act() stops when the machine enters the state and (3) a waiting time during which only requested actions can fire. A state can also carry a message that the machine prints on the user log channel when it enters the state. The JSON form of a state is described in the states section of the behavior format and the role of states in a behavior in Behaviors.

A developer rarely creates a State directly. HybridStateMachine.add_state(), add_transit() and load() create the states and keep them in hsm.states. Reading a state is common in custom code that inspects the machine:

state = agent.behav.get_state()
if state is not None and state.must_wait():
    print(f"{state.name}: {state.get_time_passed():.1f} s of {state.waiting_time} s")

A world can also adjust a state after building it in code, as the example worlds do:

behav.states["eval_time"].waiting_time = 3

State

State(name: str, idx: int = -1, action: Action | None = None, waiting_time: float = 0.0, blocking: bool = True, msg: str | None = None)
Source code in unaiverse/hsm/state.py
def __init__(self, name: str, idx: int = -1, action: Action | None = None, waiting_time: float = 0.,
             blocking: bool = True, msg: str | None = None):
    """Initializes a `State` object, which is a fundamental component of a Hybrid State Machine. A state can be
    associated with an optional `Action` to be performed, a unique name, and various properties like waiting time
    and blocking behavior. It also stores a human-readable message.

    Args:
        name: The unique name of the state.
        idx: A unique ID for the state.
        action: An optional `Action` object to be executed when the state is entered.
        waiting_time: umber of seconds to wait in the current state before acting.
        blocking: A boolean indicating if the state blocks execution until a condition is met.
        msg: An optional message associated with the state.
    """
    self.name = name  # Name of the state (must be unique)
    self.action = action  # Inner state action (it can be None)
    self.id = idx  # Unique ID of the state (-1 if not needed)
    self.waiting_time = waiting_time  # Number of seconds to wait in the current state before acting
    self.starting_time = 0.
    self.blocking = blocking
    self.msg = msg  # Human-readable message associated to this instance of state
    self.msg_printed = False
    self.state_machine = None

    # Fix UNICODE chars
    if self.msg is not None:
        self.msg = html.unescape(self.msg)

    # Message parts replaced by wildcards (commonly assumed to be in the format <value>)
    self.wildcards = {}  # Value-to-value (es: <playlist> to this:and:this)
    self.msg_with_wildcards = self.msg

    if self.name in Custom.NOT_ALLOWED_STATE_NAMES:
        log.critical(f"Invalid state name (not allowed): {self.name}")

A node of a state machine. The machine creates the object and links it to itself with set_state_machine().

Argument Type Default Meaning
name str required The unique name of the state in the machine. A name in Custom.NOT_ALLOWED_STATE_NAMES (that is "all") raises GenException.
idx int -1 The numeric id of the state. The machine passes the index of the state in its list.
action Action \| None None The inner action.
waiting_time float 0. The JSON field time_to_wait_before_acting in seconds.
blocking bool True The JSON field blocking.
msg str \| None None The message of the state. HTML entities are decoded (&#128075; becomes the character it encodes).
Attribute Type Meaning
name, id, action, waiting_time, blocking, msg The constructor arguments. msg holds the message after the replacement of the wildcards.
msg_with_wildcards str \| None The message as written in the behavior.
starting_time float The time.perf_counter() value at the first call after entering the state. It is 0. until then.
msg_printed bool Whether the message was printed since the machine entered the state.
state_machine HybridStateMachine \| None The machine that owns the state.
wildcards dict The same dictionary object that holds the wildcards of the machine.

The machine awaits the state itself (await state()) at every pass of act_states(). At the first call after entering the state the call records starting_time and prints the message once through the user log channel. The message ends with 🔴 for a blocking state and with 🟢 for a non-blocking one when the machine has the option highlight_blocking_states_in_messages. Every call then runs the inner action on the system interaction of the agent after resetting the progress of that interaction. The call returns the code of the action (0, 1 or 2) and None for a state without action. The machine ignores this value.

set_state_machine

set_state_machine(hsm: HybridStateMachine) -> None
Source code in unaiverse/hsm/state.py
def set_state_machine(self, hsm: "HybridStateMachine") -> None:
    """Registers the parent state machine that owns this state."""
    self.state_machine = hsm
    self.set_wildcards(hsm.get_wildcards())
    if self.action is not None:
        self.action.set_state_machine(hsm)

Links the state to the machine hsm, gives it the wildcards of hsm and links the inner action to the same machine. add_state() calls it. Returns None.

set_msg

set_msg(msg: str | None) -> None
Source code in unaiverse/hsm/state.py
def set_msg(self, msg: str | None) -> None:
    """Sets the message associated to this state."""

    if msg is not None:
        self.msg = html.unescape(msg)
        self.msg_with_wildcards = self.msg
    else:
        self.msg = None
        self.msg_with_wildcards = None

Replaces the message of the state with msg after decoding its HTML entities. Both msg and msg_with_wildcards take the new value and None removes the message. The machine calls it when it generates or restores messages in debug mode. Returns None.

must_wait

must_wait() -> bool
Source code in unaiverse/hsm/state.py
def must_wait(self) -> bool:
    """Checks if the state needs to wait before it can transition. It compares the current elapsed time since
    entering the state with the configured `waiting_time`. If the elapsed time is less than the waiting time,
    it returns `True`, indicating the state is still in a waiting period.

    Returns:
        A boolean indicating whether the state is currently waiting.
    """
    if self.waiting_time > 0.:
        if (time.perf_counter() - self.starting_time) >= self.waiting_time:
            return False
        else:
            log.debug(f"Time passing: {(time.perf_counter() - self.starting_time)} seconds")
            return True
    else:
        return False

Returns True while less than waiting_time seconds have passed since starting_time. A state with waiting_time equal to 0 or less never waits. HybridStateMachine.must_wait() calls it for the current state.

to_dict

to_dict() -> dict
Source code in unaiverse/hsm/state.py
def to_dict(self) -> dict:
    """Converts the state's properties into a dict. This method is useful for serialization, allowing the state to
    be easily stored or transmitted.

    Returns:
        A dict containing the state's properties.
    """
    return {
        "action": self.action.name if self.action is not None else None,
        "action_kwargs": self.action.args if self.action is not None else {},
        "msg": self.msg.encode("ascii",
                               "xmlcharrefreplace").decode("ascii") if self.msg is not None else None,
        "blocking": self.blocking,
        Custom.TIME_TO_WAIT_BEFORE_ACTING_ARG_NAMES[0]: self.waiting_time
    }

Returns the JSON form of the state as a dictionary with the keys action, action_kwargs, msg, blocking and time_to_wait_before_acting. The message is ASCII with the other characters written as HTML entities. The arguments are those of the action after the replacement of the wildcards. The message of the inner action is not part of the result.

{"action": "nop", "action_kwargs": {"message": "Exam started"}, "msg": "Exam &#128221;",
 "blocking": True, "time_to_wait_before_acting": 3.0}

has_action

has_action() -> bool
Source code in unaiverse/hsm/state.py
def has_action(self) -> bool:
    """A simple getter that checks if an action is associated with the state.

    Returns:
        True if an action is set, False otherwise.
    """
    return self.action is not None

Returns True when the state has an inner action.

get_starting_time

get_starting_time() -> float
Source code in unaiverse/hsm/state.py
def get_starting_time(self) -> float:
    """Retrieves the timestamp when the state's execution began. This is used to calculate the elapsed waiting time.

    Returns:
        A float representing the starting time.
    """
    return self.starting_time

Returns starting_time, the time.perf_counter() value recorded at the first call after entering the state. The value is 0. before that call.

get_time_passed

get_time_passed()
Source code in unaiverse/hsm/state.py
def get_time_passed(self):
    return (time.perf_counter() - self.starting_time) if self.starting_time > 0 else -1.

Returns the seconds passed since starting_time. The result is -1. when the state has not been entered yet.

reset

reset(reset_message_printing: bool = True) -> None
Source code in unaiverse/hsm/state.py
def reset(self, reset_message_printing: bool = True) -> None:
    """Resets the state's internal counters. This method is typically called when re-entering a state. It sets the
    `starting_time` to zero and also resets the associated action's step counter if an action exists.
    """
    self.starting_time = 0.
    if reset_message_printing:
        self.msg_printed = False
        if self.action is not None:
            self.action.reset_msg_printing()
    if self.action is not None:
        self.action.system_interaction.reset_state()

Clears starting_time and resets the progress of the system interaction of the inner action. The default reset_message_printing=True also lets the message of the state and of its inner action be printed again. The machine calls it on the state it leaves after each completed transition and passes False for a self-loop. Returns None.

set_blocking

set_blocking(blocking: bool) -> None
Source code in unaiverse/hsm/state.py
def set_blocking(self, blocking: bool) -> None:
    """Sets the blocking status of the state. A blocking state will prevent the state machine from transitioning to
    the next state until the action is fully completed.

    Args:
        blocking: A boolean value to set the blocking status.
    """
    self.blocking = blocking

Changes the attribute blocking to the given value. Returns None.

set_wildcards

set_wildcards(wildcards: dict[str, str | float | int | list[str]] | None) -> None
Source code in unaiverse/hsm/state.py
def set_wildcards(self, wildcards: dict[str, str | float | int | list[str]] | None) -> None:
    """Replaces wildcard dictionary.

    Args:
        wildcards: A dictionary mapping wildcard placeholders to their concrete values.
    """
    self.wildcards = wildcards if wildcards is not None else {}
    if self.action is not None:
        self.action.set_wildcards(self.wildcards)

Replaces the dictionary of wildcards of the state and of its inner action with wildcards (an empty dictionary for None). The replacement itself happens in apply_wildcards(). Returns None.

apply_wildcards

apply_wildcards() -> None
Source code in unaiverse/hsm/state.py
def apply_wildcards(self) -> None:
    """A method that replaces placeholder values (wildcards) in the state message.
    It handles both single-value and list-based wildcards.
    """
    if self.msg_with_wildcards is None:
        self.msg_with_wildcards = self.msg
    else:
        self.msg = self.msg_with_wildcards

    if self.msg is not None:
        for wildcard_from, wildcard_to in self.wildcards.items():
            self.msg = self.msg.replace(wildcard_from, str(wildcard_to))

    if self.action is not None:
        self.action.apply_wildcards()

Rebuilds msg from msg_with_wildcards and replaces in it every wildcard with str() of its value. The method then calls apply_wildcards() on the inner action. HybridStateMachine.apply_wildcards() calls it on every state. Returns None.