flatten
Flattens a hierarchical graph into a flat graph containing only leaf nodes. This function decomposes compound nodes (nodes with children) into a flat structure by:- Resolving edges targeting compound nodes to their initial child (recursively)
- Expanding edges originating from compound nodes to all leaf descendants
- Keeping only leaf nodes (nodes with no children) in the result
- Deduplicating edges that have the same source and target
Parameters
The hierarchical graph to flatten. The graph may contain compound nodes (nodes with
parentId and initialNodeId properties) and nested hierarchies.Returns
Returns a newGraph<N, E, G> containing:
- Only leaf nodes (nodes with no children) from the original graph
- Transformed edges where:
- Edges to compound nodes resolve to the compound’s initial child node (following
initialNodeIdrecursively) - Edges from compound nodes expand to multiple edges from all leaf descendants
- Duplicate edges are removed
- Self-loops created during flattening are removed
- Edges to compound nodes resolve to the compound’s initial child node (following
Example: Basic Hierarchy Flattening
Example: Multi-Level Hierarchy
Use Cases
Statechart Decomposition Theflatten function is particularly useful for statecharts and hierarchical state machines. It converts a compound state hierarchy into a flat representation suitable for:
- Generating transition tables
- Analyzing reachability between leaf states
- Simplifying state machine execution
- Export to formats that don’t support hierarchy
flatten to:
- Remove structural complexity while preserving connectivity
- Analyze the effective relationships between atomic nodes
- Prepare hierarchical graphs for algorithms that only work with flat structures
Edge Resolution Rules
When flattening a hierarchical graph, edges are transformed according to these rules: Target Resolution (Edges Into Compound Nodes)- If an edge targets a compound node, follow the compound’s
initialNodeIdrecursively until reaching a leaf node - If no
initialNodeIdis set, use the first child node - The edge resolves to a single target (the initial leaf)
- If an edge originates from a compound node, expand it to edges from all leaf descendants
- Each leaf descendant gets its own edge to the target
- This ensures all atomic nodes that are conceptually “inside” the compound have the connection
- Multiple edges with identical source and target are deduplicated
- Only one edge per source-target pair is kept
- Self-loops created during flattening are removed
Related
- Graph Types - Core graph type definitions
- createGraph - Create a new graph instance
- getChildren - Query child nodes in a hierarchy