# Topdown Layout

Property | Value
--- | ---
Type: | advanced
Identifier: | `org.eclipse.elk.topdownLayout`
Meta Data Provider: | `core.options.CoreOptions`
Value Type: | `boolean`
Default Value: | `false` (as defined in `org.eclipse.elk`)
Applies To: | parents
Dependencies: | org.eclipse.elk.topdown.nodeType

### Description

Turns topdown layout on and off. If this option is enabled, hierarchical layout will be computed first for the root node and then for its children recursively. Layouts are then scaled down to fit the area provided by their parents. Graphs must follow a certain structure for topdown layout to work properly. {@link TopdownNodeTypes.PARALLEL_NODE} nodes must have children of type {@link TopdownNodeTypes.HIERARCHICAL_NODE} and must define {@link topdown.hierarchicalNodeWidth} and {@link topdown.hierarchicalNodeAspectRatio} for their children. Furthermore they need to be laid out using an algorithm that is a {@link TopdownLayoutProvider}. Hierarchical nodes can also be parents of other hierarchical nodes and can optionally use a {@link TopdownSizeApproximator} to dynamically set sizes during topdown layout. In this case {@link topdown.hierarchicalNodeWidth} and {@link topdown.hierarchicalNodeAspectRatio} should be set on the node itself rather than the parent. The values are then used by the size approximator as base values. Hierarchical nodes require the layout option {@link nodeSize.fixedGraphSize} to be true to prevent the algorithm used there from resizing the hierarchical node. This option is not supported if ‘Hierarchy Handling’ is set to ‘INCLUDE_CHILDREN’

## Additional Documentation

## Summary

Topdown Layout introduces the ability to compute hierarchical layouts from the root node down rather than the existing method of performing layout bottom-up. This shakes up some paradigms and allows new types of visualizations. Instead of child nodes determining the size of their parents, child nodes can now be restricted in their size by their parent. Inner layouts are then scaled down to fit their parent available space. This has the result that nodes within a hierarchy are visually more equal.

## Features & Usage

### Topdown Recursive Layout

The core feature of this PR is the ability to compute a hierarchical layout from the root node down instead of up from the leaves. This is implemented within the `RecursiveGraphLayoutEngine` and the details of how to use the feature are outlined below.

#### Simple Topdown Layout

In general topdown layout can be used to scale down inner layouts. In the basic usage nodes on the same hierarchy level are assigned the same size regardless of their content. To get this behaviour all nodes should have the `org.eclipse.elk.topdownLayout` property set to `true`. The graph itself needs its `org.eclipse.elk.topdown.nodeType` to be set to `ROOT_NODE`. Other nodes need to set their node type to `HIERARCHICAL_NODE`, `org.eclipse.elk.nodeSize.fixedGraphSize` to true and `org.eclipse.elk.algorithm` to any algorithm that supports `org.eclipse.elk.nodeSize.fixedGraphSize`. Additionally node sizes can be dynamically determined with the the help of a size approximator.

#### Topdown Layout with Lookahead

Sometimes it is desirable to not layout all nodes on a hierarchy level with equal sizes, but to instead vary the node sizes depending on their content. In topdown layout the node sizes must be defined ahead of their own layout however because they need to be laid out themselves first. In order to accomplish this a `PARALLEL_NODE` node type and an `ITopdownLayoutProvider` is introduced. Layout providers that implement this interface need to be able to predict the output size of their layout before they compute the layout. In the layout these nodes will not be scaled down. Parallel nodes have the further restriction that their parent and children must all be hierarchical nodes. The following properties have to be set on a parallel node:

- `org.eclipse.elk.topdownLayout=true`
- `org.eclipse.elk.topdown.nodeType=PARALLEL_NODE`
- `org.eclipse.elk.algorithm` must be set to an algorithm that implements `ITopdownLayoutProvider`
- `org.eclipse.elk.topdown.hierarchicalNodeWidth` (optional: defaults work too)
- `org.eclipse.elk.topdown.hierarchicalNodeAspectRatio` (optional: defaults work too)

### Topdown Packing Algorithm

This algorithm is a simple box packing algorithm that places equally sized nodes in a grid and eliminates any whitespace at the end by expanding nodes. It implements the `ITopdownLayoutProvider` interface and using it for topdown layout is its primary purpose although it can also be used on its own. The algorithm has two phases (Node placement and Whitespace elimination) for both of which there is currently one available strategy.

### New Properties

In this section the new topdown layout specific properties are explained in more detail.

#### Topdown Layout

