Skip to content

Problem definition

GymProblem describes a problem as an Action-Evolution Petri Net and runs training and testing on it.

gympn.simulator.GymProblem

Bases: SimProblem

A decision problem GymProblem, which consists of a collection of simulation variables SimVar, a collection of simulation events SimEvent, and a collection of actions SimAction. The simulation has a time and a marking of SimVar. A marking is an assignment of values to SimVar variables (also see SimVar). The difference between a normal Python variable and a SimVar is that: (1) a SimVar can have multiple values; and (2) these values have a simulation time at which they become available. A SimEvent is a function that takes SimVar values as input and produces SimVar values (also see SimEvent). The difference with normal Python functions is that events can happen whenever its incoming SimVar parameters have a value. If a SimVar parameter has multiple values, it can happen on any of these values.

Additionally, the GymProblem has a collection of actions SimAction. An action is a function that takes SimVar values as input and produces SimVar values according to a policy. The policy is defined as part of the action. The difference with events is that actions are deterministic and can only happen when its incoming SimVar parameters have a value.

To be DRL-ready, a Gym environment is instantiated for each SimAction present in the network. This means that every environment trains a separate agent that is solely responsible for one action. The environment is responsible for the interaction between the agent and the simulation model. The agent receives the state of the simulation model and returns an action. The environment then executes the action on the simulation model and returns the new state to the agent.

Future work: SingleAgentGymProblem should train a single agent for all the actions in the network.

:param debugging: if set to True, produces more information for debugging purposes (defaults to True).

add_gym_var

add_gym_var(name, attributes: dict, priority=lambda token: token.time)

Creates a new GymVar with the specified name as identifier and the specified dictionary of token attributes. Token attributes specify what is the expected structure of the tokens in the place, and are expected to have string keys and numerical values. Adds the GymVar to the problem and returns it.

Parameters:

Name Type Description Default
name

a name for the SimVar.

required
attributes dict

a dictionary of token attributes

required
priority

a function that takes a token as input and returns a value that is used to sort the tokens in the order in which they will be processed (lower values first). The default is processing in the order of the time of the token.

lambda token: time

Returns:

Type Description

a SimVar with the specified name as identifier.

add_var

add_var(name, initial=None, var_attributes=None, categorical_values=None)

Creates a new SimVar with the specified name and initial value. Adds the SimVar to the problem and returns it.

Parameters:

Name Type Description Default
name

the identifier of the SimVar.

required
initial

the initial value of the SimVar.

None
var_attributes

the set of attributes that characterize the tokens in the Simvar

None
categorical_values

a dictionary containing var attributes as names and a list [min, max, step] specifying the range and step (necessary for one-hot-encoding)

None

Returns:

Type Description

a SimVar with the specified parameters.

add_action

add_action(inflow, outflow, behavior, name=None, guard=None, reward_function=None, solver=None, _fast=False)

Creates a new SimEvent with the specified parameters (also see SimEvent). Adds the SimEvent to the problem and returns it.

Parameters:

Name Type Description Default
inflow

a list of incoming SimVar of the event.

required
outflow

a list of outgoing SimVar of the event/

required
behavior

a function that takes as many parameters as there are incoming SimVar. The function must return a list with as many elements as there are outgoing SimVar. When the event happens, the function is performed on the incoming SimVar and the result of the function is put on the outgoing SimVar.

required
name

the identifier of the event.

None
guard

a function that takes as many parameters as there are incoming SimVar. The function must evaluate to True or False for all possible values of SimVar. The event can only happen for values for which the guard function evaluates to True.

None
reward_function

a function that takes as many parameters as there are incoming SimVar. The function must return a reward value for the event.

None
solver

a solver that decides which specific binding to use for firing.

None

Returns:

Type Description

a SimAction with the specified parameters.

bindings

bindings()

Calculates the set of timed bindings enabled for all events and actions in the problem.

The method determines which bindings are currently enabled based on the simulation clock and the network tag. It also updates the simulation clock and network tag as necessary.

Returns:

Type Description

A tuple containing: - A list of tuples ([(place, token), (place, token), ...], time, event) representing the enabled bindings. - A boolean indicating whether the model is still active.

simulate

simulate(duration, reporter=None)

Executes a simulation run for the specified duration.

The simulation runs events and actions until no more can occur or the specified duration is reached. If multiple events or actions can occur, one is selected based on the network tag and solver.

Parameters:

Name Type Description Default
duration

The maximum duration of the simulation.

required
reporter

A reporter or list of reporters to log simulation events. Each reporter must implement a callback method.

None

fire

fire(timed_binding)

Fires the specified timed binding. Binding is a tuple ([(place, token), (place, token), ...], time, event)

print_report

print_report(reporter, timed_binding)

