Peano
Loading...
Searching...
No Matches
Graph.py
Go to the documentation of this file.
1# This file is part of the Peano project. For conditions of distribution and
2# use, please see the copyright notice at www.peano-framework.org
3
4from typing import List, Union
5
6from .Task import Task
7
8
9class Graph:
10 """!
11
12 Holds a sequence of Task instances
13
14 """
15
16 def __init__(self):
17 self.tasks: List[Task] = []
18
19 def add_task(self, task: Task):
20 self.tasks.append(task)
21
22 def append(self, other: "Graph"):
23 """!
24
25 Concatenate another graph behind this one
26
27 The end of this graph is connected to the start of the other one:
28 Every task of the other graph that depends on nothing within the other
29 graph (its sources) additionally depends on every task of this graph
30 that no other task of this graph depends on (its sinks, @ref sink_tasks()).
31 If a sink is a global task, the sources of the other graph depend on it,
32 and the task compiler does not fuse them into its mesh sweep
33 (@ref peano4.api.taskgraph.Task.Task.GridEntity).
34 All tasks of both graphs are kept, with their own dependencies, and
35 none is dropped or merged, even if the two graphs do the same work in
36 parts. Removing such redundancy is up to the caller. The other graph
37 remains untouched, but shares its task objects with this one.
38
39 Use merge() to put two graphs next to each other instead.
40
41 @param other: peano4.api.taskgraph.Graph
42 The graph that follows this one.
43
44 """
45 shared = [t for t in other.tasks if any(t is existing for existing in self.tasks)]
46 if shared:
47 raise ValueError(
48 "Cannot append a graph that shares tasks with this one: "
49 + ", ".join(t.name for t in shared)
50 )
51 sinks = self.sink_tasks()
52 sources = [
53 task
54 for task in other.tasks
55 if not any(dependency in other.tasks for dependency in task.dependencies)
56 ]
57 for source in sources:
58 for sink in sinks:
59 source.add_dependency(sink)
60 self.tasks.extend(other.tasks)
61
62 def merge(self, other: "Graph"):
63 """!
64
65 Add all tasks of another graph to this graph, next to the existing ones
66
67 The tasks keep their dependencies, i.e. the result is the union of the
68 two graphs: they run independently of each other unless the caller adds
69 the dependencies that connect them. The other graph remains untouched
70 and shares its task objects with this one. A task which both graphs
71 hold is added only once.
72
73 This is how a host that couples several solvers
74 (@ref page_exahype_programmers_guide_coupling) puts the task graphs side by side which
75 the solvers have built independently, before it wires them. Use
76 append() to run one graph after the other.
77
78 @param other: peano4.api.taskgraph.Graph
79 The graph whose tasks are added.
80
81 """
82 for task in other.tasks:
83 if not any(task is existing for existing in self.tasks):
84 self.tasks.append(task)
85
86 def find_tasks(self, *tags) -> List[Task]:
87 """!
88
89 Return all tasks of this graph which carry at least one of the tags,
90 in the order in which they have been added to the graph
91
92 A task which carries several of the tags is returned only once.
93
94 @param tags: str
95 One or several tags, i.e. strings which the tasks hold in their
96 set tags (@ref peano4.api.taskgraph.Task.Task).
97
98 """
99 return [task for task in self.tasks if any(tag in task.tags for tag in tags)]
100
101 def source_tasks(self) -> List[Task]:
102 """!
103
104 Return all tasks which depend on no other task of this graph
105
106 These are the first tasks of the graph, i.e. the counterpart of
107 sink_tasks(). Dependencies on tasks outside of the graph are ignored.
108 The tasks are returned in the order in which they have been added to
109 the graph.
110
111 """
112 return [
113 task
114 for task in self.tasks
115 if not any(dependency in self.tasks for dependency in task.dependencies)
116 ]
117
118 def sink_tasks(self) -> List[Task]:
119 """!
120
121 Return all tasks which no other task of this graph depends on
122
123 These are the last tasks of the graph. A graph that forks, e.g.
124 because two solvers each add their own chain of tasks, has more than
125 one of them. Make a task depend on all of them to run it after the
126 whole graph, e.g. to synchronise the solvers
127 (@ref page_exahype_programmers_guide_coupling). The tasks are
128 returned in the order in which they have been added to the graph.
129
130 """
131 return [
132 task
133 for task in self.tasks
134 if not any(task in other.dependencies for other in self.tasks)
135 ]
136
137 def insert_after(self, anchors: Union[Task, List[Task]], task: Task):
138 """!
139
140 Insert a task directly after one or several anchors
141
142 The routine adds task to the graph and makes it depend on all
143 anchors. All tasks which have depended on any of the anchors so far
144 depend on task instead. Consequently, task runs after the anchors
145 but before anything that used to follow them.
146
147 Use this routine to add a step to a task graph which someone else
148 has built, e.g. to postprocess the outcome of a task. task should
149 not depend on any other task yet, unless these dependencies run
150 before the anchors anyway.
151
152 Pass several anchors if several tasks produce one outcome together.
153 The optimistic Finite Volumes, for example, write the new solution
154 either in one task or in another, depending on the cell. A single
155 task inserted after both runs once per cell, after whichever of the
156 two has updated this cell. The anchors must not depend on each
157 other, neither directly nor indirectly, as the redirection would
158 create a cycle otherwise.
159
160 @param anchors: peano4.api.taskgraph.Task or List[peano4.api.taskgraph.Task]
161 One task or a list of tasks of this graph.
162
163 @param task: peano4.api.taskgraph.Task
164 The new task. It must not be part of the graph yet.
165
166 """
167 anchors = [anchors] if isinstance(anchors, Task) else list(anchors)
168 assert len(anchors) > 0, f"Task {task.name} needs at least one anchor"
169 for anchor in anchors:
170 assert anchor in self.tasks, f"Task {anchor.name} is not part of the graph"
171 assert task not in self.tasks, f"Task {task.name} is already part of the graph"
172 for anchor in anchors:
173 for other in anchors:
174 assert other is anchor or not self._depends_on(anchor, other), (
175 f"Anchor {anchor.name} depends on anchor {other.name}, so "
176 f"{task.name} cannot be inserted after both"
177 )
178 for successor in self.tasks:
179 if any(anchor in successor.dependencies for anchor in anchors):
180 redirected = []
181 for dependency in successor.dependencies:
182 replacement = (
183 task
184 if any(dependency is anchor for anchor in anchors)
185 else dependency
186 )
187 if replacement not in redirected:
188 redirected.append(replacement)
189 successor.dependencies = redirected
190 for anchor in anchors:
191 task.add_dependency(anchor)
192 self.add_task(task)
193
194 @staticmethod
195 def _depends_on(task: Task, other: Task) -> bool:
196 """! True if task depends on other, directly or indirectly"""
197 pending = list(task.dependencies)
198 visited = []
199 while pending:
200 dependency = pending.pop()
201 if dependency is other:
202 return True
203 if dependency not in visited:
204 visited.append(dependency)
205 pending += dependency.dependencies
206 return False
207
208 def ordered_tasks(self) -> List[Task]:
209 """!
210
211 Linearise this graph's tasks into the order
212 peano4.api.taskgraph.compiler.Sequential.translate() compiles them
213 into: a straightforward recursive traversal of the dependency DAG
214 (visit a task's dependencies before the task itself), which - since
215 every dependency is visited before whatever depends on it - yields
216 a valid topological order.
217
218 This is the single source of truth for "the task after this one"
219 that both translate() and
220 peano4.api.taskgraph.compiler.PropagateUseStatements.propagate_use_statements()
221 rely on; they must agree on the same order, since the latter's
222 whole job is to reason about which task's Observer immediately
223 follows which other one's once compiled.
224
225 Repeated calls recompute the order from scratch (cheap - task
226 graphs here are small) rather than caching it, so adding further
227 tasks/dependencies after an earlier call is always reflected.
228
229 Tasks of the kind GLOBAL_START_OF_STEP come first, as they may not
230 depend on other tasks. Tasks of the kind GLOBAL_END_OF_STEP come last
231 (@ref peano4.api.taskgraph.Task.Task.GridEntity), with one exception:
232 If another task depends on them (@ref anchored_end_of_step_tasks()), they
233 end the traversal of their last dependency and keep their place
234 among the other tasks. Within each of the three parts, the order is
235 the one of the traversal.
236
237 """
238 order: List[Task] = []
239 visited = set()
240
241 def visit(task: Task):
242 if task not in visited:
243 visited.add(task)
244 for dependency in task.dependencies:
245 visit(dependency)
246 order.append(task)
247
248 for task in self.tasks:
249 visit(task)
250 Entity = Task.GridEntity
251 trailing = [
252 task
253 for task in order
254 if task.entity == Entity.GLOBAL_END_OF_STEP
255 and task not in self.anchored_end_of_step_tasks()
256 ]
257 return (
258 [task for task in order if task.entity == Entity.GLOBAL_START_OF_STEP]
259 + [
260 task
261 for task in order
262 if task.entity != Entity.GLOBAL_START_OF_STEP and task not in trailing
263 ]
264 + trailing
265 )
266
267 def anchored_end_of_step_tasks(self) -> List[Task]:
268 """!
269
270 End-of-step tasks which do not run at the very end of the step
271
272 A GLOBAL_END_OF_STEP task runs last in the last traversal. If another
273 task depends on it, this cannot hold: The task has to finish its
274 traversal first, and the dependent task then runs in a later one.
275 Such a task thus ends the traversal of its last dependency instead
276 (@ref peano4.api.taskgraph.compiler.FuseSteps.translate()). The same
277 holds for each end-of-step task which such a task depends on in turn.
278
279 @return List[Task]
280 The tasks in the order in which they have been added to the graph.
281
282 """
283 end_tasks = [
284 task for task in self.tasks if task.entity == Task.GridEntity.GLOBAL_END_OF_STEP
285 ]
286 anchored = {
287 end
288 for end in end_tasks
289 if any(end in task.dependencies for task in self.tasks if task not in end_tasks)
290 }
291 changed = True
292 while changed:
293 changed = False
294 for end in end_tasks:
295 if end not in anchored and any(
296 end in other.dependencies for other in anchored
297 ):
298 anchored.add(end)
299 changed = True
300 return [end for end in end_tasks if end in anchored]
301
302 def log_as_text(self, title: str = "Task graph"):
303 """!
304 Textual counterpart to visualise(): logs a plain-text rendering of
305 this task graph through peano4.api.Logger(), for LoggerVerbosity.TEXT
306 runs, where a matplotlib window is neither wanted nor - in a batch/
307 non-interactive run - even possible.
308
309 Renders the same information visualise() draws as a UML state
310 diagram - every task's grid entity, its dependencies, its action
311 sets (as "do / <name>" lines), the cell/face/vertex submodels it
312 declares via use_cell()/use_face()/use_vertex() (each annotated
313 with its Task.DataAccess qualifier) and whether it repeats - as one
314 block of text per task, ordered root to sink by dependency depth
315 exactly like visualise() lays its layers out top to bottom.
316 """
317 import peano4.api
318
319 if not self.tasks:
320 peano4.api.Logger().log(f"Task graph '{title}' is empty.")
321 return
322
323 # Depth of a task = 0 if it has no dependencies, else 1 + the
324 # deepest of its dependencies. Recursive but memoised - task graphs
325 # here are small and acyclic by construction. @see visualise(),
326 # which computes the very same notion of depth to lay its layers
327 # out top to bottom.
328 depth_of_task = {}
329
330 def depth(task: Task) -> int:
331 if task not in depth_of_task:
332 depth_of_task[task] = (
333 0 if not task.dependencies else 1 + max(depth(dependency) for dependency in task.dependencies)
334 )
335 return depth_of_task[task]
336
337 ordered_tasks = sorted(self.tasks, key=depth)
338
339 lines = [f"Task graph '{title}':"]
340 for task in ordered_tasks:
341 lines.append(f"- {task.name} «{task.entity.name.lower()}»")
342 if task.dependencies:
343 lines.append(
344 " depends on: " + ", ".join(dependency.name for dependency in task.dependencies)
345 )
346 for action_set in task.action_sets:
347 lines.append(f" do / {action_set.get_action_set_name()}")
348 for kind, submodels, access in (
349 ("cell", task.cell_data, task.cell_data_access),
350 ("face", task.face_data, task.face_data_access),
351 ("vertex", task.vertex_data, task.vertex_data_access),
352 ):
353 if submodels:
354 lines.append(
355 f" {kind} / "
356 + ", ".join(f"{submodel.name} [{access[submodel].name}]" for submodel in submodels)
357 )
358 if task.has_to_repeat:
359 lines.append(f" repeats while: {task.has_to_repeat}")
360
361 peano4.api.Logger().log("\n".join(lines))
362
363 def visualise(self, title: str = "Task graph"):
364 """!
365 Render this task graph with matplotlib as a UML state diagram: one
366 rounded-rectangle state per task, a solid transition arrow from
367 every dependency to the task that depends on it. Tasks are laid
368 out top to bottom by dependency depth (a task without dependencies
369 sits at the top; everything that - directly or transitively -
370 depends on it sits below it), so following the transitions always
371 moves downwards, exactly like reading a state diagram's flow of
372 control. The tasks of one layer sit side by side: every task sits
373 straight below its leftmost dependency and is moved to the right
374 only where it would otherwise overlap another task.
375
376 A filled black circle - the UML initial pseudostate - transitions
377 into every task that has no dependencies; every task nothing else
378 depends on transitions into a bullseye - the UML final pseudostate.
379 A task with has_to_repeat set (i.e. not None) is additionally drawn
380 with a small self-transition loop right of its state, the standard UML
381 notation for "this state can re-trigger itself", labelled with the
382 task's has_to_repeat string itself.
383
384 Every action set attached to a task (@see Task.add_action_set) is
385 listed inside that task's own state box as a "do / <name>" line,
386 below a separator - the same internal-activity compartment a UML
387 state uses to list its entry/exit/do behaviours, as opposed to the
388 transition arrows between states, which describe order, not
389 ownership. The same compartment also lists the cell/face/vertex
390 submodels the task declares via use_cell()/use_face()/use_vertex()
391 as "cell / <name> [<Task.DataAccess>]" (and face/vertex
392 counterparts) lines, one per kind that is actually used.
393
394 Every state also carries a small coloured badge in its top-left
395 corner indicating which kind of grid entity (vertex/face/cell/
396 global) the task works on; a legend below the title spells out
397 what each colour means, restricted to the entity kinds actually
398 used in this particular graph.
399
400 Opens a blocking matplotlib window; close it to continue.
401 """
402 import matplotlib.pyplot as plt
403 from matplotlib.lines import Line2D
404 from matplotlib.patches import Circle, FancyArrowPatch, FancyBboxPatch
405 from matplotlib.path import Path
406
407 if not self.tasks:
408 print(f"Task graph '{title}' is empty - nothing to visualise.")
409 return
410
411 # Depth of a task = 0 if it has no dependencies, else 1 + the
412 # deepest of its dependencies. Recursive but memoised - task graphs
413 # here are small and acyclic by construction.
414 depth_of_task = {}
415
416 def depth(task: Task) -> int:
417 if task not in depth_of_task:
418 depth_of_task[task] = (
419 0 if not task.dependencies else 1 + max(depth(dependency) for dependency in task.dependencies)
420 )
421 return depth_of_task[task]
422
423 layers = {}
424 for task in self.tasks:
425 layers.setdefault(depth(task), []).append(task)
426
427 entity_colour = {
428 Task.GridEntity.VERTEX: "tab:blue",
429 Task.GridEntity.FACE: "tab:orange",
430 Task.GridEntity.CELL: "tab:green",
431 Task.GridEntity.GLOBAL: "tab:purple",
432 Task.GridEntity.GLOBAL_START_OF_STEP: "tab:red",
433 Task.GridEntity.GLOBAL_END_OF_STEP: "tab:brown",
434 }
435
436 # A state's box grows with its content: a fixed-height header
437 # (task name + «entity» stereotype) plus, if the task owns action
438 # sets, one "do / <name>" line per action set in a body
439 # compartment below a separator - mirroring how a UML state lists
440 # its internal entry/exit/do behaviours.
441 HEADER_HEIGHT = 0.52
442 ACTIVITY_LINE_HEIGHT = 0.22
443 BODY_PADDING = 0.14
444 MIN_WIDTH = 1.7
445 CHAR_WIDTH = 0.10
446 HORIZONTAL_GAP = 0.6
447 VERTICAL_GAP = 0.9
448
449 def activity_lines(task: Task):
450 lines = [f"do / {action_set.get_action_set_name()}" for action_set in task.action_sets]
451 for kind, submodels, access in (
452 ("cell", task.cell_data, task.cell_data_access),
453 ("face", task.face_data, task.face_data_access),
454 ("vertex", task.vertex_data, task.vertex_data_access),
455 ):
456 if submodels:
457 lines.append(
458 f"{kind} / "
459 + ", ".join(f"{submodel.name} [{access[submodel].name}]" for submodel in submodels)
460 )
461 return lines
462
463 width_of_task, height_of_task = {}, {}
464 for task in self.tasks:
465 lines = activity_lines(task)
466 longest_line = max([len(task.name)] + [len(line) for line in lines])
467 width_of_task[task] = max(MIN_WIDTH, CHAR_WIDTH * longest_line + 0.6)
468 height_of_task[task] = HEADER_HEIGHT + (
469 BODY_PADDING + len(lines) * ACTIVITY_LINE_HEIGHT + 0.5 * BODY_PADDING if lines else 0
470 )
471
472 SELF_LOOP_WIDTH = 0.4
473 SELF_LOOP_LABEL_CHAR_WIDTH = 0.065
474 PSEUDOSTATE_OFFSET = 0.6
475
476 # Horizontal space a task's self-transition loop and its label take
477 # right of the task's state
478 def self_loop_extent(task: Task) -> float:
479 if not task.has_to_repeat:
480 return 0.0
481 return SELF_LOOP_WIDTH + 0.06 + SELF_LOOP_LABEL_CHAR_WIDTH * len(task.has_to_repeat)
482
483 # Every layer forms one row. The rows are stacked top to bottom,
484 # each as tall as its tallest state. Every state is placed straight
485 # below its leftmost dependency, i.e. left-aligned with it, and
486 # moved to the right only if it would otherwise overlap the state
487 # left of it in the same row. States without dependencies start at
488 # x=0 and extend to the right.
489 position_of_task = {}
490 row_y = 0.0
491 for layer in sorted(layers):
492 def preferred_left_edge(task: Task) -> float:
493 if not task.dependencies:
494 return 0.0
495 return min(
496 position_of_task[dependency][0] - width_of_task[dependency] / 2
497 for dependency in task.dependencies
498 )
499
500 tasks_in_layer = sorted(layers[layer], key=preferred_left_edge)
501 row_height = max(height_of_task[task] for task in tasks_in_layer)
502 next_free_x = float("-inf")
503 for task in tasks_in_layer:
504 left_edge = max(preferred_left_edge(task), next_free_x)
505 position_of_task[task] = (left_edge + width_of_task[task] / 2, row_y - row_height / 2)
506 next_free_x = left_edge + width_of_task[task] + self_loop_extent(task) + HORIZONTAL_GAP
507 row_y -= row_height + VERTICAL_GAP
508 bottom_y = row_y + VERTICAL_GAP
509
510 root_tasks = [task for task in self.tasks if not task.dependencies]
511 sink_tasks = [
512 task for task in self.tasks if not any(task in other.dependencies for other in self.tasks)
513 ]
514
515 # Text is sized in points, so - to guarantee it actually fits the
516 # (content-dependent) box widths/heights computed above in data
517 # units - the figure has to be built at a fixed, known number of
518 # inches per data unit, rather than left to matplotlib's default
519 # autoscaling, which would pick whatever scale happens to fit the
520 # default figure size.
521 INCH_PER_UNIT = 0.62
522 PADDING = 0.5
523
524 min_x = min(position_of_task[task][0] - width_of_task[task] / 2 for task in self.tasks)
525 max_x = max(
526 position_of_task[task][0] + width_of_task[task] / 2 + self_loop_extent(task) for task in self.tasks
527 )
528 min_y = bottom_y
529 max_y = 0.0
530 if root_tasks:
531 max_y = PSEUDOSTATE_OFFSET + 0.09
532 if sink_tasks:
533 min_y = bottom_y - PSEUDOSTATE_OFFSET - 0.11
534 min_x, max_x, min_y, max_y = min_x - PADDING, max_x + PADDING, min_y - PADDING, max_y + PADDING
535
536 # Reserve a fixed number of inches around the axes for title/
537 # legend/x-label chrome - fixed in inches, not a fraction of the
538 # figure, so it does not eat into the data area disproportionately
539 # on a small graph - and size the figure so the axes themselves
540 # come out to exactly INCH_PER_UNIT inches per data unit in both
541 # directions.
542 LEGEND_HEIGHT = 0.26
543 LEFT_CHROME, RIGHT_CHROME, TOP_CHROME, BOTTOM_CHROME = 0.35, 0.1, 0.4 + LEGEND_HEIGHT, 0.15
544 data_width_inches = (max_x - min_x) * INCH_PER_UNIT
545 data_height_inches = (max_y - min_y) * INCH_PER_UNIT
546 figure_width = data_width_inches + LEFT_CHROME + RIGHT_CHROME
547 figure_height = data_height_inches + TOP_CHROME + BOTTOM_CHROME
548
549 figure = plt.figure(figsize=(figure_width, figure_height))
550 axes = figure.add_axes(
551 (
552 LEFT_CHROME / figure_width,
553 BOTTOM_CHROME / figure_height,
554 data_width_inches / figure_width,
555 data_height_inches / figure_height,
556 )
557 )
558 axes.set_xlim(min_x, max_x)
559 axes.set_ylim(min_y, max_y)
560
561 # One rounded-rectangle "state" per task, with a small coloured
562 # badge in the top-left corner indicating the grid entity it
563 # works on, and - if it owns action sets - an internal-activity
564 # compartment listing them as "do / <name>".
565 state_patch = {}
566 for task in self.tasks:
567 x, y = position_of_task[task]
568 w, h = width_of_task[task], height_of_task[task]
569 lines = activity_lines(task)
570
571 box = FancyBboxPatch(
572 (x - w / 2, y - h / 2),
573 w,
574 h,
575 boxstyle="round,pad=0,rounding_size=0.09",
576 linewidth=1.3,
577 edgecolor="black",
578 facecolor="white",
579 zorder=2,
580 )
581 axes.add_patch(box)
582 state_patch[task] = box
583
584 axes.add_patch(
585 Circle(
586 (x - w / 2 + 0.10, y + h / 2 - 0.10),
587 0.045,
588 facecolor=entity_colour.get(task.entity, "tab:gray"),
589 edgecolor="none",
590 zorder=3,
591 )
592 )
593
594 header_center_y = y + h / 2 - HEADER_HEIGHT / 2 if lines else y
595 axes.annotate(
596 task.name,
597 (x, header_center_y + 0.08),
598 ha="center", va="center", zorder=3, fontsize=7.5, fontweight="bold",
599 )
600 axes.annotate(
601 f"«{task.entity.name.lower()}»",
602 (x, header_center_y - 0.13),
603 ha="center", va="center", zorder=3, fontsize=6, style="italic", color="dimgray",
604 )
605
606 if lines:
607 separator_y = y + h / 2 - HEADER_HEIGHT
608 axes.plot(
609 [x - w / 2, x + w / 2], [separator_y, separator_y],
610 color="black", linewidth=0.8, zorder=3,
611 )
612 for index, line in enumerate(lines):
613 line_y = separator_y - BODY_PADDING - index * ACTIVITY_LINE_HEIGHT - 0.08
614 axes.annotate(
615 line,
616 (x - w / 2 + 0.12, line_y),
617 ha="left", va="center", zorder=3, fontsize=6.5, color="dimgray",
618 )
619
620 # Transitions between states. patchA/patchB let matplotlib clip
621 # the arrow to the actual (content-dependent) state boundary, so
622 # this works regardless of how tall a particular box grew.
623 for task in self.tasks:
624 for dependency in task.dependencies:
625 axes.add_patch(
626 FancyArrowPatch(
627 position_of_task[dependency],
628 position_of_task[task],
629 patchA=state_patch[dependency],
630 patchB=state_patch[task],
631 arrowstyle="-|>",
632 mutation_scale=13,
633 connectionstyle="arc3,rad=0.08",
634 color="black",
635 linewidth=1.1,
636 zorder=1,
637 )
638 )
639
640 if task.has_to_repeat:
641 x, y = position_of_task[task]
642 w, h = width_of_task[task], height_of_task[task]
643 right_x = x + w / 2
644 upper_y, lower_y = y + 0.18 * h, y - 0.18 * h
645 path = Path(
646 [
647 (right_x, upper_y),
648 (right_x + SELF_LOOP_WIDTH, upper_y),
649 (right_x + SELF_LOOP_WIDTH, lower_y),
650 (right_x, lower_y),
651 ],
652 [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4],
653 )
654 axes.add_patch(
655 FancyArrowPatch(
656 path=path,
657 arrowstyle="-|>",
658 mutation_scale=12,
659 color="crimson",
660 linewidth=1.1,
661 zorder=2.5,
662 )
663 )
664 axes.annotate(
665 task.has_to_repeat,
666 (right_x + SELF_LOOP_WIDTH + 0.06, y),
667 ha="left", va="center", zorder=3, fontsize=6, style="italic", color="crimson",
668 )
669
670 # UML initial pseudostate (filled circle) transitioning into every
671 # task without dependencies, and UML final pseudostate (bullseye)
672 # collecting every task nothing else depends on.
673 if root_tasks:
674 x = sum(position_of_task[task][0] for task in root_tasks) / len(root_tasks)
675 initial_pos = (x, PSEUDOSTATE_OFFSET)
676 initial_patch = Circle(initial_pos, 0.09, facecolor="black", edgecolor="black", zorder=3)
677 axes.add_patch(initial_patch)
678 for task in root_tasks:
679 axes.add_patch(
680 FancyArrowPatch(
681 initial_pos,
682 position_of_task[task],
683 patchA=initial_patch,
684 patchB=state_patch[task],
685 arrowstyle="-|>",
686 mutation_scale=13,
687 color="black",
688 linewidth=1.1,
689 zorder=1,
690 )
691 )
692
693 if sink_tasks:
694 x = sum(position_of_task[task][0] for task in sink_tasks) / len(sink_tasks)
695 final_pos = (x, bottom_y - PSEUDOSTATE_OFFSET)
696 final_outer = Circle(final_pos, 0.11, facecolor="white", edgecolor="black", linewidth=1.3, zorder=3)
697 axes.add_patch(final_outer)
698 axes.add_patch(Circle(final_pos, 0.05, facecolor="black", edgecolor="none", zorder=4))
699 for task in sink_tasks:
700 axes.add_patch(
701 FancyArrowPatch(
702 position_of_task[task],
703 final_pos,
704 patchA=state_patch[task],
705 patchB=final_outer,
706 arrowstyle="-|>",
707 mutation_scale=13,
708 color="black",
709 linewidth=1.1,
710 zorder=1,
711 )
712 )
713
714 # Title and, right below it, a legend spelling out what the
715 # coloured badge on every state stands for - both placed as
716 # figure-level (not axes-level) elements in the TOP_CHROME rows
717 # reserved for them above, so they stay put regardless of the
718 # axes' own data-driven size.
719 title_height = TOP_CHROME - LEGEND_HEIGHT
720 figure.suptitle(title, y=1.0 - 0.5 * title_height / figure_height, fontsize=10)
721
722 used_entities = [entity for entity in Task.GridEntity if any(task.entity == entity for task in self.tasks)]
723 legend_handles = [
724 Line2D(
725 [0], [0],
726 marker="o", linestyle="none", markersize=6,
727 markerfacecolor=entity_colour.get(entity, "tab:gray"), markeredgecolor="none",
728 label=f"«{entity.name.lower()}»",
729 )
730 for entity in used_entities
731 ]
732 figure.legend(
733 handles=legend_handles,
734 loc="center",
735 bbox_to_anchor=(0.5, 1.0 - (title_height + 0.5 * LEGEND_HEIGHT) / figure_height),
736 ncol=len(legend_handles),
737 frameon=False,
738 fontsize=6.5,
739 handletextpad=0.3,
740 columnspacing=1.2,
741 )
742
743 axes.set_ylabel("Dependency depth")
744 axes.set_xticks([])
745 axes.set_yticks([])
746 axes.set_aspect("equal")
747 # Non-blocking: several related graphs (e.g. a project's Setup/
748 # TimeStep/Plot task graphs) are typically visualised back to back,
749 # and should all appear together rather than forcing the user to
750 # close each one before the next is even drawn. @see
751 # wait_for_visualisations(), which the caller invokes once after
752 # such a group to actually pause for the user to look at all of
753 # them together.
754 plt.show(block=False)
755
756
758 """!
759
760 Block until the user closes every currently open matplotlib figure -
761 the counterpart to Graph.visualise() and
762 peano4.api.taskgraph.compiler.ReportCompiledStepSequence.report_compiled_step_sequence()'s
763 own visualisation, both of which render with plt.show(block=False) so
764 that a whole group of related figures (e.g. a project's Setup/
765 TimeStep/Plot task graphs, or their compiled counterparts) can all
766 appear together rather than one at a time. Call this once after such
767 a group has been produced, to actually pause and let the user look at
768 all of them side by side before execution continues.
769
770 A no-op under any verbosity other than LoggerVerbosity.VISUALISATION,
771 and also a no-op (does not even import matplotlib) if nothing is
772 currently open - e.g. because the group in question turned out to be
773 empty.
774
775 """
776 import peano4.api
777
778 if not peano4.api.Logger().is_visualisation:
779 return
780
781 import matplotlib.pyplot as plt
782
783 if plt.get_fignums():
784 plt.show()
Singleton logger for the Peano 4 Python API.
Definition Logger.py:37
Holds a sequence of Task instances.
Definition Graph.py:9
append(self, "Graph" other)
Concatenate another graph behind this one.
Definition Graph.py:22
List[Task] source_tasks(self)
Return all tasks which depend on no other task of this graph.
Definition Graph.py:101
bool _depends_on(Task task, Task other)
True if task depends on other, directly or indirectly.
Definition Graph.py:195
List[Task] sink_tasks(self)
Return all tasks which no other task of this graph depends on.
Definition Graph.py:118
merge(self, "Graph" other)
Add all tasks of another graph to this graph, next to the existing ones.
Definition Graph.py:62
log_as_text(self, str title="Task graph")
Textual counterpart to visualise(): logs a plain-text rendering of this task graph through peano4....
Definition Graph.py:302
insert_after(self, Union[Task, List[Task]] anchors, Task task)
Insert a task directly after one or several anchors.
Definition Graph.py:137
List[Task] ordered_tasks(self)
Linearise this graph's tasks into the order peano4.api.taskgraph.compiler.Sequential....
Definition Graph.py:208
List[Task] anchored_end_of_step_tasks(self)
End-of-step tasks which do not run at the very end of the step.
Definition Graph.py:267
add_task(self, Task task)
Definition Graph.py:19
visualise(self, str title="Task graph")
Render this task graph with matplotlib as a UML state diagram: one rounded-rectangle state per task,...
Definition Graph.py:363
List[Task] find_tasks(self, *tags)
Return all tasks of this graph which carry at least one of the tags, in the order in which they have ...
Definition Graph.py:86
Which kind of mesh entity a Task works on.
Definition Task.py:114
wait_for_visualisations()
Block until the user closes every currently open matplotlib figure - the counterpart to Graph....
Definition Graph.py:757