`org.eclipse.elk.topdownLayout: boolean` Tells the recursive layout engine that a graph should be laid out using topdown layout. Must be set to the same value for all nodes of the graph. The default value is false.

#### Topdown Scale Factor

`org.eclipse.elk.topdown.scaleFactor: double` This property is calculated during topdown layout and is later used to correctly render the diagram. The topdown scale factor defines the amount by which the nodes children (as a group) need to be scaled so that they fit in their available space.

#### Topdown Hierarchical Node Width

`org.eclipse.elk.topdown.hierarchicalNodeWidth: boolean` This property is important when using parallel nodes. This value defines the width of each child node. This needs to be set on the parent and applies to all children. This is important so that the `ITopdownLayoutProvider` can provide a size prediction.

#### Topdown Hierarchical Node Aspect Ratio

`org.eclipse.elk.topdown.hierarchicalNodeAspectRatio: boolean` This property is important when using parallel nodes. This value defines the aspect ratio of each child node. This is then used together with the previous property to determine the height of each node. This needs to be set on the parent and applies to all children. This is important so that the `ITopdownLayoutProvider` can provide a size prediction.

With both of these properties care must be taken when setting the paddings of the children. The paddings must leave enough space for the node i.e. `padding.left + padding.right

#### Topdown Node Type

`org.eclipse.elk.topdown.nodeType: TopdownNodeTypes` There are two node types: `HIERARCHICAL_NODE` and `PARALLEL_NODE`. Hierarchical nodes are the basic building blocks of topdown layout they can generally be used without needing to pay attention to many constraints. Parallel nodes allow constructing topdown layouts with a lookahead allowing nodes to have sizes depending on what is inside them. Using them comes with some restrictions as already outlined.

#### Child Area Width and Child Area Height

`org.eclipse.elk.topdown.childAreaWidth: double`, `org.eclipse.elk.topdown.childAreaHeight: double` These properties are used internally to determine the size occupied by a layout. The properties are there so that algorithms that already compute these values can store them directly for later use. Otherwise they are computed by the recursive layout engine.

#### Topdown Scale Cap

`org.eclipse.elk.topdown.scaleCap: double` This value sets an upper limit on the resulting topdown scale factor that is possible. The default value is 1, which means that child nodes will never be scaled up. This means that they may not fully use the available space, but they also do not appear larger (relative with respect to their texts, line widths etc.) than their parents as this seems like generally undesirable behaviour. This property allows some flexibility to configure this within a graph.

#### Topdown Size Approximator

`org.eclipse.elk.topdown.sizeApproximator: TopdownSizeApproximator` A size approximator can only be set on hierarchical nodes and will use a given ELK node to determine a suitable size for the node before computing its layout. The `COUNT_CHILDREN` size approximator uses `sqrt(number_of_children)` as proportional factor for the node sizes. Size approximators can be made arbitrarily complex.

## Requirements

For the result layouts to be rendered correctly the viewer must support the topdown scale factor property as demonstrated in klighd-vscode/mka/topdown. When using KlighD to create topdown diagrams, hierarchical nodes require an explicit child area to be defined so that the viewer will know what part of the rendering the topdown scale factor needs to be applied to.

## Example Diagrams

The below images show some ways that topdown layout can be used.

### Layered, Force and Stress used in hierarchical nodes

### Hierarchical and parallel nodes alternating

SCCharts provide a practical use case for alternating hierarchical and parallel nodes because this structure is already inherent in the diagrams through the alternation of regions and states.

### Large SCChart

### Large mixed example

All these features can be mixed quite flexibly, but it can become quite complex. Here is an example showing a mixed composition of node types and algorithms.

- Algorithms
- Draw2D Layout
- ELK Box
- ELK DisCo
- ELK Fixed
- ELK Force
- ELK Layered
- ELK Mr. Tree
- ELK Radial
- ELK Randomizer
- ELK Rectangle Packing
- ELK SPOrE Compaction
- ELK SPOrE Overlap Removal
- ELK Stress
- ELK Top-down Packing
- ELK VertiFlex
- Graphviz Circo
- Graphviz Dot
- Graphviz FDP
- Graphviz Neato
- Graphviz Twopi
- Libavoid
- Layout Options
- Activate Inside Self Loops
- Adapt Port Positions
- Add Unnecessary Bendpoints
- Additional Port Space
- Additional Wedge Space
- Additional Wrapped Edges Spacing
- Alignment
- Allow Non-Flow Ports To Switch Sides
- Angle Penalty
- Animate
- Animation Time Factor
- Annulus Wedge Criteria
- Aspect Ratio
- Bend Points
- BK Edge Straightening
- BK Fixed Alignment
- Box Layout Mode
- Center On Root
- Child Area Height
- Child Area Width
- Cluster Crossing Penalty
- Comment Box
- Comment Comment Spacing
- Comment Node Spacing
- Compaction
- Compaction iterations
- Compaction Step Size
- Compaction Strategy
- Compaction Strategy
- Components Spacing
- Concentrate Edges
- Connected Components Compaction
- Connected Components Compaction Strategy
- Connected Components Layout Algorithm
- Consider Model Order
- Consider Model Order for Components
- Consider node model order
- Consider Port Order
- Content Alignment
- Correction Factor for Wrapping
- Cost Function for Spanning Tree
- Crossing Counter Node Order Influence
- Crossing Counter Port Order Influence
- Crossing Minimization Enforced Group Orders
- Crossing Minimization Group Ordering Strategy
- Crossing Minimization Strategy
- Crossing Penalty
- Current position of a node in the order of nodes
- Cutting Strategy
- Cycle Breaking Group Ordering Strategy
- Cycle Breaking Preferred Source Id
- Cycle Breaking Preferred Target Id
- Cycle Breaking Strategy
- DCGraph
- Debug Mode
- Default process timeout.
- Desired Edge Length
- Desired index of node
- Direction
- Direction Congruency
- Direction Priority
- Distance Model
- Distance Penalty When Improving Cuts
- Eades Repulsion
- Edge Center Label Placement Strategy
- Edge Coords
- Edge Edge Between Layer Spacing
- Edge End Texture Length
- Edge Label Placement
- Edge Label Side Selection
- Edge Label Spacing
- Edge layout strategy
- Edge Node Between Layers Spacing
- Edge Node Spacing
- Edge Routing
- Edge Routing Mode
- Edge Spacing
- Edge Thickness
- Edge Type
- Enable Hyperedges From Common Source
- Epsilon
- Expand Nodes
- Favor Straight Edges Over Balancing
- Feedback Edges
- Fill Polyominoes
- Fixed Graph Size
- Fixed Position
- Fixed Shared Path Penalty
- Fixed vertical position
- Font Name
- Font Size
- Force Model
- Force Node Model Order
- FR Temperature
- Generate Position and Layer IDs
- Graph Wrapping Strategy
- Greedy Switch Activation Threshold
- Greedy Switch Crossing Minimization
- Greedy Switch Crossing Minimization (hierarchical)
- Group ID of the Node Type
- Group ID of the Node Type
- Group ID of the Node Type
- Hierarchical Sweepiness
- Hierarchy Handling
- Hierarchy Handling (Graphviz Dot)
- High Degree Node Maximum Tree Height
- High Degree Node Threshold
- High Degree Node Treatment
- Horizontal spacing between Label and Port
- Hypernode
- Ideal Nudging Distance
- Improve Cuts
- Improve Hyperedge Routes
- Improve Hyperedge Routes Add/Delete
- Improve Wrapped Edges
- In Layer Predecessor of
- In Layer Successor of
- In new Row
- Individual Spacing
- Individual Spacing (ELK Layered)
- Inline Edge Labels
- Inside Self Loop
- Interactive
- interactive Layout
- Interactive Reference Point
- Iteration Limit
- Iterations
- Iterations Factor
- Junction Points
- Label Angle
- Label Distance
- Label Manager
- Label Manager
- Label Node Spacing
- Label Spacing
- Layer Bound
- Layer Choice Constraint
- Layer Constraint
- Layer distance
- Layer ID
- Layer Spacing Factor
- Layer Unzipping Strategy
- Layout Algorithm
- Layout Ancestors
- Layout Dimension
- Layout Partition
- Layout Partitioning
- Linear Segments Deflection Dampening
- List of Polyominoes
- Long Edge Ordering Strategy
- Manually Specified Cuts
- Margins
- Marks a node as a cluster
- Max Node Promotion Iterations
- Max. Iterations
- Maximal Animation Time
- Merge Edges
- Merge Hierarchy-Crossing Edges
- Minimal Animation Time
- Minimize Edge Length Heuristic
- MSD Freedom
- No Layout
- No Model Order
- Node arrangement strategy
- Node Flexibility
- Node Flexibility Default
- Node Label Padding
- Node Label Placement
- Node Layering Strategy
- Node Node Between Layers Spacing
- Node Placement Strategy
- Node Promotion Strategy
- Node Self Loop Spacing
- Node Size Constraints
- Node Size Minimum
- Node Size Options
- Node Spacing
- Nudge Orthogonal Segments
- Nudge Orthogonal Touching Colinear Segments
- Nudge Shared Paths With Common Endpoint
- Number of size categories
- Omit Node Micro Layout
- Optimization Goal
- Order ID
- Order nodes by height
- Orthogonal Compaction
- Outgoing Edge Angles
- Overlap Removal
- Padding
- Penalise Orthogonal Shared Paths
- Perform Unifying Nudging Preprocessing
- Polyomino Primary Sorting Criterion
- Polyomino Secondary Sorting Criterion
- Polyomino Traversal Strategy
- Port Alignment
- Port Alignment (East)
- Port Alignment (North)
- Port Alignment (South)
- Port Alignment (West)
- Port Anchor Offset
- Port Border Offset
- Port Constraints
- Port Direction Penalty
- Port Index
- Port Label Placement
- Port Labels Next to Port
- Port Side
- Port Sorting Strategy
- Port Spacing
- Position
- Position Choice Constraint
- Position Constraint
- Position Constraint
- Position ID
- Post Compaction Constraint Calculation
- Post Compaction Strategy
- Priority
- Priority (ELK Box)
- Priority (ELK Force)
- Priority (ELK Layered)
- Priority (ELK Mr. Tree)
- Progress Bar
- Radius
- Randomization Seed
- Repulsive Power
- Reset Alternation on Long Edges
- Resolved Layout Algorithm
- Reverse Direction Penalty
- Root node for spanning tree construction
- Root selection for spanning tree
- Rotate
- Row Height Reevaluation
- Scale Factor
- Search Order
- Segment Penalty
- Self-Loop Distribution
- Self-Loop Ordering
- Semi-Interactive Crossing Minimization
- Separate Connected Components
- Shape Buffer Distance
- Shape Coords
- Shift Last Placed.
- Shortness Priority
- Shortness Priority (ELK Layered)
- Sloped Edge Zone Width
- Sloppy Spline Layer Spacing Factor
- Softwrapping Fuzziness
- Sorter
- Spacing Base Value
- Spline Routing Mode
- Straightness Priority
- Stress Epsilon
- Structure Extraction Strategy
- Target Angle
- Target Width
- Thoroughness
- Topdown Hierarchical Node Aspect Ratio
- Topdown Hierarchical Node Width
- Topdown Layout
- Topdown Node Type
- Topdown Scale Cap
- Topdown Scale Factor
- Topdown Size Approximator
- Translation Optimization
- Treat Port Labels as Group
- Tree Construction Strategy
- Tree Level
- Try box layout first
- Underlying Layout Algorithm
- Unzipping Layer Split
- Upper Bound On Width [MinWidth Layerer]
- Upper Layer Estimation Scaling Factor [MinWidth Layerer]
- Upper limit for iterations of overlap removal
- Valid Indices for Wrapping
- Validate Graph
- Validate Options
- Validification Strategy
- Vertical spacing between Label and Port
- Weight of a node containing children for determining the graph size
- Weighting of Nodes
- Whether to run a supplementary scanline overlap check.
- White Space Approximation Strategy
- Whitespace elimination strategy
- Width Approximation Strategy
- Zoom to Fit
- Layout Option Groups
- box
- compaction
- compaction
- compaction.postCompaction
- componentCompaction
- considerModelOrder
- considerModelOrder.groupModelOrder
- crossingMinimization
- crossingMinimization.greedySwitch
- crossingMinimization.greedySwitchHierarchical
- cycleBreaking
- debug
- edge
- edgeLabels
- edgeLabels
- edgeRouting
- edgeRouting.polyline
- edgeRouting.splines
- edgeRouting.splines.sloppy
- font
- highDegreeNodes
- insideSelfLoops
- json
- layering
- layering.coffmanGraham
- layering.minWidth
- layering.nodePromotion
- layerUnzipping
- nodeArrangement
- nodeLabels
- nodePlacement
- nodePlacement.bk
- nodePlacement.linearSegments
- nodePlacement.networkSimplex
- nodePlacement.networkSimplex.nodeFlexibility
- nodeSize
- overlapRemoval
- packing
- packing.compaction
- partitioning
- polyomino
- port
- portAlignment
- portLabels
- priority
- processingOrder
- rotation
- spacing
- spacing
- structure
- topdown
- whiteSpaceElimination
- whitespaceElimination
- widthApproximation
- wrapping
- wrapping.cutting
- wrapping.cutting.msd
- wrapping.multiEdge
- wrapping.singleEdge
- wrapping.validify