|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from dataclasses import dataclass, field |
| 4 | +from typing import TYPE_CHECKING, Sequence, TypeVar |
| 5 | + |
| 6 | +from plotnine._mpl.layout_manager._grid import DesignGrid |
| 7 | + |
| 8 | +if TYPE_CHECKING: |
| 9 | + from matplotlib.gridspec import SubplotSpec |
| 10 | + |
| 11 | + from plotnine._mpl.gridspec import p9GridSpec |
| 12 | + from plotnine._mpl.layout_manager._grid import Rect |
| 13 | + |
| 14 | +T = TypeVar("T") |
| 15 | + |
| 16 | +EMPTY_CHARS = frozenset({"#", "."}) |
| 17 | + |
| 18 | + |
| 19 | +@dataclass |
| 20 | +class DesignSpec: |
| 21 | + """ |
| 22 | + Parsed `plot_layout(design=...)` string |
| 23 | +
|
| 24 | + Attributes |
| 25 | + ---------- |
| 26 | + nrow, ncol |
| 27 | + Grid shape. |
| 28 | + grid |
| 29 | + `nrow × ncol` matrix of labels. Empty cells carry `""`. |
| 30 | + """ |
| 31 | + |
| 32 | + nrow: int |
| 33 | + ncol: int |
| 34 | + grid: list[list[str]] |
| 35 | + _rects: list[Rect] = field(repr=False) |
| 36 | + """ |
| 37 | + Inclusive `(r0, r1, c0, c1)` rectangle per item, in plot order |
| 38 | + (= sorted order of the label characters). Internal — production |
| 39 | + consumers should go through `get_subplotspecs` and `make_grid` |
| 40 | + instead of reading this directly. |
| 41 | + """ |
| 42 | + |
| 43 | + @property |
| 44 | + def n_regions(self) -> int: |
| 45 | + """ |
| 46 | + Number of regions in the design (= items the composition needs) |
| 47 | + """ |
| 48 | + return len(self._rects) |
| 49 | + |
| 50 | + def get_subplotspecs(self, gridspec: p9GridSpec) -> list[SubplotSpec]: |
| 51 | + """ |
| 52 | + One SubplotSpec per item, sliced from `gridspec` along the |
| 53 | + item's rectangle |
| 54 | + """ |
| 55 | + return [ |
| 56 | + gridspec[r0 : r1 + 1, c0 : c1 + 1] |
| 57 | + for (r0, r1, c0, c1) in self._rects |
| 58 | + ] |
| 59 | + |
| 60 | + def make_grid(self, items: Sequence[T]) -> DesignGrid[T]: |
| 61 | + """ |
| 62 | + Span-aware `DesignGrid` placing `items` at this design's rects |
| 63 | + """ |
| 64 | + return DesignGrid(self.nrow, self.ncol, items, self._rects) |
| 65 | + |
| 66 | + |
| 67 | +def parse_design(s: str) -> DesignSpec: |
| 68 | + """ |
| 69 | + Parse a design string into a DesignSpec |
| 70 | +
|
| 71 | + See `plot_layout(design=...)` for the format. |
| 72 | + """ |
| 73 | + # Pipeline: |
| 74 | + # 1. Strip & split into rows; require equal row widths. |
| 75 | + # 2. Build the cell grid, normalising empty markers (#, .) to "". |
| 76 | + # 3. Group cell positions by label character. |
| 77 | + # 4. For each label in sorted order, take the bounding rectangle |
| 78 | + # of its cells and verify every cell inside is the same label |
| 79 | + # (loud rejection of L-shapes and overlapping regions). |
| 80 | + lines = [line.strip() for line in s.strip().split("\n")] |
| 81 | + lines = [line for line in lines if line] |
| 82 | + if not lines: |
| 83 | + raise ValueError("design string is empty") |
| 84 | + |
| 85 | + ncol = len(lines[0]) |
| 86 | + for r, line in enumerate(lines): |
| 87 | + if len(line) != ncol: |
| 88 | + raise ValueError( |
| 89 | + f"design rows have unequal lengths: " |
| 90 | + f"row 0 has {ncol} columns but row {r} has {len(line)}" |
| 91 | + ) |
| 92 | + nrow = len(lines) |
| 93 | + |
| 94 | + grid: list[list[str]] = [ |
| 95 | + ["" if ch in EMPTY_CHARS else ch for ch in line] for line in lines |
| 96 | + ] |
| 97 | + |
| 98 | + cells_by_label: dict[str, list[tuple[int, int]]] = {} |
| 99 | + for r in range(nrow): |
| 100 | + for c in range(ncol): |
| 101 | + ch = grid[r][c] |
| 102 | + if not ch: |
| 103 | + continue |
| 104 | + cells_by_label.setdefault(ch, []).append((r, c)) |
| 105 | + |
| 106 | + # Assign plots in the sorted order of label characters |
| 107 | + rects: list[Rect] = [] |
| 108 | + for label in sorted(cells_by_label): |
| 109 | + cells = cells_by_label[label] |
| 110 | + rs = [r for r, _ in cells] |
| 111 | + cs = [c for _, c in cells] |
| 112 | + r0, r1 = min(rs), max(rs) |
| 113 | + c0, c1 = min(cs), max(cs) |
| 114 | + # Rectangularity: every cell inside the bounding box must |
| 115 | + # carry this label. |
| 116 | + for r in range(r0, r1 + 1): |
| 117 | + for c in range(c0, c1 + 1): |
| 118 | + if grid[r][c] != label: |
| 119 | + found = grid[r][c] or "#" |
| 120 | + raise ValueError( |
| 121 | + f"design region '{label}' is not rectangular: " |
| 122 | + f"cell ({r}, {c}) is '{found}' but should " |
| 123 | + f"be '{label}'" |
| 124 | + ) |
| 125 | + rects.append((r0, r1, c0, c1)) |
| 126 | + |
| 127 | + return DesignSpec(nrow=nrow, ncol=ncol, grid=grid, _rects=rects) |
0 commit comments