Calls the reporter's callback function to log the details of a binding.

Parameters:

Name Type Description Default
reporter

A reporter or list of reporters to log simulation events.

required
timed_binding

The binding that occurred, represented as a tuple (binding, time, event).

required

get_heuristic_observation

get_heuristic_observation()

Creates a lean observation for heuristic solvers: - Includes only observable places and any transitions fully connected to those places. - Does NOT add a 'postpone' node (postpone is exposed via the pseudo-binding). - Propagates postpone-related flags for consistent logic in heuristics.

compute_pn_actions

compute_pn_actions()

Refresh self.pn_actions (the firable binding list) WITHOUT building the HeteroData tensor graph.

This is the cheap path for planners that only need to pick and fire actions (MCTS descent + rollout), skipping the ~66% of get_graph_observation spent on tensor/HeteroData construction. It reproduces exactly the binding-map that get_graph_observation builds in its a_transition branch — same expand_no_future_tokens, same iteration order over expanded_pn.actions, same b_time <= clock filter, same trailing postpone entry — so action indices stay identical to those the graph path produces (the network prior/eval alignment).

get_graph_observation

get_graph_observation(minimal_obs=False, normalize=False, remove_empty_nodes=True, add_self_loops=True)

Generates a graph-based observation of the problem.

The observation is represented as a heterogeneous graph, where nodes correspond to places and transitions, and edges represent the connections between them.

Parameters:

Name Type Description Default
normalize

Whether to normalize the node features (default is True).

False
add_self_loops

Whether to add self-loops to action transition nodes (default is True).

True

Returns:

Type Description

A dictionary containing: - 'graph': The graph observation as a HeteroData object. - 'mask': A mask graph indicating valid transitions. - 'actions_dict': A mapping of transitions to their bindings.

state_fingerprint

state_fingerprint()

A hashable summary of the simulation state that, with keyed random streams (stream_seed), determines the whole future of a run under a deterministic policy: clock, phase, the markings (token values and times, in marking order; restricted simulation: its places only), the firing counts and the stream seed. Two runs with equal fingerprints continue identically.

match_policy_view

match_policy_view(model)

Set global_view to the one a trained policy was built for (networks.policy_global_view), so policies trained before the whole-net view became the default still get the graphs they know. Component agents (gympn.component_agents.ComponentPolicy) also bring the turn and certificate settings they were trained under.

remove_empty_nodes

remove_empty_nodes(ret_graph)

Removes empty nodes (e.g. nodes that have numel()==0) from the graph observation by modifying the connectivity of the graph. If an empty node has incoming and outgoing edges, those will be removed.

Empty nodes are those that do not have any tokens or attributes associated with them.

Parameters:

Name Type Description Default
ret_graph

The graph observation as a HeteroData object.

required

Returns:

Type Description

The updated HeteroData object with empty nodes removed.

expand_no_future_tokens

expand_no_future_tokens(actions_only=False)

Expands the attributed A-E PN into a 1-bounded attributed A-E PN. Filters out tokens and bindings with time > self.clock.

actions_only=True builds only the expanded PLACES and ACTIONS (skipping the expanded events and all arc bookkeeping). pn_actions is derived solely from expanded_pn.actions and their input places, so the events/arcs are dead weight for compute_pn_actions — this is the cheap path in the planning hot loop and produces an IDENTICAL action order/content to the full expansion (verified), so alignment with the graph's a_transition nodes is preserved.

Returns:

Type Description

A tuple containing: - The expanded GymProblem instance. - A mapping of transitions to their bindings in the expanded problem.

save_state

save_state()

Lightweight snapshot of the MUTABLE simulation state, avoiding the deep-copy of the (immutable-during-a-search) net STRUCTURE — SimVars, transitions, arcs, id2node, metadata. Profiled: the full-pn deepcopy in env.set_state was ~20% of a search; this copies only markings + a few scalars.

Restores identically via restore_state. Token values are dicts that behaviors may mutate in place, so marking tokens are deep-copied.

restore_state

restore_state(state)

Restore a snapshot from save_state in place (self.pn stays the same object; only mutable state is rewritten).

expand

expand()

Expands the attributed A-E PN into a 1-bounded attributed A-E PN.

Each token in the original problem is mapped to a place in the expanded problem, and transitions are expanded to account for all possible token combinations.

Returns:

Type Description

A tuple containing: - The expanded GymProblem instance. - A mapping of transitions to their bindings in the expanded problem.

minimal_graph

minimal_graph(graph)

Generates a minimal graph observation by removing all nodes that are not attached to 'a_transition'.

Parameters:

Name Type Description Default
graph

The original graph observation as a HeteroData object.

required

Returns:

Type Description

