Hypha Petri Nets API Reference¶
Core Module¶
mycorrhizal.hypha.core ¶
Hypha - Decorator-based Colored Petri Net Framework
A DSL for defining and executing colored Petri nets with support for asyncio, multi-set places, guards, and hierarchical subnet composition.
Usage
from mycorrhizal.hypha.core import pn, Runner
@pn.net def ProcessingNet(builder): # Define places (all are multi-sets/bags) pending = builder.place("pending") processed = builder.place("processed")
# Define transitions
@builder.transition()
async def process(consumed, bb, timebase):
for token in consumed:
result = await handle(token)
yield {processed: result}
# Wire the net
builder.arc(pending, process).arc(processed)
Run the Petri net¶
runner = Runner(ProcessingNet, bb=blackboard) await runner.start(timebase)
Key Classes
NetBuilder - Builder for constructing Petri nets PlaceSpec - Specification for a place TransitionSpec - Specification for a transition Runner - Runtime for executing Petri nets
All places are multi-sets (bags) with unordered token storage that supports multiplicity.
Transitions
Transitions consume tokens from input places and produce tokens for output places. They are async functions that yield dictionaries mapping place references to tokens.
Guards
Guards are conditions that must be satisfied for a transition to fire. They can check token values, blackboard state, or external conditions.
PlaceSpec
dataclass
¶
PlaceSpec(name: str, handler: Optional[Callable] = None, state_factory: Optional[Callable] = None, is_io_input: bool = False, is_io_output: bool = False)
Specification for a place in the Petri net.
All places are multi-sets (bags) that support token storage with multiplicity. Tokens can be added and removed from places.
TransitionSpec
dataclass
¶
TransitionSpec(name: str, handler: Callable, guard: Optional[GuardSpec] = None, state_factory: Optional[Callable] = None, delay: float = 0.0)
Specification for a transition in the Petri net
ArcSpec
dataclass
¶
ArcSpec(source: PlaceRef | TransitionRef, target: PlaceRef | TransitionRef, weight: int = 1, name: Optional[str] = None)
Specification for an arc connecting places and transitions
NetSpec
dataclass
¶
NetSpec(name: str, parent: Optional[NetSpec] = None, places: Dict[str, PlaceSpec] = dict(), transitions: Dict[str, TransitionSpec] = dict(), arcs: List[ArcSpec] = list(), subnets: Dict[str, NetSpec] = dict())
Complete specification of a Petri net
get_fqn ¶
get_parts ¶
Return the fully qualified name as a list of path components.
If local_name is provided, returns the parts for that member under this spec (e.g. ['Parent', 'Spec', 'local']). Otherwise returns the parts for this spec itself.
Source code in src/mycorrhizal/hypha/core/specs.py
to_mermaid ¶
Generate Mermaid diagram of the net
Source code in src/mycorrhizal/hypha/core/specs.py
PlaceRef ¶
PlaceRef(local_name: str, parent_spec: NetSpec)
Reference to a place for use in arc definitions
Source code in src/mycorrhizal/hypha/core/specs.py
get_fqn ¶
get_parts ¶
__call__ ¶
__call__(func: Callable) -> PlaceRef
Allow PlaceRef to be used as a decorator to register a handler.
Example
@builder.place("queue") def queue_handler(bb): return bb.tokens
The PlaceRef is returned for use in arcs, and the handler is registered.
Source code in src/mycorrhizal/hypha/core/specs.py
TransitionRef ¶
TransitionRef(local_name: str, parent_spec: NetSpec)
Reference to a transition for use in arc definitions
Source code in src/mycorrhizal/hypha/core/specs.py
SubnetRef ¶
SubnetRef(spec: NetSpec)
Reference to a subnet instance for accessing its places/transitions
Source code in src/mycorrhizal/hypha/core/specs.py
NetBuilder ¶
NetBuilder(name: str, parent: Optional[NetSpec] = None)
Builder for constructing Petri net specifications
Source code in src/mycorrhizal/hypha/core/builder.py
place ¶
place(name_or_func: Union[str, Callable, None] = None, state_factory: Optional[Callable] = None) -> Union[PlaceRef, Callable]
Declare a regular place.
All places are multi-sets (bags) that support token storage with multiplicity. Tokens can be added and removed from places.
Can be used in three ways:
-
As a method call (returns PlaceRef for use in arcs): place = builder.place("my_place")
-
As a decorator without parens (infers name from function): @builder.place def my_place(bb): return bb.tokens
-
As a decorator with custom name: @builder.place("custom_name") def my_func(bb): return bb.tokens
Source code in src/mycorrhizal/hypha/core/builder.py
io_input_place ¶
Decorator for IOInputPlace with async generator
Source code in src/mycorrhizal/hypha/core/builder.py
io_output_place ¶
Decorator for IOOutputPlace with async handler
Source code in src/mycorrhizal/hypha/core/builder.py
transition ¶
transition(guard: Optional[GuardSpec] = None, state_factory: Optional[Callable] = None, delay: float = 0.0)
Decorator for transition function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
guard
|
Optional[GuardSpec]
|
Optional guard specification |
None
|
state_factory
|
Optional[Callable]
|
Optional state factory for transition state |
None
|
delay
|
float
|
Static delay in seconds before firing after becoming enabled (default: 0.0) |
0.0
|
Usage
@builder.transition() async def my_transition(consumed, bb, timebase): yield {output: token}
@builder.transition(delay=0.1) # 100ms delay async def delayed_transition(consumed, bb, timebase): yield {output: token}
Note: When creating multiple transitions in a loop with the same function name, the builder automatically generates unique names by appending a counter suffix.
Source code in src/mycorrhizal/hypha/core/builder.py
arc ¶
arc(source: Any, target: Any, name: Optional[str] = None, weight: int = 1) -> ArcChain
Create an arc and return chainable ArcChain
Source code in src/mycorrhizal/hypha/core/builder.py
subnet ¶
subnet(net_func: Callable, instance_name: str) -> SubnetRef
Instantiate a subnet with given instance name
Source code in src/mycorrhizal/hypha/core/builder.py
_remap_arcs_to_subnet ¶
Remap arc references to point into target subnet.
For each PlaceRef/TransitionRef in the arcs, creates a new reference bound to the target subnet. Handles nested SubnetRefs by recursively copying their specs into the target subnet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arcs
|
List[ArcSpec]
|
Original arcs from the template net |
required |
subnet_spec
|
NetSpec
|
Target subnet spec to bind references to |
required |
Returns:
| Type | Description |
|---|---|
List[ArcSpec]
|
New list of ArcSpec with remapped references |
Source code in src/mycorrhizal/hypha/core/builder.py
_remap_ref_to_subnet ¶
_remap_ref_to_subnet(ref: Any, target_subnet: NetSpec, original_spec: Optional[NetSpec] = None) -> Any
Remap a single reference to point into target subnet.
Handles: - PlaceRef: Create new PlaceRef bound to target_subnet - TransitionRef: Create new TransitionRef bound to target_subnet - SubnetRef: Recursively copy nested subnet spec into target_subnet
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref
|
Any
|
Reference to remap (PlaceRef, TransitionRef, SubnetRef, or other) |
required |
target_subnet
|
NetSpec
|
The subnet spec to bind the reference to |
required |
original_spec
|
Optional[NetSpec]
|
The original template spec (for resolving nested subnets) |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The remapped reference, or original if unknown type |
Source code in src/mycorrhizal/hypha/core/builder.py
_ensure_nested_subnets_copied ¶
Ensure all nested subnets are copied into the target subnet.
This handles nested subnets that weren't already processed during arc remapping. Each nested subnet is copied with its parent set to the target subnet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_spec
|
NetSpec
|
The template spec containing nested subnets |
required |
subnet_spec
|
NetSpec
|
The target subnet spec to copy nested subnets into |
required |
Source code in src/mycorrhizal/hypha/core/builder.py
_copy_spec_with_parent ¶
Deep copy a spec and set new parent
Source code in src/mycorrhizal/hypha/core/builder.py
forward ¶
Create a simple pass-through transition
Source code in src/mycorrhizal/hypha/core/builder.py
fork ¶
Create a transition that broadcasts tokens to multiple outputs
Source code in src/mycorrhizal/hypha/core/builder.py
join ¶
Create a transition that waits for tokens from all inputs
Source code in src/mycorrhizal/hypha/core/builder.py
merge ¶
Create transitions from each input to output
Source code in src/mycorrhizal/hypha/core/builder.py
round_robin ¶
Create a transition that distributes tokens round-robin
Source code in src/mycorrhizal/hypha/core/builder.py
route ¶
Create a transition that routes by token type
Source code in src/mycorrhizal/hypha/core/builder.py
ArcChain ¶
ArcChain(builder: NetBuilder, last_ref: Any)
Fluent interface for chaining arc definitions
Source code in src/mycorrhizal/hypha/core/builder.py
arc ¶
arc(target: Any, name: Optional[str] = None, weight: int = 1) -> ArcChain
Chain another arc from the last element to target
Source code in src/mycorrhizal/hypha/core/builder.py
Runner ¶
High-level runner for executing a Petri net
Uses MatrixRuntime for high-performance matrix-based execution.
Source code in src/mycorrhizal/hypha/core/runtime.py
start
async
¶
Start the net with given timebase
Source code in src/mycorrhizal/hypha/core/runtime.py
stop
async
¶
add_place ¶
Add a place to the running net
Source code in src/mycorrhizal/hypha/core/runtime.py
add_transition ¶
add_transition(fqn: str, handler: Callable, guard: Optional[GuardSpec] = None, state_factory: Optional[Callable] = None, delay: float = 0.0)
Add a transition to the running net
Source code in src/mycorrhizal/hypha/core/runtime.py
add_arc ¶
Add an arc to the running net
Source code in src/mycorrhizal/hypha/core/runtime.py
remove_arc
async
¶
Remove an arc from the running net
Source code in src/mycorrhizal/hypha/core/runtime.py
remove
async
¶
run_sync ¶
Run the net to completion in synchronous mode.
This is the high-performance execution path for pure computational nets. Only works with MatrixRuntime and requires no async features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timebase
|
Any
|
Timebase for timing operations |
required |
max_cycles
|
int
|
Maximum number of cycles to execute |
100000
|
Returns:
| Type | Description |
|---|---|
int
|
Number of cycles executed |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If net has async features |
Source code in src/mycorrhizal/hypha/core/runtime.py
Builder Module¶
mycorrhizal.hypha.core.builder ¶
Hypha DSL - Builder Layer
NetBuilder provides the API for declaratively constructing Petri net specifications. Used within @pn.net decorated functions.
ArcChain ¶
ArcChain(builder: NetBuilder, last_ref: Any)
Fluent interface for chaining arc definitions
Source code in src/mycorrhizal/hypha/core/builder.py
arc ¶
arc(target: Any, name: Optional[str] = None, weight: int = 1) -> ArcChain
Chain another arc from the last element to target
Source code in src/mycorrhizal/hypha/core/builder.py
NetBuilder ¶
NetBuilder(name: str, parent: Optional[NetSpec] = None)
Builder for constructing Petri net specifications
Source code in src/mycorrhizal/hypha/core/builder.py
place ¶
place(name_or_func: Union[str, Callable, None] = None, state_factory: Optional[Callable] = None) -> Union[PlaceRef, Callable]
Declare a regular place.
All places are multi-sets (bags) that support token storage with multiplicity. Tokens can be added and removed from places.
Can be used in three ways:
-
As a method call (returns PlaceRef for use in arcs): place = builder.place("my_place")
-
As a decorator without parens (infers name from function): @builder.place def my_place(bb): return bb.tokens
-
As a decorator with custom name: @builder.place("custom_name") def my_func(bb): return bb.tokens
Source code in src/mycorrhizal/hypha/core/builder.py
io_input_place ¶
Decorator for IOInputPlace with async generator
Source code in src/mycorrhizal/hypha/core/builder.py
io_output_place ¶
Decorator for IOOutputPlace with async handler
Source code in src/mycorrhizal/hypha/core/builder.py
transition ¶
transition(guard: Optional[GuardSpec] = None, state_factory: Optional[Callable] = None, delay: float = 0.0)
Decorator for transition function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
guard
|
Optional[GuardSpec]
|
Optional guard specification |
None
|
state_factory
|
Optional[Callable]
|
Optional state factory for transition state |
None
|
delay
|
float
|
Static delay in seconds before firing after becoming enabled (default: 0.0) |
0.0
|
Usage
@builder.transition() async def my_transition(consumed, bb, timebase): yield {output: token}
@builder.transition(delay=0.1) # 100ms delay async def delayed_transition(consumed, bb, timebase): yield {output: token}
Note: When creating multiple transitions in a loop with the same function name, the builder automatically generates unique names by appending a counter suffix.
Source code in src/mycorrhizal/hypha/core/builder.py
arc ¶
arc(source: Any, target: Any, name: Optional[str] = None, weight: int = 1) -> ArcChain
Create an arc and return chainable ArcChain
Source code in src/mycorrhizal/hypha/core/builder.py
subnet ¶
subnet(net_func: Callable, instance_name: str) -> SubnetRef
Instantiate a subnet with given instance name
Source code in src/mycorrhizal/hypha/core/builder.py
_remap_arcs_to_subnet ¶
Remap arc references to point into target subnet.
For each PlaceRef/TransitionRef in the arcs, creates a new reference bound to the target subnet. Handles nested SubnetRefs by recursively copying their specs into the target subnet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arcs
|
List[ArcSpec]
|
Original arcs from the template net |
required |
subnet_spec
|
NetSpec
|
Target subnet spec to bind references to |
required |
Returns:
| Type | Description |
|---|---|
List[ArcSpec]
|
New list of ArcSpec with remapped references |
Source code in src/mycorrhizal/hypha/core/builder.py
_remap_ref_to_subnet ¶
_remap_ref_to_subnet(ref: Any, target_subnet: NetSpec, original_spec: Optional[NetSpec] = None) -> Any
Remap a single reference to point into target subnet.
Handles: - PlaceRef: Create new PlaceRef bound to target_subnet - TransitionRef: Create new TransitionRef bound to target_subnet - SubnetRef: Recursively copy nested subnet spec into target_subnet
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref
|
Any
|
Reference to remap (PlaceRef, TransitionRef, SubnetRef, or other) |
required |
target_subnet
|
NetSpec
|
The subnet spec to bind the reference to |
required |
original_spec
|
Optional[NetSpec]
|
The original template spec (for resolving nested subnets) |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The remapped reference, or original if unknown type |
Source code in src/mycorrhizal/hypha/core/builder.py
_ensure_nested_subnets_copied ¶
Ensure all nested subnets are copied into the target subnet.
This handles nested subnets that weren't already processed during arc remapping. Each nested subnet is copied with its parent set to the target subnet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_spec
|
NetSpec
|
The template spec containing nested subnets |
required |
subnet_spec
|
NetSpec
|
The target subnet spec to copy nested subnets into |
required |
Source code in src/mycorrhizal/hypha/core/builder.py
_copy_spec_with_parent ¶
Deep copy a spec and set new parent
Source code in src/mycorrhizal/hypha/core/builder.py
forward ¶
Create a simple pass-through transition
Source code in src/mycorrhizal/hypha/core/builder.py
fork ¶
Create a transition that broadcasts tokens to multiple outputs
Source code in src/mycorrhizal/hypha/core/builder.py
join ¶
Create a transition that waits for tokens from all inputs
Source code in src/mycorrhizal/hypha/core/builder.py
merge ¶
Create transitions from each input to output
Source code in src/mycorrhizal/hypha/core/builder.py
round_robin ¶
Create a transition that distributes tokens round-robin
Source code in src/mycorrhizal/hypha/core/builder.py
route ¶
Create a transition that routes by token type
Source code in src/mycorrhizal/hypha/core/builder.py
PetriNetDSL ¶
Module-level API for Petri net definition
net
staticmethod
¶
Decorator for defining a Petri net. The decorated function receives a NetBuilder as its parameter.
Source code in src/mycorrhizal/hypha/core/builder.py
Runtime Module¶
mycorrhizal.hypha.core.runtime ¶
Hypha DSL - Runtime Layer
Runtime objects that execute the Petri net specification. Manages token flow, transition firing, and asyncio task coordination.
PlaceWrapper ¶
PlaceWrapper(matrix_runtime: MatrixRuntime, place_idx: int)
Wrapper for places in MatrixRuntime to provide NetRuntime-like API.
Source code in src/mycorrhizal/hypha/core/runtime.py
add_token ¶
IncidenceMatrix
dataclass
¶
IncidenceMatrix(num_places: int, num_transitions: int, matrix: Dict[int, Dict[int, int]] = dict(), place_to_idx: Dict[Tuple[str, ...], int] = dict(), idx_to_place: Dict[int, Tuple[str, ...]] = dict(), transition_to_idx: Dict[Tuple[str, ...], int] = dict(), idx_to_transition: Dict[int, Tuple[str, ...]] = dict(), input_requirements: Dict[int, Dict[int, int]] = dict(), output_destinations: Dict[int, Dict[int, int]] = dict())
Incidence matrix representation of Petri net structure.
The incidence matrix A represents the net structure: - Rows: places (P rows) - Columns: transitions (T columns) - Entry A[i,j]: net token change at place i when transition j fires - Negative value: tokens consumed from place i - Positive value: tokens produced to place i - Zero: no connection
For a transition with input arcs (consuming tokens) and output arcs (producing tokens), the column shows the net change.
get ¶
set ¶
Set matrix entry at (place_idx, trans_idx)
add_input ¶
Add input arc (consumes tokens, so negative entry)
Source code in src/mycorrhizal/hypha/core/runtime.py
add_output ¶
Add output arc (produces tokens, so positive entry)
Source code in src/mycorrhizal/hypha/core/runtime.py
compute_state_change ¶
Compute state change: delta = A @ F
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
firing_vector
|
List[int]
|
List of length num_transitions with 0/1 values |
required |
Returns:
| Type | Description |
|---|---|
Dict[int, int]
|
Dict mapping place_idx -> net_token_change |
Source code in src/mycorrhizal/hypha/core/runtime.py
is_enabled ¶
Check if transition is enabled (has sufficient input tokens).
IMPORTANT: When multiple arcs connect the same place to a transition, we need to check if there are enough tokens to satisfy all arcs. The old runtime allowed "bag semantics" where arcs could consume the same token, but for practical purposes we require distinct tokens per arc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trans_idx
|
int
|
Transition index |
required |
marking
|
Dict[int, int]
|
Current marking (place_idx -> token_count) |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if transition has all required input tokens |
Source code in src/mycorrhizal/hypha/core/runtime.py
get_token_slots ¶
Get token consumption slots for a transition (cached for performance).
When multiple arcs connect the same place to a transition, we need to consume separate tokens (or the same token multiple times for bag semantics).
Returns:
| Type | Description |
|---|---|
List[Tuple[int, int]]
|
List of (place_idx, slot_index) tuples representing token consumption slots |
Source code in src/mycorrhizal/hypha/core/runtime.py
TokenEntry
dataclass
¶
Represents a token with optional data payload.
TokenRegistry ¶
Marking
dataclass
¶
State vector representation of Petri net marking.
For data-carrying tokens, stores token IDs. For simple count places, stores the count directly.
PERFORMANCE: Cached count dict is invalidated on token changes to avoid recomputing on every transition check.
_invalidate_cache ¶
get_count ¶
add_tokens ¶
Add tokens to a place.
remove_tokens ¶
Remove tokens from a place (returns removed tokens).
Source code in src/mycorrhizal/hypha/core/runtime.py
remove_tokens_fast ¶
Remove specific tokens from a place (faster O(1) per token).
This is used when we know exactly which tokens to remove. Uses a set-based approach for O(n) total instead of O(n*m).
Source code in src/mycorrhizal/hypha/core/runtime.py
peek_tokens ¶
has_tokens ¶
get_count_dict ¶
Get dict of place_idx -> token_count (cached for performance).
Source code in src/mycorrhizal/hypha/core/runtime.py
GuardInfo
dataclass
¶
GuardInfo(has_guard: bool = False, guard_spec: Optional[GuardSpec] = None, requires_tokens: bool = False)
Information about a transition's guard.
GuardMatrix ¶
Guard type matrix and evaluation logic.
Tracks which transitions have guards and evaluates them to build the firing vector F.
Source code in src/mycorrhizal/hypha/core/runtime.py
set_guard ¶
set_guard(trans_idx: int, guard_spec: Optional[GuardSpec], requires_tokens: bool = False)
Set guard info for a transition.
Source code in src/mycorrhizal/hypha/core/runtime.py
has_guard ¶
evaluate ¶
evaluate(trans_idx: int, marking: Marking, incidence_matrix: IncidenceMatrix, bb: Any, timebase: Any, token_registry: TokenRegistry) -> bool | Any
Evaluate guard for a transition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trans_idx
|
int
|
Transition index |
required |
marking
|
Marking
|
Current marking |
required |
incidence_matrix
|
IncidenceMatrix
|
Incidence matrix for net structure |
required |
bb
|
Any
|
Blackboard |
required |
timebase
|
Any
|
Timebase |
required |
token_registry
|
TokenRegistry
|
Token registry for data lookups |
required |
Returns:
| Type | Description |
|---|---|
bool | Any
|
True if guard passes (or no guard), False otherwise |
bool | Any
|
Can also return async generator for async guards (handled by caller) |
Source code in src/mycorrhizal/hypha/core/runtime.py
MatrixRuntime ¶
MatrixRuntime(spec: NetSpec, bb: Any, timebase: Any)
Matrix-based Petri net runtime.
Uses incidence matrix and state vector for execution, eliminating per-transition asyncio overhead.
Execution model: 1. Build firing vector F by evaluating enabled transitions 2. Fire via M_new = M + (A @ F) 3. Process token data flow for fired transitions 4. Repeat
Source code in src/mycorrhizal/hypha/core/runtime.py
places
property
¶
places: Dict[Tuple[str, ...], PlaceWrapper]
Get places dict (compatibility layer with NetRuntime).
transitions
property
¶
Get transitions dict (compatibility layer with NetRuntime).
Note: This returns a simplified view for compatibility with mycelium bridge. The actual transition data is stored in _transition_specs.
_detect_async_features ¶
Detect if the net has async features that require async mode.
Returns:
| Type | Description |
|---|---|
bool
|
True if net has IO places, async transitions, or async guards |
Source code in src/mycorrhizal/hypha/core/runtime.py
get_cache_stats ¶
Get cache statistics for monitoring and debugging.
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict with current cache size, maxsize, and hit/miss counts |
_create_interface_view_if_needed ¶
Create constrained view if handler has interface type hint.
Source code in src/mycorrhizal/hypha/core/runtime.py
_start_io_input
async
¶
Start IO input places.
Source code in src/mycorrhizal/hypha/core/runtime.py
_io_input_loop
async
¶
_io_input_loop(place_idx: int, place_spec: PlaceSpec)
IO input loop for a single place.
Source code in src/mycorrhizal/hypha/core/runtime.py
_handle_io_output
async
¶
Handle IO output for a token.
Source code in src/mycorrhizal/hypha/core/runtime.py
add_token ¶
Add a token to a place.
Source code in src/mycorrhizal/hypha/core/runtime.py
add_token_by_fqn ¶
Add a token by place FQN.
get_token_count_by_fqn ¶
Get token count by place FQN.
Source code in src/mycorrhizal/hypha/core/runtime.py
_build_firing_vector
async
¶
Build firing vector F by evaluating enabled transitions.
Returns:
| Type | Description |
|---|---|
List[int]
|
List of 0/1 values indicating which transitions fire |
Source code in src/mycorrhizal/hypha/core/runtime.py
_execute_transition
async
¶
Execute a transition with input tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trans_idx
|
int
|
Transition index |
required |
input_tokens
|
List[Any]
|
List of consumed token data |
required |
Source code in src/mycorrhizal/hypha/core/runtime.py
_process_yield
async
¶
Process yielded output from transition.
Source code in src/mycorrhizal/hypha/core/runtime.py
_process_dict_yield
async
¶
Process dictionary yield.
Source code in src/mycorrhizal/hypha/core/runtime.py
_process_single_yield
async
¶
Process single (place_ref, token) yield.
Source code in src/mycorrhizal/hypha/core/runtime.py
_resolve_place_ref ¶
Resolve a place reference to a place index.
Uses parent-relative mapping for subnet instances, similar to NetRuntime.
Resolution strategies: 1. Exact match using PlaceRef.get_parts() 2. Parent-relative mapping using transition's FQN context
Source code in src/mycorrhizal/hypha/core/runtime.py
_add_token_to_place
async
¶
Add a token to a place, handling IO output.
Source code in src/mycorrhizal/hypha/core/runtime.py
_expand_wildcard_to_outputs
async
¶
_expand_wildcard_to_outputs(trans_idx: int, wildcard_token: Any, explicit_targets: set, output_dests: Dict[int, int])
Expand wildcard token to all output places.
Source code in src/mycorrhizal/hypha/core/runtime.py
_fire_transitions
async
¶
Fire transitions using matrix multiplication and process data flow.
This is the CRITICAL method: state transformation is ALWAYS via matmul.
CRITICAL: When multiple transitions compete for the same input place, we must fire them sequentially (each consumes its tokens before the next fires) to ensure each token is consumed by exactly one transition per cycle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
firing_vector
|
List[int]
|
Binary vector indicating which transitions fire |
required |
Source code in src/mycorrhizal/hypha/core/runtime.py
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 | |
run_cycle
async
¶
Run a single execution cycle.
Source code in src/mycorrhizal/hypha/core/runtime.py
run
async
¶
Main execution loop.
Source code in src/mycorrhizal/hypha/core/runtime.py
start
async
¶
Start the runtime.
Source code in src/mycorrhizal/hypha/core/runtime.py
stop
async
¶
Stop the runtime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float
|
Maximum time to wait for graceful shutdown (seconds) |
5.0
|
Source code in src/mycorrhizal/hypha/core/runtime.py
_build_firing_vector_sync ¶
Build firing vector F by evaluating enabled transitions (synchronous).
Returns:
| Type | Description |
|---|---|
List[int]
|
List of 0/1 values indicating which transitions fire |
Source code in src/mycorrhizal/hypha/core/runtime.py
_execute_transition_sync ¶
Execute a transition with input tokens (synchronous).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trans_idx
|
int
|
Transition index |
required |
input_tokens
|
List[Any]
|
List of consumed token data |
required |
Source code in src/mycorrhizal/hypha/core/runtime.py
_process_yield_sync ¶
Process yielded output from transition (synchronous).
Source code in src/mycorrhizal/hypha/core/runtime.py
_process_dict_yield_sync ¶
Process dictionary yield (synchronous).
Source code in src/mycorrhizal/hypha/core/runtime.py
_process_single_yield_sync ¶
Process single (place_ref, token) yield (synchronous).
Source code in src/mycorrhizal/hypha/core/runtime.py
_add_token_to_place_sync ¶
Add a token to a place, handling IO output (synchronous).
Note: IO output places are not supported in sync mode - tokens are just added.
Source code in src/mycorrhizal/hypha/core/runtime.py
_expand_wildcard_to_outputs_sync ¶
_expand_wildcard_to_outputs_sync(trans_idx: int, wildcard_token: Any, explicit_targets: set, output_dests: Dict[int, int])
Expand wildcard token to all output places (synchronous).
Source code in src/mycorrhizal/hypha/core/runtime.py
_fire_transitions_sync ¶
Fire transitions using matrix multiplication and process data flow (synchronous).
This is the synchronous version of _fire_transitions for pure computational nets.
CRITICAL: When multiple transitions compete for the same input place, we must fire them sequentially (each consumes its tokens before the next fires) to ensure each token is consumed by exactly one transition per cycle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
firing_vector
|
List[int]
|
Binary vector indicating which transitions fire |
required |
Source code in src/mycorrhizal/hypha/core/runtime.py
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 | |
run_cycle_sync ¶
Run a single execution cycle (synchronous).
Returns:
| Type | Description |
|---|---|
bool
|
True if any transitions fired, False otherwise |
Source code in src/mycorrhizal/hypha/core/runtime.py
run_sync ¶
Run the net to completion or max cycles (synchronous execution).
This is the high-performance synchronous execution path for pure computational nets. It avoids all asyncio overhead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_cycles
|
int
|
Maximum number of cycles to execute (prevents infinite loops) |
100000
|
Returns:
| Type | Description |
|---|---|
|
Number of cycles executed |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If net has async features (use async mode instead) |
Source code in src/mycorrhizal/hypha/core/runtime.py
Runner ¶
High-level runner for executing a Petri net
Uses MatrixRuntime for high-performance matrix-based execution.
Source code in src/mycorrhizal/hypha/core/runtime.py
start
async
¶
Start the net with given timebase
Source code in src/mycorrhizal/hypha/core/runtime.py
stop
async
¶
add_place ¶
Add a place to the running net
Source code in src/mycorrhizal/hypha/core/runtime.py
add_transition ¶
add_transition(fqn: str, handler: Callable, guard: Optional[GuardSpec] = None, state_factory: Optional[Callable] = None, delay: float = 0.0)
Add a transition to the running net
Source code in src/mycorrhizal/hypha/core/runtime.py
add_arc ¶
Add an arc to the running net
Source code in src/mycorrhizal/hypha/core/runtime.py
remove_arc
async
¶
Remove an arc from the running net
Source code in src/mycorrhizal/hypha/core/runtime.py
remove
async
¶
run_sync ¶
Run the net to completion in synchronous mode.
This is the high-performance execution path for pure computational nets. Only works with MatrixRuntime and requires no async features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timebase
|
Any
|
Timebase for timing operations |
required |
max_cycles
|
int
|
Maximum number of cycles to execute |
100000
|
Returns:
| Type | Description |
|---|---|
int
|
Number of cycles executed |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If net has async features |
Source code in src/mycorrhizal/hypha/core/runtime.py
build_incidence_matrix ¶
build_incidence_matrix(spec: NetSpec) -> IncidenceMatrix
Build incidence matrix from net specification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
NetSpec
|
Net specification |
required |
Returns:
| Type | Description |
|---|---|
IncidenceMatrix
|
IncidenceMatrix representation |
Source code in src/mycorrhizal/hypha/core/runtime.py
build_guard_matrix ¶
build_guard_matrix(spec: NetSpec, incidence_matrix: IncidenceMatrix) -> GuardMatrix
Build guard matrix from net specification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
NetSpec
|
Net specification |
required |
incidence_matrix
|
IncidenceMatrix
|
Incidence matrix for index mapping |
required |
Returns:
| Type | Description |
|---|---|
GuardMatrix
|
GuardMatrix with guard information |
Source code in src/mycorrhizal/hypha/core/runtime.py
Specifications Module¶
mycorrhizal.hypha.core.specs ¶
Hypha DSL - Specification Layer
Core data structures representing the declarative specification of a Petri net. These are built by the decorator API and used to instantiate runtime objects.
PlaceSpec
dataclass
¶
PlaceSpec(name: str, handler: Optional[Callable] = None, state_factory: Optional[Callable] = None, is_io_input: bool = False, is_io_output: bool = False)
Specification for a place in the Petri net.
All places are multi-sets (bags) that support token storage with multiplicity. Tokens can be added and removed from places.
TransitionSpec
dataclass
¶
TransitionSpec(name: str, handler: Callable, guard: Optional[GuardSpec] = None, state_factory: Optional[Callable] = None, delay: float = 0.0)
Specification for a transition in the Petri net
ArcSpec
dataclass
¶
ArcSpec(source: PlaceRef | TransitionRef, target: PlaceRef | TransitionRef, weight: int = 1, name: Optional[str] = None)
Specification for an arc connecting places and transitions
NetSpec
dataclass
¶
NetSpec(name: str, parent: Optional[NetSpec] = None, places: Dict[str, PlaceSpec] = dict(), transitions: Dict[str, TransitionSpec] = dict(), arcs: List[ArcSpec] = list(), subnets: Dict[str, NetSpec] = dict())
Complete specification of a Petri net
get_fqn ¶
get_parts ¶
Return the fully qualified name as a list of path components.
If local_name is provided, returns the parts for that member under this spec (e.g. ['Parent', 'Spec', 'local']). Otherwise returns the parts for this spec itself.
Source code in src/mycorrhizal/hypha/core/specs.py
to_mermaid ¶
Generate Mermaid diagram of the net
Source code in src/mycorrhizal/hypha/core/specs.py
PlaceRef ¶
PlaceRef(local_name: str, parent_spec: NetSpec)
Reference to a place for use in arc definitions
Source code in src/mycorrhizal/hypha/core/specs.py
get_fqn ¶
get_parts ¶
__call__ ¶
__call__(func: Callable) -> PlaceRef
Allow PlaceRef to be used as a decorator to register a handler.
Example
@builder.place("queue") def queue_handler(bb): return bb.tokens
The PlaceRef is returned for use in arcs, and the handler is registered.
Source code in src/mycorrhizal/hypha/core/specs.py
TransitionRef ¶
TransitionRef(local_name: str, parent_spec: NetSpec)
Reference to a transition for use in arc definitions
Source code in src/mycorrhizal/hypha/core/specs.py
Utilities¶
mycorrhizal.hypha.util ¶
Hypha Petri Net Utilities
Utility functions for Petri net operations like Mermaid diagram generation.
to_mermaid ¶
to_mermaid(spec: NetSpec) -> str
Generate Mermaid diagram from a NetSpec.
This is a utility wrapper around NetSpec.to_mermaid() for convenience. Use this when you have a spec object and want to generate a diagram.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
NetSpec
|
The NetSpec to generate a diagram for |
required |
Returns:
| Type | Description |
|---|---|
str
|
Mermaid diagram as a string |