retroflow 0.1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- retroflow/__init__.py +45 -0
- retroflow/flowchart.py +194 -0
- retroflow/graph.py +192 -0
- retroflow/layout.py +302 -0
- retroflow/parser.py +99 -0
- retroflow/png_renderer.py +512 -0
- retroflow/py.typed +0 -0
- retroflow/renderer.py +252 -0
- retroflow-0.1.2.dist-info/METADATA +380 -0
- retroflow-0.1.2.dist-info/RECORD +12 -0
- retroflow-0.1.2.dist-info/WHEEL +4 -0
- retroflow-0.1.2.dist-info/licenses/LICENSE +21 -0
retroflow/layout.py
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Layout module for flowchart generator.
|
|
3
|
+
|
|
4
|
+
Implements sophisticated layout algorithms for positioning nodes.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import math
|
|
8
|
+
from collections import deque
|
|
9
|
+
from typing import Dict, List, Tuple
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class LayoutAlgorithm:
|
|
13
|
+
"""
|
|
14
|
+
Implements a layered graph layout algorithm (Sugiyama-style).
|
|
15
|
+
|
|
16
|
+
The algorithm works in phases:
|
|
17
|
+
1. Layer assignment - assign nodes to vertical layers
|
|
18
|
+
2. Crossing minimization - order nodes within layers
|
|
19
|
+
3. Horizontal positioning - position nodes to minimize width
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(self, graph, horizontal_spacing=4, vertical_spacing=3):
|
|
23
|
+
self.graph = graph
|
|
24
|
+
self.horizontal_spacing = horizontal_spacing
|
|
25
|
+
self.vertical_spacing = vertical_spacing
|
|
26
|
+
self.layers = [] # List of lists of nodes
|
|
27
|
+
self.positions = {} # node -> (x, y) in layer coordinates
|
|
28
|
+
self.feedback_edges = []
|
|
29
|
+
|
|
30
|
+
def compute_layout(self) -> Dict[str, Tuple[int, int]]:
|
|
31
|
+
"""
|
|
32
|
+
Compute layout positions for all nodes.
|
|
33
|
+
|
|
34
|
+
Returns:
|
|
35
|
+
Dictionary mapping node names to (layer, position_in_layer) tuples
|
|
36
|
+
"""
|
|
37
|
+
# Phase 1: Handle cycles by finding feedback edges
|
|
38
|
+
self._handle_cycles()
|
|
39
|
+
|
|
40
|
+
# Phase 2: Assign nodes to layers
|
|
41
|
+
self._assign_layers()
|
|
42
|
+
|
|
43
|
+
# Phase 3: Minimize crossings
|
|
44
|
+
self._minimize_crossings()
|
|
45
|
+
|
|
46
|
+
# Phase 4: Optimize for square layout
|
|
47
|
+
self._optimize_for_square_layout()
|
|
48
|
+
|
|
49
|
+
# Phase 5: Assign final positions
|
|
50
|
+
self._assign_positions()
|
|
51
|
+
|
|
52
|
+
return self.positions
|
|
53
|
+
|
|
54
|
+
def _handle_cycles(self):
|
|
55
|
+
"""Identify feedback edges to break cycles."""
|
|
56
|
+
self.feedback_edges = self.graph.find_feedback_edges()
|
|
57
|
+
|
|
58
|
+
def _is_feedback_edge(self, source: str, target: str) -> bool:
|
|
59
|
+
"""Check if an edge is a feedback edge."""
|
|
60
|
+
return (source, target) in self.feedback_edges
|
|
61
|
+
|
|
62
|
+
def _assign_layers(self):
|
|
63
|
+
"""
|
|
64
|
+
Assign nodes to layers using longest path layering.
|
|
65
|
+
This minimizes edge span.
|
|
66
|
+
"""
|
|
67
|
+
# Calculate layer for each node (longest path from roots)
|
|
68
|
+
node_layers = {}
|
|
69
|
+
|
|
70
|
+
# Start with roots
|
|
71
|
+
roots = self.graph.get_roots()
|
|
72
|
+
if not roots:
|
|
73
|
+
# If no roots (cycle), pick nodes with minimum in-degree
|
|
74
|
+
in_degrees = {
|
|
75
|
+
node: len(
|
|
76
|
+
[
|
|
77
|
+
s
|
|
78
|
+
for s in self.graph.get_predecessors(node)
|
|
79
|
+
if not self._is_feedback_edge(s, node)
|
|
80
|
+
]
|
|
81
|
+
)
|
|
82
|
+
for node in self.graph.nodes
|
|
83
|
+
}
|
|
84
|
+
roots = [
|
|
85
|
+
node
|
|
86
|
+
for node, deg in in_degrees.items()
|
|
87
|
+
if deg == min(in_degrees.values())
|
|
88
|
+
]
|
|
89
|
+
|
|
90
|
+
# BFS to assign layers
|
|
91
|
+
queue = deque([(node, 0) for node in roots])
|
|
92
|
+
visited = set()
|
|
93
|
+
|
|
94
|
+
while queue:
|
|
95
|
+
node, layer = queue.popleft()
|
|
96
|
+
|
|
97
|
+
if node in visited:
|
|
98
|
+
# Update layer if we found a longer path
|
|
99
|
+
node_layers[node] = max(node_layers.get(node, 0), layer)
|
|
100
|
+
continue
|
|
101
|
+
|
|
102
|
+
visited.add(node)
|
|
103
|
+
node_layers[node] = layer
|
|
104
|
+
|
|
105
|
+
# Add successors (ignoring feedback edges)
|
|
106
|
+
for successor in self.graph.get_successors(node):
|
|
107
|
+
if not self._is_feedback_edge(node, successor):
|
|
108
|
+
queue.append((successor, layer + 1))
|
|
109
|
+
|
|
110
|
+
# Handle any unvisited nodes (shouldn't happen but be safe)
|
|
111
|
+
for node in self.graph.nodes:
|
|
112
|
+
if node not in node_layers:
|
|
113
|
+
node_layers[node] = 0
|
|
114
|
+
|
|
115
|
+
# Group nodes by layer
|
|
116
|
+
max_layer = max(node_layers.values()) if node_layers else 0
|
|
117
|
+
self.layers = [[] for _ in range(max_layer + 1)]
|
|
118
|
+
|
|
119
|
+
for node, layer in node_layers.items():
|
|
120
|
+
self.layers[layer].append(node)
|
|
121
|
+
|
|
122
|
+
def _minimize_crossings(self):
|
|
123
|
+
"""
|
|
124
|
+
Minimize edge crossings using barycenter heuristic.
|
|
125
|
+
Iteratively reorder nodes within layers.
|
|
126
|
+
"""
|
|
127
|
+
if len(self.layers) <= 1:
|
|
128
|
+
return
|
|
129
|
+
|
|
130
|
+
# Perform multiple passes
|
|
131
|
+
for iteration in range(3):
|
|
132
|
+
# Forward pass (top to bottom)
|
|
133
|
+
for i in range(1, len(self.layers)):
|
|
134
|
+
self._reorder_layer(i, self.layers[i - 1])
|
|
135
|
+
|
|
136
|
+
# Backward pass (bottom to top)
|
|
137
|
+
for i in range(len(self.layers) - 2, -1, -1):
|
|
138
|
+
self._reorder_layer(i, self.layers[i + 1])
|
|
139
|
+
|
|
140
|
+
def _reorder_layer(self, layer_idx: int, reference_layer: List[str]):
|
|
141
|
+
"""Reorder nodes in a layer based on barycenter of connected nodes."""
|
|
142
|
+
layer = self.layers[layer_idx]
|
|
143
|
+
|
|
144
|
+
# Calculate barycenter for each node
|
|
145
|
+
barycenters = []
|
|
146
|
+
for node in layer:
|
|
147
|
+
positions = []
|
|
148
|
+
|
|
149
|
+
# Get positions of connected nodes in reference layer
|
|
150
|
+
for ref_node in reference_layer:
|
|
151
|
+
ref_pos = reference_layer.index(ref_node)
|
|
152
|
+
|
|
153
|
+
# Check if connected (either direction, skip feedback edges)
|
|
154
|
+
if node in self.graph.get_successors(ref_node):
|
|
155
|
+
if not self._is_feedback_edge(ref_node, node):
|
|
156
|
+
positions.append(ref_pos)
|
|
157
|
+
if node in self.graph.get_predecessors(ref_node):
|
|
158
|
+
if not self._is_feedback_edge(node, ref_node):
|
|
159
|
+
positions.append(ref_pos)
|
|
160
|
+
|
|
161
|
+
# Calculate barycenter
|
|
162
|
+
if positions:
|
|
163
|
+
barycenter = sum(positions) / len(positions)
|
|
164
|
+
else:
|
|
165
|
+
barycenter = len(reference_layer) / 2 # Center if no connections
|
|
166
|
+
|
|
167
|
+
barycenters.append((barycenter, node))
|
|
168
|
+
|
|
169
|
+
# Sort by barycenter
|
|
170
|
+
barycenters.sort()
|
|
171
|
+
self.layers[layer_idx] = [node for _, node in barycenters]
|
|
172
|
+
|
|
173
|
+
def _optimize_for_square_layout(self):
|
|
174
|
+
"""
|
|
175
|
+
Optimize layer distribution to create a more square-like layout.
|
|
176
|
+
Tries to balance height vs width.
|
|
177
|
+
"""
|
|
178
|
+
total_nodes = len(self.graph.nodes)
|
|
179
|
+
if total_nodes == 0:
|
|
180
|
+
return
|
|
181
|
+
|
|
182
|
+
# Calculate ideal aspect ratio (closer to 1 = more square)
|
|
183
|
+
ideal_layers = math.ceil(math.sqrt(total_nodes))
|
|
184
|
+
current_layers = len(self.layers)
|
|
185
|
+
|
|
186
|
+
# If we have too many layers, try to redistribute
|
|
187
|
+
if current_layers > ideal_layers * 1.5:
|
|
188
|
+
self._redistribute_layers(ideal_layers)
|
|
189
|
+
|
|
190
|
+
def _redistribute_layers(self, target_layer_count: int):
|
|
191
|
+
"""
|
|
192
|
+
Redistribute nodes across fewer layers to create wider layout.
|
|
193
|
+
This is a heuristic approach.
|
|
194
|
+
"""
|
|
195
|
+
if len(self.layers) <= target_layer_count:
|
|
196
|
+
return
|
|
197
|
+
|
|
198
|
+
# Calculate compression ratio
|
|
199
|
+
compression = len(self.layers) / target_layer_count
|
|
200
|
+
|
|
201
|
+
# Create new layer assignment
|
|
202
|
+
new_layers = [[] for _ in range(target_layer_count)]
|
|
203
|
+
|
|
204
|
+
for old_layer_idx, layer in enumerate(self.layers):
|
|
205
|
+
new_layer_idx = min(
|
|
206
|
+
int(old_layer_idx / compression), target_layer_count - 1
|
|
207
|
+
)
|
|
208
|
+
new_layers[new_layer_idx].extend(layer)
|
|
209
|
+
|
|
210
|
+
# Only apply if it doesn't create too-wide layers
|
|
211
|
+
max_width = max(len(layer) for layer in new_layers)
|
|
212
|
+
if max_width <= target_layer_count * 1.5:
|
|
213
|
+
self.layers = new_layers
|
|
214
|
+
|
|
215
|
+
def _assign_positions(self):
|
|
216
|
+
"""Assign final (x, y) positions to nodes."""
|
|
217
|
+
self.positions = {}
|
|
218
|
+
|
|
219
|
+
for layer_idx, layer in enumerate(self.layers):
|
|
220
|
+
for pos_idx, node in enumerate(layer):
|
|
221
|
+
# y position based on layer
|
|
222
|
+
y = layer_idx
|
|
223
|
+
# x position based on position in layer
|
|
224
|
+
x = pos_idx
|
|
225
|
+
self.positions[node] = (x, y)
|
|
226
|
+
|
|
227
|
+
def get_layout_dimensions(self) -> Tuple[int, int]:
|
|
228
|
+
"""
|
|
229
|
+
Get the dimensions of the layout in layer coordinates.
|
|
230
|
+
|
|
231
|
+
Returns:
|
|
232
|
+
(width, height) tuple
|
|
233
|
+
"""
|
|
234
|
+
if not self.layers:
|
|
235
|
+
return (0, 0)
|
|
236
|
+
|
|
237
|
+
width = max(len(layer) for layer in self.layers)
|
|
238
|
+
height = len(self.layers)
|
|
239
|
+
|
|
240
|
+
return (width, height)
|
|
241
|
+
|
|
242
|
+
def get_edges_for_rendering(self) -> List[Tuple[str, str, bool]]:
|
|
243
|
+
"""
|
|
244
|
+
Get edges with information about whether they're reversed.
|
|
245
|
+
|
|
246
|
+
Returns:
|
|
247
|
+
List of (source, target, is_feedback) tuples
|
|
248
|
+
"""
|
|
249
|
+
edges = []
|
|
250
|
+
for source, target in self.graph.edges:
|
|
251
|
+
is_feedback = self._is_feedback_edge(source, target)
|
|
252
|
+
edges.append((source, target, is_feedback))
|
|
253
|
+
return edges
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
class SimpleLayout:
|
|
257
|
+
"""Simpler vertical layout for small graphs."""
|
|
258
|
+
|
|
259
|
+
def __init__(self, graph):
|
|
260
|
+
self.graph = graph
|
|
261
|
+
self.positions = {}
|
|
262
|
+
|
|
263
|
+
def compute_layout(self) -> Dict[str, Tuple[int, int]]:
|
|
264
|
+
"""Compute simple vertical layout."""
|
|
265
|
+
nodes = self.graph.topological_sort()
|
|
266
|
+
|
|
267
|
+
for idx, node in enumerate(nodes):
|
|
268
|
+
self.positions[node] = (0, idx)
|
|
269
|
+
|
|
270
|
+
return self.positions
|
|
271
|
+
|
|
272
|
+
def get_layout_dimensions(self) -> Tuple[int, int]:
|
|
273
|
+
"""Get layout dimensions."""
|
|
274
|
+
if not self.positions:
|
|
275
|
+
return (0, 0)
|
|
276
|
+
return (1, len(self.positions))
|
|
277
|
+
|
|
278
|
+
def get_edges_for_rendering(self) -> List[Tuple[str, str, bool]]:
|
|
279
|
+
"""Get edges for rendering."""
|
|
280
|
+
return [(s, t, False) for s, t in self.graph.edges]
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def compute_layout(graph, algorithm="layered", **kwargs) -> LayoutAlgorithm:
|
|
284
|
+
"""
|
|
285
|
+
Compute layout for a graph.
|
|
286
|
+
|
|
287
|
+
Args:
|
|
288
|
+
graph: Graph object
|
|
289
|
+
algorithm: 'layered' or 'simple'
|
|
290
|
+
**kwargs: Additional parameters for layout algorithm
|
|
291
|
+
|
|
292
|
+
Returns:
|
|
293
|
+
Layout object with computed positions
|
|
294
|
+
"""
|
|
295
|
+
if algorithm == "simple" or len(graph.nodes) <= 3:
|
|
296
|
+
layout = SimpleLayout(graph)
|
|
297
|
+
layout.compute_layout()
|
|
298
|
+
return layout
|
|
299
|
+
else:
|
|
300
|
+
layout = LayoutAlgorithm(graph, **kwargs)
|
|
301
|
+
layout.compute_layout()
|
|
302
|
+
return layout
|
retroflow/parser.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Parser module for flowchart generator.
|
|
3
|
+
|
|
4
|
+
Handles parsing of input text into graph connections.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import List, Tuple
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ParseError(Exception):
|
|
11
|
+
"""Raised when input parsing fails."""
|
|
12
|
+
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Parser:
|
|
17
|
+
"""Parses flowchart input text into connections."""
|
|
18
|
+
|
|
19
|
+
def __init__(self):
|
|
20
|
+
self.connections = []
|
|
21
|
+
|
|
22
|
+
def parse(self, input_text: str) -> List[Tuple[str, str]]:
|
|
23
|
+
"""
|
|
24
|
+
Parse input text and return list of (source, target) connections.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
input_text: Multi-line string with connections in format "A -> B"
|
|
28
|
+
|
|
29
|
+
Returns:
|
|
30
|
+
List of (source, target) tuples
|
|
31
|
+
|
|
32
|
+
Raises:
|
|
33
|
+
ParseError: If input format is invalid
|
|
34
|
+
"""
|
|
35
|
+
connections = []
|
|
36
|
+
|
|
37
|
+
for line_num, line in enumerate(input_text.strip().split("\n"), 1):
|
|
38
|
+
line = line.strip()
|
|
39
|
+
|
|
40
|
+
# Skip empty lines and comments
|
|
41
|
+
if not line or line.startswith("#"):
|
|
42
|
+
continue
|
|
43
|
+
|
|
44
|
+
# Check for arrow
|
|
45
|
+
if "->" not in line:
|
|
46
|
+
raise ParseError(
|
|
47
|
+
f"Line {line_num}: Expected '->' in connection: {line}"
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
# Split on arrow
|
|
51
|
+
parts = line.split("->")
|
|
52
|
+
if len(parts) != 2:
|
|
53
|
+
raise ParseError(f"Line {line_num}: Invalid connection format: {line}")
|
|
54
|
+
|
|
55
|
+
source = parts[0].strip()
|
|
56
|
+
target = parts[1].strip()
|
|
57
|
+
|
|
58
|
+
# Validate node names
|
|
59
|
+
if not source:
|
|
60
|
+
raise ParseError(f"Line {line_num}: Empty source node")
|
|
61
|
+
if not target:
|
|
62
|
+
raise ParseError(f"Line {line_num}: Empty target node")
|
|
63
|
+
|
|
64
|
+
connections.append((source, target))
|
|
65
|
+
|
|
66
|
+
if not connections:
|
|
67
|
+
raise ParseError("No valid connections found in input")
|
|
68
|
+
|
|
69
|
+
return connections
|
|
70
|
+
|
|
71
|
+
def get_all_nodes(self, connections: List[Tuple[str, str]]) -> List[str]:
|
|
72
|
+
"""
|
|
73
|
+
Extract all unique nodes from connections.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
connections: List of (source, target) tuples
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
Sorted list of unique node names
|
|
80
|
+
"""
|
|
81
|
+
nodes = set()
|
|
82
|
+
for source, target in connections:
|
|
83
|
+
nodes.add(source)
|
|
84
|
+
nodes.add(target)
|
|
85
|
+
return sorted(nodes)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def parse_flowchart(input_text: str) -> List[Tuple[str, str]]:
|
|
89
|
+
"""
|
|
90
|
+
Convenience function to parse flowchart input.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
input_text: Multi-line string with connections
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
List of (source, target) tuples
|
|
97
|
+
"""
|
|
98
|
+
parser = Parser()
|
|
99
|
+
return parser.parse(input_text)
|