The updated HeteroData object with only 'a_transition' nodes and those directly attached to them.

tokens_combinations staticmethod

tokens_combinations(event)

Creates a list of token combinations that are available to the specified event. These are combinations of tokens that are on the incoming SimVar of the event. For example, if a event has incoming SimVar a and b with tokens 1@0 on a and 2@0, 3@0 on b, the possible combinations are [(a, 1@0), (b, 2@0)] and [(a, 1@0), (b, 3@0)]

Parameters:

Name Type Description Default
event

the event to return the token combinations for.

required

Returns:

Type Description

a list of lists, each of which is a token combination.

event_bindings

event_bindings(event)

Calculates the set of bindings that enables the given event. Each binding is a tuple ([(place, token), (place, token), ...], time) that represents a single enabling binding. A binding is a possible token combination (see token_combinations), for which the event's guard function evaluates to True. In case there is no guard function, any combination is also a binding. The time is the time at which the latest token is available. For example, if a event has incoming SimVar a and b marked with tokens [1@2] on a and [2@3, 3@1] on b, the possible bindings are ([(a, 1@2), (b, 2@3)], 3) and ([(a, 1@2), (b, 3@1)], 3)

Parameters:

Name Type Description Default
event

the event for which to calculate the enabling bindings.

required

Returns:

Type Description

list of tuples ([(place, token), (place, token), ...], time)

get_to_first_action

get_to_first_action()

Runs the petri net until it gets to 'a' tag (initialization for mdp environment)

run_evolutions

run_evolutions(run, i, active_model, build_obs=True)

Function invoked by Gym environment to let the network perform evolutions when no actions are required

build_obs=False returns None instead of the HeteroData graph observation at each return point (the graph build is ~80% of step cost; cheap planner rollouts don't need it). pn.pn_actions is still updated by bindings(), so callers can pick/fire actions without the graph.

net_partition

net_partition()

Component id of every transition: the connected components of the undirected place-transition graph (an edge joins a place to every transition that consumes from or produces into it). Two transitions sharing ANY place -- a queue, a resource pool -- are in one component, so pre-emption never crosses a component boundary. Depends on the net only, never on the marking or the trajectory: this is the influence certificate of nfgae (suite/paper/NFGAE_THEORY.md, Theorem 1). Postpone is a pseudo-binding, not a transition, so it never merges components.

DEAD transitions are pruned first: a place is markable if it is marked now or produced into by a live transition, a transition is live if all its input places are markable (least fixpoint). This over-approximates what can ever fire (it ignores token counts and guards), so pruning is sound -- a dead transition never fires under any policy. It matters for e.g. multi-site with n_flex=0, whose empty flex place would otherwise glue every site into one component. Dead transitions map to None (they never fire, so are never looked up). Computed on first use from the marking at that time (the initial one, in practice) and cached; the topology is fixed.

net_place_partition

net_place_partition()

Component id of every place (see net_partition).

net_component_members

net_component_members(c)

The live transitions of component c in the current partition, as a frozenset of transition ids. With the marking-based certificate this is the stable name of a component: ids are renumbered when the partition refines, member sets are not.

update_reward

update_reward(timed_binding, result_tokens=None)

Accrue the firing's reward, in total and for its net component.

make_metadata

make_metadata(add_self_loops=True, add_action_to_action=True, add_reverse_edges=False)

Construct PyG HeteroData metadata: (node_types, edge_type_tuples).

New optional flags: - add_action_to_action: include a generic ('a_transition','a_to_a','a_transition') metapath that connects action nodes (useful to let the GNN pass messages directly between different action nodes such as stage A and stage B). - add_reverse_edges: add reverse edge types for each discovered edge type so message passing can flow bidirectionally (each (u,rel,v) adds (v, rel+'_rev', u)).

set_seed

set_seed(seed, *, deterministic: bool = True)

Seed every stochastic source (Python, NumPy, PyTorch, cuDNN) for a reproducible run. Single source of truth is :func:gympn.seed_everything. Environment stochasticity (arrivals, delays) uses the global random / numpy modules, so this also makes the net's dynamics reproducible.

training_run

training_run(length=10, args_dict=None)

Runs the petri net as a reinforcement learning environment.

Parameters:

Name Type Description Default
length

the length of the run.

10
args_dict

a dictionary with the arguments to be used for the run. The possible keys are:

Algorithm Parameters: - algorithm (str): The training algorithm to use. Choices are ['ppo-clip', 'ppo-penalty', 'pg']. Default: 'ppo-clip'. - gam (float): Discount rate. Default: 0.99. - lam (float): Generalized advantage parameter. Default: 0.99. - eps (float): Clip ratio for clipped PPO. Default: 0.2. - c (float): KLD weight for penalty PPO. Default: 0.2. - ent_bonus (float): Bonus factor for sampled policy entropy. Default: 0.0. - vf_coeff (float): Value function loss coefficient in total loss. Default: 0.5. - agent_seed (int or None): Seed for the agent. Default: None.

Policy Model: - policy_model (str): The type of policy network. Choices are ['gnn']. Default: 'gnn'. - policy_kwargs (dict): Arguments to the policy model constructor, passed through json.loads. Default: {"hidden_layers": [64]}. - policy_lr (float): Policy model learning rate. Default: 3e-4. - policy_updates (int): Number of policy model updates per epoch. Default: 2. - policy_kld_limit (float or None): KL divergence limit for early stopping. Default: None (disabled — not recommended for variable action sets). - policy_weights (str): Filename for initial policy weights. Default: "" (empty string). - policy_network (str): Filename for initial policy network. Default: "" (empty string). - score (bool): Whether to have multi-objective training. Default: False. - score_weight (float): Weight gradients of L2 loss. Default: 1e-3.

Value Model: - value_model (str): The type of value network. Choices are ['none', 'gnn']. Default: 'gnn'. - value_kwargs (dict): Arguments to the value model constructor, passed through json.loads. Default: {"hidden_layers": [64]}. - value_lr (float): Value model learning rate. Default: 3e-4. - value_updates (int): Number of value model updates per epoch. Default: 10. - value_weights (str): Filename for initial value weights. Default: "" (empty string)`.

Training Parameters: - episodes (int): Number of episodes per epoch. Default: 10. - epochs (int): Number of epochs. Default: 100. - max_episode_length (int or None): Maximum number of interactions per episode. Default: None. - batch_size (int or None): Size of batches in training. Default: 64. - sort_states (bool): Whether to sort the states before batching. Default: False. - use_gpu (bool): Whether to use a GPU if available. Default: False. - load_policy_network (bool): Whether to load a previously trained policy as a starting point for this run. Default: False. - verbose (int): How much information to print. Default: 0.

Saving Parameters: - name (str): Name of the training run. Default: 'run'. - datetag (bool): Whether to append the current time to the run name. Default: False. - logdir (str): Base directory for training runs. Default: 'data/train'. - save_freq (int): How often to save the models. Default: 1. - 'use_wandb' (bool): Whether to use Weights & Biases for logging. Default: True. - 'wandb_mode' (str): W&B mode: 'online' (cloud), 'offline' (local), or 'disabled'. Default: 'offline'.

None

step

step(reporter=None, length=None)

Executes one simulation step.

Evolution phase: - Fire one evolution binding (as before).

Action phase: - GymSolver: use policy over graph observation (postpone already included). - Other solvers: expose 'postpone' via a pseudo-binding and pass the augmented list to the solver. Solver may return: * 'postpone' (string) * the postpone pseudo-binding tuple * a real timed binding from the augmented list

set_solver

set_solver(solver)

Sets the solver for the problem.

The solver determines which action to execute when multiple actions are enabled.

:param solver: An instance of a solver class implementing the BaseSolver interface.

testing_run

testing_run(solver, length=10, reporter=None, visualize=False, seed=None)

Test run aligned with AEPN_Env semantics: 1) Ensure we start in ACTION phase (like env.reset()). 2) Loop: - Choose exactly ONE action (or postpone). - Apply it (fire or postpone). - Run all evolutions: obs, terminated, _ = run_evolutions(...) - Stop when 'terminated' is True (same as AEPN_Env.step). 3) Return total accumulated reward (same scalar your env exposes in info['pn_reward']).

The testing run evaluates the solver's performance over a specified duration.

Parameters:

Name Type Description Default
solver

An instance of a solver class implementing the BaseSolver interface.

required
length

The maximum duration of the testing run. The simulation will stop if the clock exceeds (or matches) this length.

10
reporter

A reporter to log simulation events.

None
visualize

Whether to visualize the simulation.

False
seed

if given, seed all stochastic sources first (via :func:gympn.seed_everything) so the evaluation episode is reproducible.

None

Returns:

Type Description

The total reward accumulated during the testing run.

set_unobservable

set_unobservable(simvars=None, token_attrs=None)

Defines the set of unobservable simulation variables and token attributes.

Unobservable variables and attributes are excluded from observations and graph representations.

Parameters:

Name Type Description Default
simvars

A list of SimVar IDs that are unobservable.

None
token_attrs

A dictionary mapping SimVar IDs to lists of unobservable token attribute names.

None

postpone

postpone(comp=None)

Postpones the current action by advancing the clock to the next valid evolution event.

Component scope (postpone_scope='component'): only component comp waits -- its actions are blocked until one of ITS events fires -- and the decision round continues for the other components.