Spaces:
Runtime error
Runtime error
Deploy 713c2c3: Real-figure fixes: dotted lines with markers, legend grid fill, same-colour series by shape, annotation text removal, tinted bars, frame-touching bars
Browse files- EVAL_LOG.md +41 -0
- README.md +4 -4
- plotscribe/axes.py +11 -0
- plotscribe/export.py +29 -3
- plotscribe/extract_line.py +85 -18
- plotscribe/legend.py +125 -11
- plotscribe/pipeline.py +115 -5
- plotscribe/series.py +136 -15
- tests/test_tricky.py +76 -0
EVAL_LOG.md
CHANGED
|
@@ -252,3 +252,44 @@ Fixes:
|
|
| 252 |
| clean: silent failures / median error | 0% / 0.11% | 0% / 0.11% |
|
| 253 |
| clean: status ok | 100% | 97% (6 line charts with misread rotated category names, correctly flagged) |
|
| 254 |
| PlotQA test / held-out RNSS | 99.5 / 97.1 | 99.5 / 97.1 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
| clean: silent failures / median error | 0% / 0.11% | 0% / 0.11% |
|
| 253 |
| clean: status ok | 100% | 97% (6 line charts with misread rotated category names, correctly flagged) |
|
| 254 |
| PlotQA test / held-out RNSS | 99.5 / 97.1 | 99.5 / 97.1 |
|
| 255 |
+
|
| 256 |
+
## Stage 11 — real pgfplots / xmgrace figures (user examples)
|
| 257 |
+
|
| 258 |
+
Four user figures (`data/my_figs/tricky_examples`, not in the repo; checked by
|
| 259 |
+
`tests/test_tricky.py` when present) failed: dotted lines with markers on a log axis
|
| 260 |
+
read as ~1000 scatter points; black legend entries and a black dashed data line lost;
|
| 261 |
+
bar legend with paired-bar swatches missed; light tints of other series' colours
|
| 262 |
+
merged away; a bar against the frame cut the plot area at mid-height.
|
| 263 |
+
|
| 264 |
+
Fixes:
|
| 265 |
+
1. Legend: swatch colour from the saturated interior (black-outlined markers);
|
| 266 |
+
swatch outlines are not text; taller marker swatches; label words joined across
|
| 267 |
+
wide spaces; a missed entry (2x spacing) no longer breaks the column; a grid pass
|
| 268 |
+
adds entries the pairing missed (black/grey or dashed swatches, coloured text),
|
| 269 |
+
only with a new colour and readable text.
|
| 270 |
+
2. Colours: peaks below the threshold no longer stop the search (thin-line
|
| 271 |
+
anti-aliasing peaks came first); blends are merged before thresholding; a tint
|
| 272 |
+
that fills solid areas is its own colour, and pixels prefer the colour they match
|
| 273 |
+
at full strength.
|
| 274 |
+
3. Same-colour legend entries of different kinds (markers vs line) are split by
|
| 275 |
+
shape; marks attached to markers (error bars) and outlines of other series dropped.
|
| 276 |
+
4. Annotation text drawn in a series colour (glyph-sized, thick, collinear marks of
|
| 277 |
+
varied size or touching) is removed; black/grey marks not in a multi-entry legend
|
| 278 |
+
are ignored as annotations.
|
| 279 |
+
5. Markers on dotted lines: the larger blobs are the markers; lone same-colour marks
|
| 280 |
+
with no line into them are not markers; corners in marker gaps must leave the
|
| 281 |
+
straight line; a line running past its last visible marker ends at a hidden marker,
|
| 282 |
+
aligned with the other series' marker x.
|
| 283 |
+
6. Gridline removal only at tick-label grid positions / detected long lines (a black
|
| 284 |
+
dashed reference line is data).
|
| 285 |
+
7. Plot bottom/top from a full-width line beyond the vertical lines; grouped bars on
|
| 286 |
+
a numeric x axis give one row per group at the tick value; no-legend bar series
|
| 287 |
+
ordered left to right; empty non-legend colours dropped.
|
| 288 |
+
8. Status: legend and plot colours not matching up lowers it.
|
| 289 |
+
|
| 290 |
+
| 200 charts | before | after |
|
| 291 |
+
|---|---|---|
|
| 292 |
+
| clean: silent / median error / series count | 0% / 0.11% / 99% | 0% / 0.10% / 99.5% |
|
| 293 |
+
| perturbed: silent / series count / recall / type | 0.5% / 88.5% / 84% / 91% | 0.5% / 90.5% / 85.5% / 92% |
|
| 294 |
+
| PlotQA test / held-out RNSS | 99.5 / 97.1 | 99.6 / 97.1 |
|
| 295 |
+
| user figures t_1..t_4 | all wrong | all correct (t_2 low_confidence: 3 y labels covered) |
|
README.md
CHANGED
|
@@ -162,12 +162,12 @@ whose data lies outside the plotted y range (cut off by the frame).
|
|
| 162 |
|
| 163 |
| 200 charts, auto type | clean (default matplotlib PNG) | perturbed (styles, fonts, 50–150 dpi, JPEG q40–95, log, dashes, markers) |
|
| 164 |
|---|---|---|
|
| 165 |
-
| chart type correct | 100% |
|
| 166 |
-
| series count correct | 99% |
|
| 167 |
-
| point recall | 98.7% |
|
| 168 |
| median of per-chart median error | **0.11%** | 0.26% |
|
| 169 |
| p90 of per-chart median error | 0.24% | 9.2% |
|
| 170 |
-
| status `ok` | 97% |
|
| 171 |
| abstained (`uncalibrated`/`failed`) | 0% | 21% |
|
| 172 |
| **silent failures** (status `ok` but median error > 2% or recall < 50%) | **0%** | 0.5% |
|
| 173 |
|
|
|
|
| 162 |
|
| 163 |
| 200 charts, auto type | clean (default matplotlib PNG) | perturbed (styles, fonts, 50–150 dpi, JPEG q40–95, log, dashes, markers) |
|
| 164 |
|---|---|---|
|
| 165 |
+
| chart type correct | 100% | 92% |
|
| 166 |
+
| series count correct | 99.5% | 90.5% |
|
| 167 |
+
| point recall | 98.7% | 85.5% |
|
| 168 |
| median of per-chart median error | **0.11%** | 0.26% |
|
| 169 |
| p90 of per-chart median error | 0.24% | 9.2% |
|
| 170 |
+
| status `ok` | 97% | 49.5% |
|
| 171 |
| abstained (`uncalibrated`/`failed`) | 0% | 21% |
|
| 172 |
| **silent failures** (status `ok` but median error > 2% or recall < 50%) | **0%** | 0.5% |
|
| 173 |
|
plotscribe/axes.py
CHANGED
|
@@ -243,6 +243,17 @@ def estimate_plot_box(h_segs: list[Segment], v_segs: list[Segment], width: int,
|
|
| 243 |
ext_h = _extent(h_segs, top, bottom, 2 * tol_y)
|
| 244 |
if ext_h and h_segs:
|
| 245 |
left, right = ext_h
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
if top is None and len(h_segs) >= 2:
|
| 247 |
top, bottom = min(s.pos for s in h_segs), max(s.pos for s in h_segs)
|
| 248 |
notes.append("plot top/bottom from outermost horizontal lines")
|
|
|
|
| 243 |
ext_h = _extent(h_segs, top, bottom, 2 * tol_y)
|
| 244 |
if ext_h and h_segs:
|
| 245 |
left, right = ext_h
|
| 246 |
+
# A bar against a spine merges with it, cutting the vertical lines short: a
|
| 247 |
+
# horizontal line spanning the full width beyond them is the frame edge.
|
| 248 |
+
if left is not None and right is not None and bottom is not None:
|
| 249 |
+
span = [s.pos for s in h_segs if s.start <= left + 2 * tol_x and s.end >= right - 2 * tol_x]
|
| 250 |
+
below = [p for p in span if p > bottom + 2 * tol_y]
|
| 251 |
+
above = [p for p in span if p < top - 2 * tol_y]
|
| 252 |
+
if below:
|
| 253 |
+
bottom = max(below)
|
| 254 |
+
notes.append("plot bottom from a full-width line below the vertical lines")
|
| 255 |
+
if above:
|
| 256 |
+
top = min(above)
|
| 257 |
if top is None and len(h_segs) >= 2:
|
| 258 |
top, bottom = min(s.pos for s in h_segs), max(s.pos for s in h_segs)
|
| 259 |
notes.append("plot top/bottom from outermost horizontal lines")
|
plotscribe/export.py
CHANGED
|
@@ -52,6 +52,27 @@ def _cluster_positions(xs: np.ndarray, tol: float) -> np.ndarray:
|
|
| 52 |
return labels
|
| 53 |
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
def build_table(series: list[Series], x_cal: Calibration | None, y_cal: Calibration | None,
|
| 56 |
chart_type: str, plot_width: float) -> pd.DataFrame:
|
| 57 |
"""Convert per-series pixel points into the CSV layout described in the module doc."""
|
|
@@ -112,7 +133,8 @@ def build_table(series: list[Series], x_cal: Calibration | None, y_cal: Calibrat
|
|
| 112 |
|
| 113 |
xs = np.array([p[1] for p in pts])
|
| 114 |
tol = max(1.5, 0.004 * plot_width)
|
| 115 |
-
|
|
|
|
| 116 |
n_rows = int(lab.max()) + 1
|
| 117 |
xpx = np.array([xs[lab == k].mean() for k in range(n_rows)])
|
| 118 |
table = {n: [np.nan] * n_rows for n in names}
|
|
@@ -120,11 +142,15 @@ def build_table(series: list[Series], x_cal: Calibration | None, y_cal: Calibrat
|
|
| 120 |
table[names[si]][k] = y
|
| 121 |
xv = np.asarray(x_cal.to_value(xpx), float) if x_ok else xpx
|
| 122 |
if x_ok and x_cal.tick_px:
|
| 123 |
-
# A point exactly on a labelled tick takes the label's value (no fit residual)
|
|
|
|
| 124 |
tp, tv = np.asarray(x_cal.tick_px), np.asarray(x_cal.tick_values)
|
|
|
|
|
|
|
|
|
|
| 125 |
for k, p in enumerate(xpx):
|
| 126 |
j = int(np.argmin(np.abs(tp - p)))
|
| 127 |
-
if abs(tp[j] - p) <
|
| 128 |
xv[k] = tv[j]
|
| 129 |
df = pd.DataFrame({xname: xv, **table})
|
| 130 |
return df.sort_values(xname, kind="stable").reset_index(drop=True)
|
|
|
|
| 52 |
return labels
|
| 53 |
|
| 54 |
|
| 55 |
+
def _bar_group_tol(pts: list[tuple[int, float, float]]) -> float | None:
|
| 56 |
+
"""Single-linkage tolerance that joins the side-by-side bars of a group on a
|
| 57 |
+
numeric x axis (one bar per series), or None if the positions show no groups."""
|
| 58 |
+
xs = np.sort(np.array([p[1] for p in pts]))
|
| 59 |
+
d = np.sort(np.diff(xs))
|
| 60 |
+
if d.size < 2:
|
| 61 |
+
return None
|
| 62 |
+
upper_med = np.array([np.median(d[k + 1:]) for k in range(d.size - 1)])
|
| 63 |
+
ok = (d[1:] >= 1.5 * d[:-1] + 1) & (d[:-1] < 0.5 * upper_med)
|
| 64 |
+
if not ok.any():
|
| 65 |
+
return None
|
| 66 |
+
i = int(np.argmax(np.where(ok, np.diff(d), -1.0)))
|
| 67 |
+
tol = float(d[i] + d[i + 1]) / 2
|
| 68 |
+
lab = _cluster_positions(np.array([p[1] for p in pts]), tol)
|
| 69 |
+
for k in range(int(lab.max()) + 1):
|
| 70 |
+
members = [p[0] for p, g in zip(pts, lab) if g == k]
|
| 71 |
+
if len(members) != len(set(members)):
|
| 72 |
+
return None # two bars of one series in a group: not grouped bars
|
| 73 |
+
return tol
|
| 74 |
+
|
| 75 |
+
|
| 76 |
def build_table(series: list[Series], x_cal: Calibration | None, y_cal: Calibration | None,
|
| 77 |
chart_type: str, plot_width: float) -> pd.DataFrame:
|
| 78 |
"""Convert per-series pixel points into the CSV layout described in the module doc."""
|
|
|
|
| 133 |
|
| 134 |
xs = np.array([p[1] for p in pts])
|
| 135 |
tol = max(1.5, 0.004 * plot_width)
|
| 136 |
+
group_tol = _bar_group_tol(pts) if chart_type in ("bar", "grouped_bar") and len(series) > 1 else None
|
| 137 |
+
lab = _cluster_positions(xs, max(tol, group_tol or 0.0))
|
| 138 |
n_rows = int(lab.max()) + 1
|
| 139 |
xpx = np.array([xs[lab == k].mean() for k in range(n_rows)])
|
| 140 |
table = {n: [np.nan] * n_rows for n in names}
|
|
|
|
| 142 |
table[names[si]][k] = y
|
| 143 |
xv = np.asarray(x_cal.to_value(xpx), float) if x_ok else xpx
|
| 144 |
if x_ok and x_cal.tick_px:
|
| 145 |
+
# A point exactly on a labelled tick takes the label's value (no fit residual);
|
| 146 |
+
# a bar group (side-by-side bars, offset from its tick) takes its tick's value.
|
| 147 |
tp, tv = np.asarray(x_cal.tick_px), np.asarray(x_cal.tick_values)
|
| 148 |
+
snap = 0.5
|
| 149 |
+
if group_tol is not None and len(tp) > 1:
|
| 150 |
+
snap = 0.3 * float(np.min(np.diff(np.sort(tp))))
|
| 151 |
for k, p in enumerate(xpx):
|
| 152 |
j = int(np.argmin(np.abs(tp - p)))
|
| 153 |
+
if abs(tp[j] - p) < snap:
|
| 154 |
xv[k] = tv[j]
|
| 155 |
df = pd.DataFrame({xname: xv, **table})
|
| 156 |
return df.sort_values(xname, kind="stable").reset_index(drop=True)
|
plotscribe/extract_line.py
CHANGED
|
@@ -139,9 +139,14 @@ def find_markers(mask: np.ndarray, alpha: np.ndarray, thickness: float) -> np.nd
|
|
| 139 |
return np.zeros((0, 2))
|
| 140 |
areas = stats[1:, cv2.CC_STAT_AREA].astype(float)
|
| 141 |
med = float(np.median(areas))
|
|
|
|
|
|
|
|
|
|
| 142 |
# Corners of a thick line survive the opening as blobs barely larger than the
|
| 143 |
# kernel; real markers are clearly larger.
|
| 144 |
-
|
|
|
|
|
|
|
| 145 |
return np.zeros((0, 2))
|
| 146 |
pts = []
|
| 147 |
for i in range(1, n):
|
|
@@ -156,6 +161,20 @@ def find_markers(mask: np.ndarray, alpha: np.ndarray, thickness: float) -> np.nd
|
|
| 156 |
pts.append(((xx * wts).sum() / s + 0.5, (yy * wts).sum() / s + 0.5))
|
| 157 |
if len(pts) < 2:
|
| 158 |
return np.zeros((0, 2))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
return np.asarray(sorted(pts))
|
| 160 |
|
| 161 |
|
|
@@ -274,7 +293,20 @@ def sample_curve(cl: Centreline, grid_px: np.ndarray) -> np.ndarray:
|
|
| 274 |
return np.stack([g, np.interp(g, cl.x, ys)], 1) if len(g) else np.zeros((0, 2))
|
| 275 |
|
| 276 |
|
| 277 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
"""Add line corners where a marker is missing (hidden under another series' marker).
|
| 279 |
|
| 280 |
A gap between consecutive markers much wider than their usual spacing still has
|
|
@@ -284,27 +316,69 @@ def fill_marker_gaps(markers: np.ndarray, cl: Centreline) -> np.ndarray:
|
|
| 284 |
return markers
|
| 285 |
gaps = np.diff(markers[:, 0])
|
| 286 |
typical = float(np.median(gaps))
|
|
|
|
|
|
|
|
|
|
| 287 |
extra = []
|
| 288 |
-
for (xa,
|
| 289 |
if g < 1.6 * typical:
|
| 290 |
continue
|
| 291 |
sel = (cl.x > xa) & (cl.x < xb)
|
| 292 |
if sel.sum() < 3:
|
| 293 |
continue
|
| 294 |
idx = np.flatnonzero(sel)
|
| 295 |
-
seg = rdp(cl.x[idx],
|
| 296 |
-
inner = idx[seg[1:-1]]
|
| 297 |
for k in inner:
|
| 298 |
-
# Only corners clear of the neighbouring markers
|
| 299 |
-
|
|
|
|
|
|
|
| 300 |
extra.append((cl.x[k], cl.y[k]))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
if not extra:
|
| 302 |
return markers
|
| 303 |
return np.asarray(sorted([tuple(m) for m in markers] + extra))
|
| 304 |
|
| 305 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
def extract_line(mask: np.ndarray, alpha: np.ndarray, category_px: list[float] | None = None,
|
| 307 |
-
tick_px: list[float] | None = None, grid_px: np.ndarray | None = None
|
|
|
|
| 308 |
) -> tuple[np.ndarray, str, Centreline | None]:
|
| 309 |
"""Data points (x, y) in pixels and the method used.
|
| 310 |
|
|
@@ -320,7 +394,7 @@ def extract_line(mask: np.ndarray, alpha: np.ndarray, category_px: list[float] |
|
|
| 320 |
markers = find_markers(mask, alpha, cl.run_thickness)
|
| 321 |
span = cl.x[-1] - cl.x[0]
|
| 322 |
if len(markers) >= 2 and np.ptp(markers[:, 0]) >= 0.5 * span:
|
| 323 |
-
return fill_marker_gaps(markers, cl), "markers", cl
|
| 324 |
if category_px:
|
| 325 |
cp = np.asarray([c for c in category_px if cl.x[0] - cl.thickness <= c <= cl.x[-1] + cl.thickness])
|
| 326 |
if len(cp):
|
|
@@ -332,16 +406,9 @@ def extract_line(mask: np.ndarray, alpha: np.ndarray, category_px: list[float] |
|
|
| 332 |
# Corners are found on the de-jittered centreline, with a tolerance above the
|
| 333 |
# measured jitter, so noise does not create clusters of spurious vertices.
|
| 334 |
ys = smoothed(cl)
|
| 335 |
-
|
| 336 |
-
# Robust jitter estimate: genuine sharp corners are few, large residuals.
|
| 337 |
-
noise = float(1.4826 * np.median(np.abs(r - np.median(r))))
|
| 338 |
-
eps = float(np.clip(max(0.5 * cl.thickness, 2.5 * noise), 0.6, 4.0))
|
| 339 |
-
if cl.observed.mean() < 0.7:
|
| 340 |
-
# Dotted/dashed: the centreline between pieces is interpolated and jagged.
|
| 341 |
-
eps *= 2.5
|
| 342 |
-
idx = rdp(cl.x, ys, eps)
|
| 343 |
idx = thin_vertices(cl.x, ys, idx, max(3.0 * cl.thickness, 0.012 * (cl.x[-1] - cl.x[0])))
|
| 344 |
-
verts = refine_vertices(cl, idx)
|
| 345 |
if tick_px:
|
| 346 |
snapped = snap_to_ticks(verts, cl, tick_px)
|
| 347 |
if snapped is not None:
|
|
|
|
| 139 |
return np.zeros((0, 2))
|
| 140 |
areas = stats[1:, cv2.CC_STAT_AREA].astype(float)
|
| 141 |
med = float(np.median(areas))
|
| 142 |
+
big = areas >= 4 * med
|
| 143 |
+
if big.sum() >= 2 and (~big).sum() >= 10:
|
| 144 |
+
med = float(np.median(areas[big])) # dotted line: the dots are not the markers
|
| 145 |
# Corners of a thick line survive the opening as blobs barely larger than the
|
| 146 |
# kernel; real markers are clearly larger.
|
| 147 |
+
kernel_area = np.pi * k * k / 4
|
| 148 |
+
uniform = len(areas) >= 3 and np.std(areas) < 0.15 * np.mean(areas) # corners vary with the angle
|
| 149 |
+
if med < (1.2 if uniform else 1.6) * kernel_area:
|
| 150 |
return np.zeros((0, 2))
|
| 151 |
pts = []
|
| 152 |
for i in range(1, n):
|
|
|
|
| 161 |
pts.append(((xx * wts).sum() / s + 0.5, (yy * wts).sum() / s + 0.5))
|
| 162 |
if len(pts) < 2:
|
| 163 |
return np.zeros((0, 2))
|
| 164 |
+
# A marker of the series has its line running into it; a lone marker of the same
|
| 165 |
+
# colour (an annotation, a legend-like key in the plot) has none around it.
|
| 166 |
+
line = mask.astype(np.uint8) & (1 - cv2.dilate(blobs, kernel))
|
| 167 |
+
r = int(np.ceil(np.sqrt(med) * 0.8))
|
| 168 |
+
ring = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * r + 1, 2 * r + 1))
|
| 169 |
+
near = cv2.dilate(blobs, ring) & line
|
| 170 |
+
nlab = lab * (blobs > 0)
|
| 171 |
+
support = np.bincount(cv2.dilate(nlab.astype(np.uint16), ring)[near > 0].ravel(), minlength=n)
|
| 172 |
+
keep = []
|
| 173 |
+
for (px, py) in pts:
|
| 174 |
+
i = lab[int(py), int(px)] if blobs[int(py), int(px)] else 0
|
| 175 |
+
keep.append(i == 0 or support[i] >= 3)
|
| 176 |
+
if sum(keep) >= 2 and sum(keep) >= 0.5 * len(pts):
|
| 177 |
+
pts = [p for p, k in zip(pts, keep) if k]
|
| 178 |
return np.asarray(sorted(pts))
|
| 179 |
|
| 180 |
|
|
|
|
| 293 |
return np.stack([g, np.interp(g, cl.x, ys)], 1) if len(g) else np.zeros((0, 2))
|
| 294 |
|
| 295 |
|
| 296 |
+
def corner_eps(cl: Centreline) -> float:
|
| 297 |
+
"""RDP tolerance for the de-jittered centreline: above the measured jitter."""
|
| 298 |
+
r = cl.y - smoothed(cl)
|
| 299 |
+
# Robust jitter estimate: genuine sharp corners are few, large residuals.
|
| 300 |
+
noise = float(1.4826 * np.median(np.abs(r - np.median(r))))
|
| 301 |
+
eps = float(np.clip(max(0.5 * cl.thickness, 2.5 * noise), 0.6, 4.0))
|
| 302 |
+
if cl.observed.mean() < 0.7:
|
| 303 |
+
# Dotted/dashed: the centreline between pieces is interpolated and jagged.
|
| 304 |
+
eps *= 2.5
|
| 305 |
+
return eps
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def fill_marker_gaps(markers: np.ndarray, cl: Centreline,
|
| 309 |
+
y_bounds: tuple[float, float] | None = None) -> np.ndarray:
|
| 310 |
"""Add line corners where a marker is missing (hidden under another series' marker).
|
| 311 |
|
| 312 |
A gap between consecutive markers much wider than their usual spacing still has
|
|
|
|
| 316 |
return markers
|
| 317 |
gaps = np.diff(markers[:, 0])
|
| 318 |
typical = float(np.median(gaps))
|
| 319 |
+
# Only clear corners: a dotted trace bends slightly between its dots.
|
| 320 |
+
ys, eps = smoothed(cl), max(corner_eps(cl), 2.0 * cl.thickness)
|
| 321 |
+
min_gap = max(3.0 * cl.thickness, 0.012 * (cl.x[-1] - cl.x[0]))
|
| 322 |
extra = []
|
| 323 |
+
for (xa, ya), (xb, yb), g in zip(markers[:-1], markers[1:], gaps):
|
| 324 |
if g < 1.6 * typical:
|
| 325 |
continue
|
| 326 |
sel = (cl.x > xa) & (cl.x < xb)
|
| 327 |
if sel.sum() < 3:
|
| 328 |
continue
|
| 329 |
idx = np.flatnonzero(sel)
|
| 330 |
+
seg = rdp(cl.x[idx], ys[idx], eps)
|
| 331 |
+
inner = idx[thin_vertices(cl.x[idx], ys[idx], seg, min_gap)[1:-1]]
|
| 332 |
for k in inner:
|
| 333 |
+
# Only corners clear of the neighbouring markers and off the straight
|
| 334 |
+
# line between them.
|
| 335 |
+
off = abs(ys[k] - (ya + (yb - ya) * (cl.x[k] - xa) / g))
|
| 336 |
+
if cl.x[k] - xa > 0.4 * typical and xb - cl.x[k] > 0.4 * typical and off > eps:
|
| 337 |
extra.append((cl.x[k], cl.y[k]))
|
| 338 |
+
# The line continuing well past the first/last marker ends at a hidden marker -
|
| 339 |
+
# if it runs there without a long break (not a stray mark) and does not just
|
| 340 |
+
# leave the plot area.
|
| 341 |
+
def continuous(a: float, b: float) -> bool:
|
| 342 |
+
obs = cl.observed[(cl.x >= a) & (cl.x <= b)]
|
| 343 |
+
run = longest = 0
|
| 344 |
+
for o in obs:
|
| 345 |
+
run = 0 if o else run + 1
|
| 346 |
+
longest = max(longest, run)
|
| 347 |
+
return longest < 0.25 * typical
|
| 348 |
+
|
| 349 |
+
def inside(y: float) -> bool:
|
| 350 |
+
return y_bounds is None or y_bounds[0] + 2 * cl.thickness < y < y_bounds[1] - 2 * cl.thickness
|
| 351 |
+
|
| 352 |
+
if markers[0, 0] - cl.x[0] > 0.6 * typical and continuous(cl.x[0], markers[0, 0]) and inside(ys[0]):
|
| 353 |
+
extra.append((cl.x[0], ys[0]))
|
| 354 |
+
if cl.x[-1] - markers[-1, 0] > 0.6 * typical and continuous(markers[-1, 0], cl.x[-1]) and inside(ys[-1]):
|
| 355 |
+
extra.append((cl.x[-1], ys[-1]))
|
| 356 |
if not extra:
|
| 357 |
return markers
|
| 358 |
return np.asarray(sorted([tuple(m) for m in markers] + extra))
|
| 359 |
|
| 360 |
|
| 361 |
+
def drop_collinear(verts: np.ndarray, eps: float) -> np.ndarray:
|
| 362 |
+
"""Remove interior vertices within ``eps`` of the line through their neighbours
|
| 363 |
+
(left over where another series covers a straight stretch)."""
|
| 364 |
+
v = [tuple(p) for p in verts]
|
| 365 |
+
changed = True
|
| 366 |
+
while changed and len(v) > 2:
|
| 367 |
+
changed = False
|
| 368 |
+
dev = []
|
| 369 |
+
for k in range(1, len(v) - 1):
|
| 370 |
+
(xa, ya), (x, y), (xb, yb) = v[k - 1], v[k], v[k + 1]
|
| 371 |
+
dev.append(abs(y - (ya + (yb - ya) * (x - xa) / (xb - xa))) if xb > xa else np.inf)
|
| 372 |
+
k = int(np.argmin(dev))
|
| 373 |
+
if dev[k] < eps:
|
| 374 |
+
del v[k + 1]
|
| 375 |
+
changed = True
|
| 376 |
+
return np.asarray(v).reshape(-1, 2)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
def extract_line(mask: np.ndarray, alpha: np.ndarray, category_px: list[float] | None = None,
|
| 380 |
+
tick_px: list[float] | None = None, grid_px: np.ndarray | None = None,
|
| 381 |
+
y_bounds: tuple[float, float] | None = None
|
| 382 |
) -> tuple[np.ndarray, str, Centreline | None]:
|
| 383 |
"""Data points (x, y) in pixels and the method used.
|
| 384 |
|
|
|
|
| 394 |
markers = find_markers(mask, alpha, cl.run_thickness)
|
| 395 |
span = cl.x[-1] - cl.x[0]
|
| 396 |
if len(markers) >= 2 and np.ptp(markers[:, 0]) >= 0.5 * span:
|
| 397 |
+
return fill_marker_gaps(markers, cl, y_bounds), "markers", cl
|
| 398 |
if category_px:
|
| 399 |
cp = np.asarray([c for c in category_px if cl.x[0] - cl.thickness <= c <= cl.x[-1] + cl.thickness])
|
| 400 |
if len(cp):
|
|
|
|
| 406 |
# Corners are found on the de-jittered centreline, with a tolerance above the
|
| 407 |
# measured jitter, so noise does not create clusters of spurious vertices.
|
| 408 |
ys = smoothed(cl)
|
| 409 |
+
idx = rdp(cl.x, ys, corner_eps(cl))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
idx = thin_vertices(cl.x, ys, idx, max(3.0 * cl.thickness, 0.012 * (cl.x[-1] - cl.x[0])))
|
| 411 |
+
verts = drop_collinear(refine_vertices(cl, idx), corner_eps(cl))
|
| 412 |
if tick_px:
|
| 413 |
snapped = snap_to_ticks(verts, cl, tick_px)
|
| 414 |
if snapped is not None:
|
plotscribe/legend.py
CHANGED
|
@@ -64,11 +64,22 @@ def _components(lab: np.ndarray, ink: np.ndarray, bg: np.ndarray, max_w: float,
|
|
| 64 |
x, y, w, h, area = stats[i]
|
| 65 |
if w > max_w or h > max_h or area < 3:
|
| 66 |
continue
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
out.append(_Comp(BBox(float(x), float(y), float(x + w), float(y + h)), float(np.hypot(col[1], col[2])),
|
| 73 |
col, float(area) / float(w * h), i))
|
| 74 |
return out
|
|
@@ -102,13 +113,27 @@ def detect_legend(rgb: np.ndarray, lab: np.ndarray, ink: np.ndarray, bg: np.ndar
|
|
| 102 |
def excluded(b: BBox) -> bool:
|
| 103 |
return any(b.intersects(e) for e in exclude)
|
| 104 |
|
| 105 |
-
glyphs = [c for c in text_comps if 0.25 * ch <= c.box.h <= 1.8 * ch
|
| 106 |
-
and c.box.w <= 2.5 * ch and not (c.box.w >= 3 * c.box.h and c.box.h <= 0.3 * ch)
|
| 107 |
-
and not excluded(c.box)]
|
| 108 |
swatches = [c for c in comps if (c.chroma >= COLOURED or (c.box.w >= 2.5 * c.box.h and c.box.w >= ch))
|
| 109 |
and c.box.w >= 0.3 * ch and c.box.h >= 2 and not excluded(c.box)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
lines = group_words([g.box for g in glyphs], ch, gap_x=0.8 * ch, gap_y=-0.1 * ch)
|
| 111 |
lines = [ln for ln in lines if ln.h <= 2.0 * ch and ln.h >= 0.5 * ch]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
cands: list[tuple[_Comp, BBox]] = []
|
| 114 |
for ln in lines:
|
|
@@ -117,7 +142,8 @@ def detect_legend(rgb: np.ndarray, lab: np.ndarray, ink: np.ndarray, bg: np.ndar
|
|
| 117 |
gap = ln.x0 - s.box.x1
|
| 118 |
# Markers sit centred in a ~2 em handle, so their gap to the text is larger.
|
| 119 |
max_gap = 3.2 * ch if _swatch_kind(s, ch) == "marker" else 2.0 * ch
|
| 120 |
-
|
|
|
|
| 121 |
if best is None or gap < best[0]:
|
| 122 |
best = (gap, s)
|
| 123 |
if best is not None:
|
|
@@ -133,8 +159,11 @@ def detect_legend(rgb: np.ndarray, lab: np.ndarray, ink: np.ndarray, bg: np.ndar
|
|
| 133 |
if g is col and len(g) > 1:
|
| 134 |
g = sorted(g, key=lambda c: c[1].cy)
|
| 135 |
gaps = np.diff([c[1].cy for c in g])
|
| 136 |
-
# Entries of one legend are evenly stacked
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
| 138 |
return [ref]
|
| 139 |
return g
|
| 140 |
|
|
@@ -151,6 +180,8 @@ def detect_legend(rgb: np.ndarray, lab: np.ndarray, ink: np.ndarray, bg: np.ndar
|
|
| 151 |
text, conf = ocr.read_line(prepare_crop(rgb[rs, cs], ch))
|
| 152 |
entries.append(LegendEntry(swatch=sw.box, text_box=ln, label=text.strip(), lab=sw.lab,
|
| 153 |
kind=_swatch_kind(sw, ch), conf=conf))
|
|
|
|
|
|
|
| 154 |
repair_label_pattern(entries)
|
| 155 |
leg.entries = entries
|
| 156 |
union = entries[0].swatch.union(entries[0].text_box)
|
|
@@ -171,6 +202,89 @@ def detect_legend(rgb: np.ndarray, lab: np.ndarray, ink: np.ndarray, bg: np.ndar
|
|
| 171 |
return leg
|
| 172 |
|
| 173 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
def _grow_to_frame(ink: np.ndarray, box: BBox, ch: float) -> BBox:
|
| 175 |
"""Extend ``box`` outward (up to ~1.2 glyph heights) to include a surrounding frame."""
|
| 176 |
h, w = ink.shape
|
|
|
|
| 64 |
x, y, w, h, area = stats[i]
|
| 65 |
if w > max_w or h > max_h or area < 3:
|
| 66 |
continue
|
| 67 |
+
m = (labels[y:y + h, x:x + w] == i).astype(np.uint8)
|
| 68 |
+
# Filled shapes (patches, markers) are often outlined in black: take the colour
|
| 69 |
+
# from the interior when there is one.
|
| 70 |
+
k = 5 if min(w, h) >= 12 else 3
|
| 71 |
+
inner = cv2.erode(m, np.ones((k, k), np.uint8)) if min(w, h) >= 6 else np.zeros_like(m)
|
| 72 |
+
if inner.sum() >= 0.3 * m.sum():
|
| 73 |
+
ys, xs = np.nonzero(inner)
|
| 74 |
+
pix = lab[y + ys, x + xs]
|
| 75 |
+
ch = np.hypot(pix[:, 1], pix[:, 2])
|
| 76 |
+
# The fill is the most saturated part (outlines are darker/greyer).
|
| 77 |
+
col = np.median(pix[ch >= np.percentile(ch, 60)], axis=0)
|
| 78 |
+
else:
|
| 79 |
+
ys, xs = np.nonzero(m)
|
| 80 |
+
pix = lab[y + ys, x + xs]
|
| 81 |
+
de = np.linalg.norm(pix - bg, axis=1)
|
| 82 |
+
col = pix[de >= 0.7 * de.max()].mean(axis=0)
|
| 83 |
out.append(_Comp(BBox(float(x), float(y), float(x + w), float(y + h)), float(np.hypot(col[1], col[2])),
|
| 84 |
col, float(area) / float(w * h), i))
|
| 85 |
return out
|
|
|
|
| 113 |
def excluded(b: BBox) -> bool:
|
| 114 |
return any(b.intersects(e) for e in exclude)
|
| 115 |
|
|
|
|
|
|
|
|
|
|
| 116 |
swatches = [c for c in comps if (c.chroma >= COLOURED or (c.box.w >= 2.5 * c.box.h and c.box.w >= ch))
|
| 117 |
and c.box.w >= 0.3 * ch and c.box.h >= 2 and not excluded(c.box)]
|
| 118 |
+
coloured = [c.box for c in swatches if c.chroma >= COLOURED]
|
| 119 |
+
# Dark outlines of coloured swatches are not text.
|
| 120 |
+
glyphs = [c for c in text_comps if 0.25 * ch <= c.box.h <= 1.8 * ch
|
| 121 |
+
and c.box.w <= 2.5 * ch and not (c.box.w >= 3 * c.box.h and c.box.h <= 0.3 * ch)
|
| 122 |
+
and not excluded(c.box)
|
| 123 |
+
and not any(c.box.iou(b) > 0.3 or (c.box.intersects(b) and c.box.area < b.area) for b in coloured)]
|
| 124 |
lines = group_words([g.box for g in glyphs], ch, gap_x=0.8 * ch, gap_y=-0.1 * ch)
|
| 125 |
lines = [ln for ln in lines if ln.h <= 2.0 * ch and ln.h >= 0.5 * ch]
|
| 126 |
+
# Join the words of one label separated by a wide space ("Tx-PAM2 & Rx-SBRNN").
|
| 127 |
+
lines.sort(key=lambda b: (b.cy, b.x0))
|
| 128 |
+
joined: list[BBox] = []
|
| 129 |
+
for ln in lines:
|
| 130 |
+
prev = next((j for j in reversed(range(len(joined))) if abs(joined[j].cy - ln.cy) <= 0.3 * ln.h
|
| 131 |
+
and 0 <= ln.x0 - joined[j].x1 <= 1.5 * ch), None)
|
| 132 |
+
if prev is None:
|
| 133 |
+
joined.append(ln)
|
| 134 |
+
else:
|
| 135 |
+
joined[prev] = joined[prev].union(ln)
|
| 136 |
+
lines = joined
|
| 137 |
|
| 138 |
cands: list[tuple[_Comp, BBox]] = []
|
| 139 |
for ln in lines:
|
|
|
|
| 142 |
gap = ln.x0 - s.box.x1
|
| 143 |
# Markers sit centred in a ~2 em handle, so their gap to the text is larger.
|
| 144 |
max_gap = 3.2 * ch if _swatch_kind(s, ch) == "marker" else 2.0 * ch
|
| 145 |
+
max_h = 1.8 * ln.h if _swatch_kind(s, ch) == "marker" else 1.6 * ln.h
|
| 146 |
+
if -0.2 * ch <= gap <= max_gap and abs(s.box.cy - ln.cy) <= 0.45 * ln.h and s.box.h <= max_h:
|
| 147 |
if best is None or gap < best[0]:
|
| 148 |
best = (gap, s)
|
| 149 |
if best is not None:
|
|
|
|
| 159 |
if g is col and len(g) > 1:
|
| 160 |
g = sorted(g, key=lambda c: c[1].cy)
|
| 161 |
gaps = np.diff([c[1].cy for c in g])
|
| 162 |
+
# Entries of one legend are evenly stacked (a missed entry leaves a gap
|
| 163 |
+
# of twice the spacing).
|
| 164 |
+
step = float(gaps.min())
|
| 165 |
+
mult = gaps / max(step, 1e-6)
|
| 166 |
+
if np.any((gaps > 3.5 * ch) & ((mult > 3.2) | (np.abs(mult - np.round(mult)) > 0.15))):
|
| 167 |
return [ref]
|
| 168 |
return g
|
| 169 |
|
|
|
|
| 180 |
text, conf = ocr.read_line(prepare_crop(rgb[rs, cs], ch))
|
| 181 |
entries.append(LegendEntry(swatch=sw.box, text_box=ln, label=text.strip(), lab=sw.lab,
|
| 182 |
kind=_swatch_kind(sw, ch), conf=conf))
|
| 183 |
+
if len(entries) >= 2:
|
| 184 |
+
entries = _fill_grid(entries, rgb, lab, ink, bg, ch, ocr)
|
| 185 |
repair_label_pattern(entries)
|
| 186 |
leg.entries = entries
|
| 187 |
union = entries[0].swatch.union(entries[0].text_box)
|
|
|
|
| 202 |
return leg
|
| 203 |
|
| 204 |
|
| 205 |
+
def _fill_grid(entries: list[LegendEntry], rgb: np.ndarray, lab: np.ndarray, ink: np.ndarray,
|
| 206 |
+
bg: np.ndarray, ch: float, ocr: OCRBackend) -> list[LegendEntry]:
|
| 207 |
+
"""Add entries the pairing missed in a vertical legend (black/grey swatches, dashed
|
| 208 |
+
swatches, coloured text): entries are evenly stacked, so look at the empty slots
|
| 209 |
+
between and next to the found ones for ink in both the swatch and text columns."""
|
| 210 |
+
es = sorted(entries, key=lambda e: e.text_box.cy)
|
| 211 |
+
cys = np.array([e.text_box.cy for e in es])
|
| 212 |
+
gaps = np.diff(cys)
|
| 213 |
+
step = float(np.median(gaps[gaps < 1.5 * gaps.min()])) # text boxes shift with descenders
|
| 214 |
+
if step < 0.8 * ch or np.any(np.abs(gaps / step - np.round(gaps / step)) > 0.3):
|
| 215 |
+
return entries
|
| 216 |
+
tx0 = float(np.median([e.text_box.x0 for e in es]))
|
| 217 |
+
sx0 = min(e.swatch.x0 for e in es)
|
| 218 |
+
if any(abs(e.text_box.x0 - tx0) > 0.5 * ch for e in es) or tx0 - sx0 < 0.8 * ch:
|
| 219 |
+
return entries
|
| 220 |
+
h, w = ink.shape
|
| 221 |
+
half = 0.4 * step
|
| 222 |
+
|
| 223 |
+
def slot(cy: float) -> LegendEntry | None:
|
| 224 |
+
y0, y1 = int(max(0, cy - half)), int(min(h, cy + half))
|
| 225 |
+
if y1 - y0 < 3:
|
| 226 |
+
return None
|
| 227 |
+
xs0 = int(sx0 - 0.1 * ch)
|
| 228 |
+
sw = ink[y0:y1, xs0:int(tx0 - 0.3 * ch)].copy()
|
| 229 |
+
tx = ink[y0:y1, int(tx0 - 0.2 * ch):int(min(w, tx0 + 1.5 * ch))]
|
| 230 |
+
if sw.size == 0 or tx.size == 0:
|
| 231 |
+
return None
|
| 232 |
+
# A frame line crossing the slot is not an entry; frame sides are not swatches.
|
| 233 |
+
if np.any(ink[y0:y1, xs0:int(min(w, tx0 + 1.5 * ch))].mean(axis=1) > 0.8):
|
| 234 |
+
return None
|
| 235 |
+
sw[:, sw.mean(axis=0) > 0.9] = False
|
| 236 |
+
if sw.sum() < 0.3 * ch or tx.sum() < 0.5 * ch:
|
| 237 |
+
return None
|
| 238 |
+
rows = np.flatnonzero(tx.any(axis=1))
|
| 239 |
+
if rows.size == 0 or rows[-1] - rows[0] < 0.5 * ch:
|
| 240 |
+
return None
|
| 241 |
+
# Text extent: to the right until a gap of 2 glyph heights.
|
| 242 |
+
band = ink[y0:y1, int(tx0 - 0.2 * ch):]
|
| 243 |
+
cols = np.flatnonzero(band.any(axis=0))
|
| 244 |
+
end = cols[0]
|
| 245 |
+
for c in cols[1:]:
|
| 246 |
+
if c - end > 2 * ch:
|
| 247 |
+
break
|
| 248 |
+
end = c
|
| 249 |
+
tbox = BBox(tx0 - 0.2 * ch, float(y0 + rows[0]), tx0 - 0.2 * ch + end + 1, float(y0 + rows[-1] + 1))
|
| 250 |
+
sy, sxs = np.nonzero(sw)
|
| 251 |
+
sbox = BBox(float(xs0 + sxs.min()), float(y0 + sy.min()), float(xs0 + sxs.max() + 1), float(y0 + sy.max() + 1))
|
| 252 |
+
pix = lab[y0 + sy, xs0 + sxs]
|
| 253 |
+
de = np.linalg.norm(pix - bg, axis=1)
|
| 254 |
+
col = np.median(pix[de >= 0.7 * de.max()], axis=0)
|
| 255 |
+
r = tbox.expand(max(2.0, 0.25 * ch)).clip(w, h)
|
| 256 |
+
rs, cs = r.slices()
|
| 257 |
+
text, conf = ocr.read_line(prepare_crop(rgb[rs, cs], ch))
|
| 258 |
+
text = text.strip().rstrip("|]l1 ").strip() if text.strip().endswith("|") else text.strip()
|
| 259 |
+
if sum(c.isalnum() for c in text) < 2:
|
| 260 |
+
return None
|
| 261 |
+
kind = "line" if sbox.w >= 2.5 * sbox.h else "marker"
|
| 262 |
+
# A new entry has its own colour (the pairing missed it for being black/grey
|
| 263 |
+
# or dashed) and a readable label; else it is plot content next to the legend.
|
| 264 |
+
if any(np.linalg.norm(col - e.lab) < 15 for e in es) or conf < 0.5:
|
| 265 |
+
return None
|
| 266 |
+
if sum(c.isalpha() for c in text) < 0.6 * len(text.replace(" ", "")):
|
| 267 |
+
return None
|
| 268 |
+
return LegendEntry(swatch=sbox, text_box=tbox, label=text.strip(), lab=col, kind=kind, conf=conf)
|
| 269 |
+
|
| 270 |
+
out = list(es)
|
| 271 |
+
for a, b in zip(es, es[1:]): # missed rows between found entries
|
| 272 |
+
k = int(round((b.text_box.cy - a.text_box.cy) / step))
|
| 273 |
+
for j in range(1, k):
|
| 274 |
+
e = slot(a.text_box.cy + j * step)
|
| 275 |
+
if e is not None:
|
| 276 |
+
out.append(e)
|
| 277 |
+
for direction, start in ((1, cys[-1]), (-1, cys[0])): # rows just below / above
|
| 278 |
+
cy = start
|
| 279 |
+
while True:
|
| 280 |
+
cy += direction * step
|
| 281 |
+
e = slot(cy)
|
| 282 |
+
if e is None:
|
| 283 |
+
break
|
| 284 |
+
out.append(e)
|
| 285 |
+
return sorted(out, key=lambda e: e.text_box.cy)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
def _grow_to_frame(ink: np.ndarray, box: BBox, ch: float) -> BBox:
|
| 289 |
"""Extend ``box`` outward (up to ~1.2 glyph heights) to include a surrounding frame."""
|
| 290 |
h, w = ink.shape
|
plotscribe/pipeline.py
CHANGED
|
@@ -419,6 +419,7 @@ def run(path: str | Path, ocr_backend: str = "tesseract", chart_type: str | None
|
|
| 419 |
res.stage_conf[f"calib_{name}"] = cal.confidence
|
| 420 |
|
| 421 |
char_h = float(np.median([c for c in (xch, ych) if c > 0])) if (xch > 0 or ych > 0) else 0.0
|
|
|
|
| 422 |
leg = legend_mod.detect_legend(pre.rgb, pre.lab, ink, ax.panel_bg, char_h, ocr,
|
| 423 |
exclude=[lb.bbox for lb in res.x_labels + res.y_labels])
|
| 424 |
res.extra["legend_box"] = leg.box
|
|
@@ -449,6 +450,16 @@ def run(path: str | Path, ocr_backend: str = "tesseract", chart_type: str | None
|
|
| 449 |
return res
|
| 450 |
|
| 451 |
extract(res, series)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 452 |
status_from_calibration(res)
|
| 453 |
check_data_outside_box(res, series)
|
| 454 |
check_clipping(res, series)
|
|
@@ -456,13 +467,35 @@ def run(path: str | Path, ocr_backend: str = "tesseract", chart_type: str | None
|
|
| 456 |
return res
|
| 457 |
|
| 458 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 459 |
def separate_series(res: PipelineResult, ink: np.ndarray, leg: legend_mod.Legend) -> list[Series]:
|
| 460 |
"""Colour clusters in the plot area, reconciled with legend swatch colours."""
|
| 461 |
ax = res.axes
|
| 462 |
assert ax is not None
|
| 463 |
region = series_mod.plot_interior(ax, ink.shape)
|
| 464 |
rgb, grid = series_mod.remove_gridlines(res.pre.rgb, region, ax.line_thickness, res.pre.noise_sigma,
|
| 465 |
-
ax.panel_bg)
|
|
|
|
| 466 |
lab = to_lab(rgb)
|
| 467 |
ink = axes_mod.ink_mask(lab, ax.figure_bg, region, ax.panel_bg, axes_mod.ink_threshold(res.pre.noise_sigma))
|
| 468 |
res.extra["clean_rgb"] = rgb
|
|
@@ -471,7 +504,9 @@ def separate_series(res: PipelineResult, ink: np.ndarray, leg: legend_mod.Legend
|
|
| 471 |
exclude = [leg.box] if leg.box is not None else []
|
| 472 |
cand, _ = series_mod.candidate_mask(lab, ink, ax, exclude)
|
| 473 |
bg = series_mod.bg_for(ax)
|
| 474 |
-
|
|
|
|
|
|
|
| 475 |
colours: list[np.ndarray] = []
|
| 476 |
names: list[str] = []
|
| 477 |
from_legend: list[bool] = []
|
|
@@ -493,11 +528,17 @@ def separate_series(res: PipelineResult, ink: np.ndarray, leg: legend_mod.Legend
|
|
| 493 |
continue
|
| 494 |
if leg.entries and c.weight < 0.1:
|
| 495 |
continue # stray colour (anti-aliasing, text) when the legend says otherwise
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 496 |
colours.append(c.lab)
|
| 497 |
names.append(f"series_{len(names) + 1}")
|
| 498 |
from_legend.append(False)
|
| 499 |
if leg.entries:
|
| 500 |
res.warn("series", f"colour cluster {series_mod.describe_color(c.lab)} not in legend")
|
|
|
|
| 501 |
if not leg.entries:
|
| 502 |
res.warn("legend", "no legend found; series named series_1..n")
|
| 503 |
# Unique names.
|
|
@@ -509,6 +550,38 @@ def separate_series(res: PipelineResult, ink: np.ndarray, leg: legend_mod.Legend
|
|
| 509 |
else:
|
| 510 |
seen[n] = 1
|
| 511 |
masks, alpha, labels = series_mod.series_masks(rgb, cand, ax, colours, res.pre.noise_sigma)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 512 |
outline = series_mod.outline_clusters(masks)
|
| 513 |
if outline:
|
| 514 |
keep = [i for i in range(len(masks)) if i not in outline or from_legend[i]]
|
|
@@ -549,8 +622,10 @@ def extract(res: PipelineResult, series: list[Series]) -> None:
|
|
| 549 |
num_ticks = res.axes.x_ticks if (res.x_cal is not None and res.x_cal.kind != "categorical") else None
|
| 550 |
n_grid = res.extra.get("resample")
|
| 551 |
grid = sample_grid(res, [s.mask for s in live], n_grid) if n_grid else None
|
|
|
|
|
|
|
| 552 |
for s in live:
|
| 553 |
-
pts, method, cl = extract_line(s.mask, alpha, cat_px, num_ticks, grid)
|
| 554 |
if cl is not None:
|
| 555 |
cls[s.name] = cl
|
| 556 |
s.points_px = pts
|
|
@@ -558,6 +633,7 @@ def extract(res: PipelineResult, series: list[Series]) -> None:
|
|
| 558 |
res.extra.setdefault("diagnostics_extra", {})["point_method"] = methods
|
| 559 |
if cat_px is None:
|
| 560 |
fill_occluded_ends(res, live, cls)
|
|
|
|
| 561 |
elif ctype in ("bar", "grouped_bar", "stacked_bar"):
|
| 562 |
extract_bars(res, series, alpha, labels)
|
| 563 |
elif ctype == "scatter":
|
|
@@ -639,6 +715,38 @@ def sample_grid(res: PipelineResult, masks: list[np.ndarray], samples: int = SAM
|
|
| 639 |
return np.sort(np.asarray(x.to_px(vals), float))
|
| 640 |
|
| 641 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 642 |
def fill_occluded_ends(res: PipelineResult, series: list[Series], cls: dict) -> None:
|
| 643 |
"""Extend lines whose visible start/end lies on another line that continues further.
|
| 644 |
|
|
@@ -879,9 +987,11 @@ def status_from_calibration(res: PipelineResult) -> None:
|
|
| 879 |
if status == "ok" and x is not None and x.kind != "categorical" and x.n_inliers >= 2 and x.confidence < 0.3:
|
| 880 |
status = "low_confidence"
|
| 881 |
n_leg = len(res.extra.get("legend_info", {}).get("entries", []))
|
| 882 |
-
|
|
|
|
|
|
|
| 883 |
status = "low_confidence"
|
| 884 |
-
res.warn("series", "
|
| 885 |
if x is not None and x.kind == "categorical" and x.categories:
|
| 886 |
junk = sum(misread_name(c) for c in x.categories)
|
| 887 |
if junk >= max(2.0, len(x.categories) / 3):
|
|
|
|
| 419 |
res.stage_conf[f"calib_{name}"] = cal.confidence
|
| 420 |
|
| 421 |
char_h = float(np.median([c for c in (xch, ych) if c > 0])) if (xch > 0 or ych > 0) else 0.0
|
| 422 |
+
res.extra["char_h"] = char_h
|
| 423 |
leg = legend_mod.detect_legend(pre.rgb, pre.lab, ink, ax.panel_bg, char_h, ocr,
|
| 424 |
exclude=[lb.bbox for lb in res.x_labels + res.y_labels])
|
| 425 |
res.extra["legend_box"] = leg.box
|
|
|
|
| 450 |
return res
|
| 451 |
|
| 452 |
extract(res, series)
|
| 453 |
+
dropped = [s for s in series if not s.from_legend and len(s.points_px) == 0 and not getattr(s, "segments_px", None)]
|
| 454 |
+
if dropped and len(dropped) < len(series):
|
| 455 |
+
series[:] = [s for s in series if s not in dropped]
|
| 456 |
+
res.extra["series"] = series
|
| 457 |
+
res.warn("series", f"{len(dropped)} colour(s) without data marks ignored")
|
| 458 |
+
if "bar" in res.chart_type and not any(s.from_legend for s in series):
|
| 459 |
+
# No legend: number the series in drawing order within a group (left to right).
|
| 460 |
+
series.sort(key=lambda s: float(np.min(s.points_px[:, 0])) if len(s.points_px) else np.inf)
|
| 461 |
+
for k, s in enumerate(series):
|
| 462 |
+
s.name = f"series_{k + 1}"
|
| 463 |
status_from_calibration(res)
|
| 464 |
check_data_outside_box(res, series)
|
| 465 |
check_clipping(res, series)
|
|
|
|
| 467 |
return res
|
| 468 |
|
| 469 |
|
| 470 |
+
def gridline_positions(cal: Calibration | None, lines: list) -> list[float] | None:
|
| 471 |
+
"""Pixel positions where gridlines can be: every step of the labelled tick grid
|
| 472 |
+
across the axis, plus detected long lines. None (no restriction) without a
|
| 473 |
+
numeric calibration."""
|
| 474 |
+
if cal is None or cal.kind not in ("linear", "log") or cal.n_inliers < 2:
|
| 475 |
+
return None
|
| 476 |
+
t = np.sort(np.asarray(cal.tick_values, float))
|
| 477 |
+
if cal.kind == "log":
|
| 478 |
+
t = np.log10(t[t > 0])
|
| 479 |
+
if t.size < 2:
|
| 480 |
+
return None
|
| 481 |
+
step = float(np.min(np.diff(t)))
|
| 482 |
+
if step <= 0:
|
| 483 |
+
return None
|
| 484 |
+
lo, hi = t[0] - 50 * step, t[-1] + 50 * step
|
| 485 |
+
vals = np.arange(np.ceil(lo / step) * step, hi + 0.5 * step, step)
|
| 486 |
+
if cal.kind == "log":
|
| 487 |
+
vals = 10.0 ** vals
|
| 488 |
+
return [float(p) for p in np.atleast_1d(cal.to_px(vals))] + [s.pos for s in lines]
|
| 489 |
+
|
| 490 |
+
|
| 491 |
def separate_series(res: PipelineResult, ink: np.ndarray, leg: legend_mod.Legend) -> list[Series]:
|
| 492 |
"""Colour clusters in the plot area, reconciled with legend swatch colours."""
|
| 493 |
ax = res.axes
|
| 494 |
assert ax is not None
|
| 495 |
region = series_mod.plot_interior(ax, ink.shape)
|
| 496 |
rgb, grid = series_mod.remove_gridlines(res.pre.rgb, region, ax.line_thickness, res.pre.noise_sigma,
|
| 497 |
+
ax.panel_bg, gridline_positions(res.y_cal, ax.h_lines),
|
| 498 |
+
gridline_positions(res.x_cal, ax.v_lines))
|
| 499 |
lab = to_lab(rgb)
|
| 500 |
ink = axes_mod.ink_mask(lab, ax.figure_bg, region, ax.panel_bg, axes_mod.ink_threshold(res.pre.noise_sigma))
|
| 501 |
res.extra["clean_rgb"] = rgb
|
|
|
|
| 504 |
exclude = [leg.box] if leg.box is not None else []
|
| 505 |
cand, _ = series_mod.candidate_mask(lab, ink, ax, exclude)
|
| 506 |
bg = series_mod.bg_for(ax)
|
| 507 |
+
h, w = cand.shape
|
| 508 |
+
clusters = series_mod.find_colors(lab[cand], bg, is_solid=series_mod.solid_colour_test(
|
| 509 |
+
lab, cand, max(50, int(0.0005 * h * w))))
|
| 510 |
colours: list[np.ndarray] = []
|
| 511 |
names: list[str] = []
|
| 512 |
from_legend: list[bool] = []
|
|
|
|
| 528 |
continue
|
| 529 |
if leg.entries and c.weight < 0.1:
|
| 530 |
continue # stray colour (anti-aliasing, text) when the legend says otherwise
|
| 531 |
+
if len(leg.entries) >= 2 and series_mod.chroma(c.lab) < 15:
|
| 532 |
+
# Black/grey marks outside a multi-entry legend: annotations, frames, arrows.
|
| 533 |
+
res.warn("series", f"black/grey marks {series_mod.describe_color(c.lab)} not in the legend ignored "
|
| 534 |
+
"(annotations?)")
|
| 535 |
+
continue
|
| 536 |
colours.append(c.lab)
|
| 537 |
names.append(f"series_{len(names) + 1}")
|
| 538 |
from_legend.append(False)
|
| 539 |
if leg.entries:
|
| 540 |
res.warn("series", f"colour cluster {series_mod.describe_color(c.lab)} not in legend")
|
| 541 |
+
res.extra["not_in_legend"] = res.extra.get("not_in_legend", 0) + 1
|
| 542 |
if not leg.entries:
|
| 543 |
res.warn("legend", "no legend found; series named series_1..n")
|
| 544 |
# Unique names.
|
|
|
|
| 550 |
else:
|
| 551 |
seen[n] = 1
|
| 552 |
masks, alpha, labels = series_mod.series_masks(rgb, cand, ax, colours, res.pre.noise_sigma)
|
| 553 |
+
for i, m in enumerate(masks):
|
| 554 |
+
masks[i], n_text = series_mod.remove_text(m, res.extra.get("char_h", 0.0))
|
| 555 |
+
if n_text:
|
| 556 |
+
labels[m & ~masks[i]] = -1
|
| 557 |
+
res.warn("series", f"{n_text} text annotation(s) in colour {series_mod.describe_color(colours[i])} "
|
| 558 |
+
"ignored")
|
| 559 |
+
# Same-colour legend entries told apart by shape: markers vs a line.
|
| 560 |
+
ents = leg.entries
|
| 561 |
+
for i in range(len(ents)):
|
| 562 |
+
for j in range(i + 1, len(ents)):
|
| 563 |
+
if np.linalg.norm(colours[i] - colours[j]) >= 10 or {ents[i].kind, ents[j].kind} != {"marker", "line"}:
|
| 564 |
+
continue
|
| 565 |
+
mi, li = (i, j) if ents[i].kind == "marker" else (j, i)
|
| 566 |
+
size = min(ents[mi].swatch.w, ents[mi].swatch.h)
|
| 567 |
+
mk, ln = series_mod.split_marker_line(masks[i] | masks[j], size)
|
| 568 |
+
# Outlines of other series' markers (black rings) are not the line.
|
| 569 |
+
others = np.zeros_like(ln)
|
| 570 |
+
for k, m in enumerate(masks):
|
| 571 |
+
if k not in (i, j):
|
| 572 |
+
others |= m
|
| 573 |
+
near = cv2.dilate(others.astype(np.uint8), np.ones((9, 9), np.uint8)) > 0
|
| 574 |
+
n_c, comp = cv2.connectedComponents(ln.astype(np.uint8), connectivity=8)
|
| 575 |
+
if n_c > 1:
|
| 576 |
+
frac = np.bincount(comp[ln], weights=near[ln], minlength=n_c) / np.maximum(
|
| 577 |
+
np.bincount(comp[ln], minlength=n_c), 1)
|
| 578 |
+
ln = ln & ~(frac > 0.5)[comp]
|
| 579 |
+
if mk.any() and ln.any():
|
| 580 |
+
masks[mi], masks[li] = mk, ln
|
| 581 |
+
labels[mk] = mi
|
| 582 |
+
labels[ln] = li
|
| 583 |
+
res.warn("series", f"'{ents[mi].label}' and '{ents[li].label}' share a colour; told apart by "
|
| 584 |
+
"shape (markers vs line)")
|
| 585 |
outline = series_mod.outline_clusters(masks)
|
| 586 |
if outline:
|
| 587 |
keep = [i for i in range(len(masks)) if i not in outline or from_legend[i]]
|
|
|
|
| 622 |
num_ticks = res.axes.x_ticks if (res.x_cal is not None and res.x_cal.kind != "categorical") else None
|
| 623 |
n_grid = res.extra.get("resample")
|
| 624 |
grid = sample_grid(res, [s.mask for s in live], n_grid) if n_grid else None
|
| 625 |
+
assert res.axes is not None
|
| 626 |
+
interior = series_mod.plot_interior(res.axes, alpha.shape)
|
| 627 |
for s in live:
|
| 628 |
+
pts, method, cl = extract_line(s.mask, alpha, cat_px, num_ticks, grid, (interior.y0, interior.y1))
|
| 629 |
if cl is not None:
|
| 630 |
cls[s.name] = cl
|
| 631 |
s.points_px = pts
|
|
|
|
| 633 |
res.extra.setdefault("diagnostics_extra", {})["point_method"] = methods
|
| 634 |
if cat_px is None:
|
| 635 |
fill_occluded_ends(res, live, cls)
|
| 636 |
+
align_hidden_ends(live, methods, res.extra.get("char_h", 0.0))
|
| 637 |
elif ctype in ("bar", "grouped_bar", "stacked_bar"):
|
| 638 |
extract_bars(res, series, alpha, labels)
|
| 639 |
elif ctype == "scatter":
|
|
|
|
| 715 |
return np.sort(np.asarray(x.to_px(vals), float))
|
| 716 |
|
| 717 |
|
| 718 |
+
def align_hidden_ends(series: list[Series], methods: dict, char_h: float) -> None:
|
| 719 |
+
"""Put a marker line's end point that is hidden under another series' marker at
|
| 720 |
+
that marker's x (several series often share their first/last x)."""
|
| 721 |
+
if char_h <= 0:
|
| 722 |
+
return
|
| 723 |
+
for s in series:
|
| 724 |
+
if methods.get(s.name) != "markers" or len(s.points_px) < 2:
|
| 725 |
+
continue
|
| 726 |
+
others = [o.points_px for o in series if o is not s and methods.get(o.name) == "markers"
|
| 727 |
+
and len(o.points_px)]
|
| 728 |
+
if not others:
|
| 729 |
+
continue
|
| 730 |
+
other = np.concatenate(others)
|
| 731 |
+
pts = s.points_px[np.argsort(s.points_px[:, 0])]
|
| 732 |
+
for end in (0, -1):
|
| 733 |
+
x, y = pts[end]
|
| 734 |
+
d = np.abs(other[:, 0] - x)
|
| 735 |
+
ok = (d >= 0.05) & (d <= 1.2 * char_h) & (np.abs(other[:, 1] - y) <= 1.5 * char_h)
|
| 736 |
+
if not ok.any():
|
| 737 |
+
continue
|
| 738 |
+
j = int(np.argmin(np.where(ok, d, np.inf)))
|
| 739 |
+
# The other series' marker x is outside this end: move the end there and
|
| 740 |
+
# drop own points now beyond it (fragments of the hidden stretch).
|
| 741 |
+
nx = float(other[j, 0])
|
| 742 |
+
inward = pts[:, 0] >= nx if end == 0 else pts[:, 0] <= nx
|
| 743 |
+
if (nx - x) * (1 if end == 0 else -1) < 0:
|
| 744 |
+
continue
|
| 745 |
+
keep = inward & (np.abs(pts[:, 0] - nx) > 0.75 * char_h)
|
| 746 |
+
pts = np.vstack([[nx, y], pts[keep]]) if end == 0 else np.vstack([pts[keep], [nx, y]])
|
| 747 |
+
s.points_px = pts
|
| 748 |
+
|
| 749 |
+
|
| 750 |
def fill_occluded_ends(res: PipelineResult, series: list[Series], cls: dict) -> None:
|
| 751 |
"""Extend lines whose visible start/end lies on another line that continues further.
|
| 752 |
|
|
|
|
| 987 |
if status == "ok" and x is not None and x.kind != "categorical" and x.n_inliers >= 2 and x.confidence < 0.3:
|
| 988 |
status = "low_confidence"
|
| 989 |
n_leg = len(res.extra.get("legend_info", {}).get("entries", []))
|
| 990 |
+
unmatched = res.extra.get("legend_unmatched", 0)
|
| 991 |
+
if status == "ok" and n_leg and (unmatched >= max(2, n_leg / 2)
|
| 992 |
+
or (unmatched and res.extra.get("not_in_legend", 0))):
|
| 993 |
status = "low_confidence"
|
| 994 |
+
res.warn("series", "legend colours and plot colours do not match up; series may be mixed up")
|
| 995 |
if x is not None and x.kind == "categorical" and x.categories:
|
| 996 |
junk = sum(misread_name(c) for c in x.categories)
|
| 997 |
if junk >= max(2.0, len(x.categories) / 3):
|
plotscribe/series.py
CHANGED
|
@@ -12,6 +12,8 @@ from __future__ import annotations
|
|
| 12 |
|
| 13 |
from dataclasses import dataclass
|
| 14 |
|
|
|
|
|
|
|
| 15 |
import cv2
|
| 16 |
import numpy as np
|
| 17 |
|
|
@@ -42,7 +44,7 @@ class GridRemoval:
|
|
| 42 |
|
| 43 |
|
| 44 |
def _remove_thin_lines(rgb: np.ndarray, region: BBox, k: int, axis: int, noise: float,
|
| 45 |
-
bg: np.ndarray) -> list[int]:
|
| 46 |
"""Inpaint achromatic thin lines along ``axis`` (0: horizontal lines, 1: vertical) in place.
|
| 47 |
|
| 48 |
A pixel is on a thin line if the pixels ``k`` away on both sides agree with each
|
|
@@ -66,7 +68,10 @@ def _remove_thin_lines(rgb: np.ndarray, region: BBox, k: int, axis: int, noise:
|
|
| 66 |
score = thin.sum(axis=1)
|
| 67 |
lines = np.flatnonzero(score > 0.25 * width)
|
| 68 |
removed: list[int] = []
|
|
|
|
| 69 |
for r in lines:
|
|
|
|
|
|
|
| 70 |
on_bg = thin[r] & (np.linalg.norm(nb[r] - bg, axis=1) < tol_same)
|
| 71 |
pix = mid[r][on_bg] if on_bg.sum() >= 5 else mid[r][thin[r]]
|
| 72 |
if np.ptp(np.median(pix, axis=0)) > 30: # coloured: a flat data line, not a gridline
|
|
@@ -76,7 +81,6 @@ def _remove_thin_lines(rgb: np.ndarray, region: BBox, k: int, axis: int, noise:
|
|
| 76 |
removed.append(int(r + k))
|
| 77 |
out = sub.transpose(1, 0, 2) if axis == 1 else sub
|
| 78 |
rgb[rs, cs] = np.clip(out, 0, 255).astype(np.uint8)
|
| 79 |
-
offset = cs.start if axis == 1 else rs.start
|
| 80 |
return [r + offset for r in removed]
|
| 81 |
|
| 82 |
|
|
@@ -105,13 +109,18 @@ def is_grey_overlay(p: np.ndarray, n: np.ndarray, tol: float) -> np.ndarray:
|
|
| 105 |
|
| 106 |
|
| 107 |
def remove_gridlines(rgb: np.ndarray, region: BBox, line_thickness: float, noise: float,
|
| 108 |
-
bg_lab: np.ndarray
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
out = rgb.copy()
|
| 111 |
k = int(np.ceil(line_thickness / 2)) + 3
|
| 112 |
bg = lab_to_rgb(bg_lab)
|
| 113 |
-
rows = _remove_thin_lines(out, region, k, 0, noise, bg)
|
| 114 |
-
cols = _remove_thin_lines(out, region, k, 1, noise, bg)
|
| 115 |
return out, GridRemoval(rows=rows, cols=cols)
|
| 116 |
|
| 117 |
|
|
@@ -133,12 +142,15 @@ def candidate_mask(lab: np.ndarray, ink: np.ndarray, ax: AxesResult, exclude: li
|
|
| 133 |
|
| 134 |
|
| 135 |
def find_colors(pixels: np.ndarray, bg: np.ndarray, min_frac: float = 0.02, max_k: int = 10,
|
| 136 |
-
merge_de: float = 12.0
|
|
|
|
| 137 |
"""Mode-seeking on a quantised Lab histogram: each peak is a series colour.
|
| 138 |
|
| 139 |
Anti-aliased blends spread thinly along bg->colour segments, so they do not form
|
| 140 |
peaks; pure series colours do. ``k`` is chosen automatically by stopping when
|
| 141 |
-
the next peak holds less than ``min_frac`` of the pixels.
|
|
|
|
|
|
|
| 142 |
"""
|
| 143 |
if len(pixels) == 0:
|
| 144 |
return []
|
|
@@ -151,8 +163,12 @@ def find_colors(pixels: np.ndarray, bg: np.ndarray, min_frac: float = 0.02, max_
|
|
| 151 |
centers = uniq.astype(np.float32) * bin_size
|
| 152 |
alive = np.ones(len(uniq), bool)
|
| 153 |
total = float(len(pix))
|
|
|
|
|
|
|
| 154 |
out: list[ColorCluster] = []
|
| 155 |
-
|
|
|
|
|
|
|
| 156 |
i = int(np.argmax(np.where(alive, counts, -1)))
|
| 157 |
c = centers[i]
|
| 158 |
for _ in range(3): # mean shift on bins
|
|
@@ -163,8 +179,12 @@ def find_colors(pixels: np.ndarray, bg: np.ndarray, min_frac: float = 0.02, max_
|
|
| 163 |
member = alive & (d < merge_de)
|
| 164 |
weight = counts[member].sum() / total
|
| 165 |
alive &= d >= 1.5 * merge_de
|
| 166 |
-
if weight < min_frac:
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
if np.linalg.norm(c - bg) < 15.0:
|
| 169 |
continue # residual background / faint blends
|
| 170 |
out.append(ColorCluster(lab=c, weight=float(weight)))
|
|
@@ -173,12 +193,24 @@ def find_colors(pixels: np.ndarray, bg: np.ndarray, min_frac: float = 0.02, max_
|
|
| 173 |
merged: list[ColorCluster] = []
|
| 174 |
for cl in sorted(out, key=lambda c: -float(np.linalg.norm(c.lab - bg))):
|
| 175 |
for m in merged:
|
| 176 |
-
if np.linalg.norm(m.lab - cl.lab) < merge_de or
|
|
|
|
| 177 |
m.weight += cl.weight
|
| 178 |
break
|
| 179 |
else:
|
| 180 |
merged.append(cl)
|
| 181 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
|
| 184 |
def lab_to_rgb(lab: np.ndarray) -> np.ndarray:
|
|
@@ -227,8 +259,11 @@ def soft_assign(rgb: np.ndarray, cand: np.ndarray, bg: np.ndarray, colors: list[
|
|
| 227 |
continue
|
| 228 |
a = np.clip(px @ v / vv, 0.0, 1.2)
|
| 229 |
d = np.linalg.norm(px - a[:, None] * v[None, :], axis=1)
|
| 230 |
-
|
| 231 |
-
|
|
|
|
|
|
|
|
|
|
| 232 |
best_i = np.where(better, i, best_i)
|
| 233 |
best_a = np.where(better, a, best_a)
|
| 234 |
labels[ys, xs] = best_i
|
|
@@ -252,6 +287,92 @@ def remove_specks(mask: np.ndarray, min_area: int) -> np.ndarray:
|
|
| 252 |
return keep[lab]
|
| 253 |
|
| 254 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
def bg_for(ax: AxesResult) -> np.ndarray:
|
| 256 |
return np.asarray(ax.panel_bg, np.float32)
|
| 257 |
|
|
|
|
| 12 |
|
| 13 |
from dataclasses import dataclass
|
| 14 |
|
| 15 |
+
from typing import Callable
|
| 16 |
+
|
| 17 |
import cv2
|
| 18 |
import numpy as np
|
| 19 |
|
|
|
|
| 44 |
|
| 45 |
|
| 46 |
def _remove_thin_lines(rgb: np.ndarray, region: BBox, k: int, axis: int, noise: float,
|
| 47 |
+
bg: np.ndarray, allowed: list[float] | None = None) -> list[int]:
|
| 48 |
"""Inpaint achromatic thin lines along ``axis`` (0: horizontal lines, 1: vertical) in place.
|
| 49 |
|
| 50 |
A pixel is on a thin line if the pixels ``k`` away on both sides agree with each
|
|
|
|
| 68 |
score = thin.sum(axis=1)
|
| 69 |
lines = np.flatnonzero(score > 0.25 * width)
|
| 70 |
removed: list[int] = []
|
| 71 |
+
offset = cs.start if axis == 1 else rs.start
|
| 72 |
for r in lines:
|
| 73 |
+
if allowed and min(abs(r + k + offset - a) for a in allowed) > max(3, k):
|
| 74 |
+
continue # gridlines sit at ticks / detected lines; elsewhere a flat data line
|
| 75 |
on_bg = thin[r] & (np.linalg.norm(nb[r] - bg, axis=1) < tol_same)
|
| 76 |
pix = mid[r][on_bg] if on_bg.sum() >= 5 else mid[r][thin[r]]
|
| 77 |
if np.ptp(np.median(pix, axis=0)) > 30: # coloured: a flat data line, not a gridline
|
|
|
|
| 81 |
removed.append(int(r + k))
|
| 82 |
out = sub.transpose(1, 0, 2) if axis == 1 else sub
|
| 83 |
rgb[rs, cs] = np.clip(out, 0, 255).astype(np.uint8)
|
|
|
|
| 84 |
return [r + offset for r in removed]
|
| 85 |
|
| 86 |
|
|
|
|
| 109 |
|
| 110 |
|
| 111 |
def remove_gridlines(rgb: np.ndarray, region: BBox, line_thickness: float, noise: float,
|
| 112 |
+
bg_lab: np.ndarray, rows_ok: list[float] | None = None,
|
| 113 |
+
cols_ok: list[float] | None = None) -> tuple[np.ndarray, GridRemoval]:
|
| 114 |
+
"""Copy of ``rgb`` with achromatic gridlines inpainted inside ``region``.
|
| 115 |
+
|
| 116 |
+
``rows_ok``/``cols_ok``: where gridlines can be (ticks, long lines); a flat
|
| 117 |
+
achromatic line elsewhere is data (e.g. a black dashed reference line).
|
| 118 |
+
"""
|
| 119 |
out = rgb.copy()
|
| 120 |
k = int(np.ceil(line_thickness / 2)) + 3
|
| 121 |
bg = lab_to_rgb(bg_lab)
|
| 122 |
+
rows = _remove_thin_lines(out, region, k, 0, noise, bg, rows_ok)
|
| 123 |
+
cols = _remove_thin_lines(out, region, k, 1, noise, bg, cols_ok)
|
| 124 |
return out, GridRemoval(rows=rows, cols=cols)
|
| 125 |
|
| 126 |
|
|
|
|
| 142 |
|
| 143 |
|
| 144 |
def find_colors(pixels: np.ndarray, bg: np.ndarray, min_frac: float = 0.02, max_k: int = 10,
|
| 145 |
+
merge_de: float = 12.0, is_solid: Callable[[np.ndarray], bool] | None = None
|
| 146 |
+
) -> list[ColorCluster]:
|
| 147 |
"""Mode-seeking on a quantised Lab histogram: each peak is a series colour.
|
| 148 |
|
| 149 |
Anti-aliased blends spread thinly along bg->colour segments, so they do not form
|
| 150 |
peaks; pure series colours do. ``k`` is chosen automatically by stopping when
|
| 151 |
+
the next peak holds less than ``min_frac`` of the pixels. A peak on such a
|
| 152 |
+
segment that ``is_solid`` (fills areas, e.g. a light tint of another series'
|
| 153 |
+
colour) is kept as its own colour.
|
| 154 |
"""
|
| 155 |
if len(pixels) == 0:
|
| 156 |
return []
|
|
|
|
| 163 |
centers = uniq.astype(np.float32) * bin_size
|
| 164 |
alive = np.ones(len(uniq), bool)
|
| 165 |
total = float(len(pix))
|
| 166 |
+
# Collect peaks generously (anti-aliasing of thin lines forms many small peaks
|
| 167 |
+
# that are merged below), then keep colours that hold min_frac after merging.
|
| 168 |
out: list[ColorCluster] = []
|
| 169 |
+
tries = 0
|
| 170 |
+
while len(out) < 3 * max_k and alive.any() and tries < 6 * max_k:
|
| 171 |
+
tries += 1
|
| 172 |
i = int(np.argmax(np.where(alive, counts, -1)))
|
| 173 |
c = centers[i]
|
| 174 |
for _ in range(3): # mean shift on bins
|
|
|
|
| 179 |
member = alive & (d < merge_de)
|
| 180 |
weight = counts[member].sum() / total
|
| 181 |
alive &= d >= 1.5 * merge_de
|
| 182 |
+
if weight < 0.4 * min_frac:
|
| 183 |
+
# A small peak (e.g. anti-aliasing of a big series) can come before a real
|
| 184 |
+
# but less dense colour: skip it; stop once only crumbs remain.
|
| 185 |
+
if counts[alive].sum() < min_frac * total:
|
| 186 |
+
break
|
| 187 |
+
continue
|
| 188 |
if np.linalg.norm(c - bg) < 15.0:
|
| 189 |
continue # residual background / faint blends
|
| 190 |
out.append(ColorCluster(lab=c, weight=float(weight)))
|
|
|
|
| 193 |
merged: list[ColorCluster] = []
|
| 194 |
for cl in sorted(out, key=lambda c: -float(np.linalg.norm(c.lab - bg))):
|
| 195 |
for m in merged:
|
| 196 |
+
if np.linalg.norm(m.lab - cl.lab) < merge_de or (
|
| 197 |
+
is_blend_of(cl.lab, m.lab, bg) and not (is_solid is not None and is_solid(cl.lab))):
|
| 198 |
m.weight += cl.weight
|
| 199 |
break
|
| 200 |
else:
|
| 201 |
merged.append(cl)
|
| 202 |
+
merged = [m for m in merged if m.weight >= min_frac]
|
| 203 |
+
return sorted(merged, key=lambda c: -c.weight)[:max_k]
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def solid_colour_test(lab: np.ndarray, cand: np.ndarray, min_area: int) -> Callable[[np.ndarray], bool]:
|
| 207 |
+
"""``is_solid`` for find_colors: pixels of that colour survive a 5x5 erosion
|
| 208 |
+
(filled areas), unlike 1-2 px anti-aliasing fringes."""
|
| 209 |
+
def test(c: np.ndarray) -> bool:
|
| 210 |
+
m = (cand & (np.linalg.norm(lab - c, axis=-1) < 8.0)).astype(np.uint8)
|
| 211 |
+
core = int(cv2.erode(m, np.ones((5, 5), np.uint8)).sum())
|
| 212 |
+
return core >= max(min_area, 0.25 * int(m.sum()))
|
| 213 |
+
return test
|
| 214 |
|
| 215 |
|
| 216 |
def lab_to_rgb(lab: np.ndarray) -> np.ndarray:
|
|
|
|
| 259 |
continue
|
| 260 |
a = np.clip(px @ v / vv, 0.0, 1.2)
|
| 261 |
d = np.linalg.norm(px - a[:, None] * v[None, :], axis=1)
|
| 262 |
+
# A pixel that is exactly a light tint (another series) also lies on the blend
|
| 263 |
+
# line of the saturated colour: prefer the colour it matches at full strength.
|
| 264 |
+
cost = d + 0.05 * np.sqrt(vv) * (1.0 - np.minimum(a, 1.0))
|
| 265 |
+
better = (cost < best_d) & (a > 0.25) & (d < tol)
|
| 266 |
+
best_d = np.where(better, cost, best_d)
|
| 267 |
best_i = np.where(better, i, best_i)
|
| 268 |
best_a = np.where(better, a, best_a)
|
| 269 |
labels[ys, xs] = best_i
|
|
|
|
| 287 |
return keep[lab]
|
| 288 |
|
| 289 |
|
| 290 |
+
def remove_text(mask: np.ndarray, char_h: float) -> tuple[np.ndarray, int]:
|
| 291 |
+
"""Remove annotation text drawn in a series colour (e.g. a label next to a curve).
|
| 292 |
+
|
| 293 |
+
Text = groups of >= 4 glyph-sized components (0.4-1.6 label heights) close to each
|
| 294 |
+
other with varied sizes. Dotted-line dots are smaller, markers are far apart and
|
| 295 |
+
dashes are uniform, so they are kept. Returns the cleaned mask and the number of
|
| 296 |
+
text groups removed.
|
| 297 |
+
"""
|
| 298 |
+
if char_h <= 0 or not mask.any():
|
| 299 |
+
return mask, 0
|
| 300 |
+
n, lab, stats, _ = cv2.connectedComponentsWithStats(mask.astype(np.uint8), connectivity=8)
|
| 301 |
+
x, y, w, h, area = (stats[1:, k].astype(float) for k in range(5))
|
| 302 |
+
glyph = np.flatnonzero((np.maximum(w, h) >= 0.4 * char_h) & (np.maximum(w, h) <= 1.6 * char_h))
|
| 303 |
+
if glyph.size < 4:
|
| 304 |
+
return mask, 0
|
| 305 |
+
parent = {int(i): int(i) for i in glyph}
|
| 306 |
+
|
| 307 |
+
def root(i: int) -> int:
|
| 308 |
+
while parent[i] != i:
|
| 309 |
+
parent[i] = parent[parent[i]]
|
| 310 |
+
i = parent[i]
|
| 311 |
+
return i
|
| 312 |
+
|
| 313 |
+
gap = 0.5 * char_h
|
| 314 |
+
for a_i, a in enumerate(glyph):
|
| 315 |
+
for b in glyph[a_i + 1:]:
|
| 316 |
+
dx = max(x[b] - (x[a] + w[a]), x[a] - (x[b] + w[b]), 0.0)
|
| 317 |
+
dy = max(y[b] - (y[a] + h[a]), y[a] - (y[b] + h[b]), 0.0)
|
| 318 |
+
if max(dx, dy) <= gap:
|
| 319 |
+
parent[root(int(a))] = root(int(b))
|
| 320 |
+
groups: dict[int, list[int]] = {}
|
| 321 |
+
for i in glyph:
|
| 322 |
+
groups.setdefault(root(int(i)), []).append(int(i))
|
| 323 |
+
drop = np.zeros(n, bool)
|
| 324 |
+
found = 0
|
| 325 |
+
|
| 326 |
+
def thick(i: int) -> bool:
|
| 327 |
+
# Most letters are thick in every direction (o, a, e, R); dashes and line
|
| 328 |
+
# pieces are thin across, whatever their angle.
|
| 329 |
+
ys, xs = np.nonzero(lab[int(y[i]):int(y[i] + h[i]), int(x[i]):int(x[i] + w[i])] == i + 1)
|
| 330 |
+
(_, _), (rw, rh), _ = cv2.minAreaRect(np.stack([xs, ys], 1).astype(np.float32))
|
| 331 |
+
return min(rw, rh) >= 0.3 * char_h
|
| 332 |
+
|
| 333 |
+
for g in groups.values():
|
| 334 |
+
if len(g) < 4:
|
| 335 |
+
continue
|
| 336 |
+
g_thick = [i for i in g if thick(i)]
|
| 337 |
+
if len(g_thick) < 4:
|
| 338 |
+
continue
|
| 339 |
+
# Letters differ in size or sit almost touching; repeated data markers are
|
| 340 |
+
# identical and spaced along their line.
|
| 341 |
+
ar = area[g_thick]
|
| 342 |
+
gaps = []
|
| 343 |
+
for a in g_thick:
|
| 344 |
+
gaps.append(min(max(x[b] - (x[a] + w[a]), x[a] - (x[b] + w[b]), y[b] - (y[a] + h[a]),
|
| 345 |
+
y[a] - (y[b] + h[b]), 0.0) for b in g_thick if b != a))
|
| 346 |
+
lettered = np.std(ar) / np.mean(ar) > 0.12 or float(np.median(gaps)) <= 0.35 * char_h
|
| 347 |
+
# A label is one line of glyphs (any angle); a cluster of scatter markers is not.
|
| 348 |
+
c = np.stack([x[g_thick] + w[g_thick] / 2, y[g_thick] + h[g_thick] / 2], 1)
|
| 349 |
+
c = c - c.mean(axis=0)
|
| 350 |
+
sv = np.linalg.svd(c, compute_uv=False)
|
| 351 |
+
across = float(sv[1] / np.sqrt(len(c))) if len(sv) > 1 else 0.0
|
| 352 |
+
span = max(x[g].max() + w[g].max(), 0) - x[g].min(), (y[g] + h[g]).max() - y[g].min()
|
| 353 |
+
if lettered and across <= 0.3 * char_h and max(span) >= 2.5 * char_h:
|
| 354 |
+
drop[np.asarray(g) + 1] = True
|
| 355 |
+
found += 1
|
| 356 |
+
if not found:
|
| 357 |
+
return mask, 0
|
| 358 |
+
return mask & ~drop[lab], found
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def split_marker_line(mask: np.ndarray, marker_size: float) -> tuple[np.ndarray, np.ndarray]:
|
| 362 |
+
"""Split one colour's mask into markers and a line (two legend entries of the same
|
| 363 |
+
colour, one a marker and one a line). Marks attached to markers (error bars)
|
| 364 |
+
belong to neither."""
|
| 365 |
+
k = max(3, int(round(0.6 * marker_size))) | 1
|
| 366 |
+
m = mask.astype(np.uint8)
|
| 367 |
+
blobs = cv2.morphologyEx(m, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k, k)))
|
| 368 |
+
markers = m & cv2.dilate(blobs, np.ones((3, 3), np.uint8))
|
| 369 |
+
rest = m & (1 - markers)
|
| 370 |
+
n, lab = cv2.connectedComponents(rest, connectivity=8)
|
| 371 |
+
touching = np.unique(lab[(cv2.dilate(markers, np.ones((5, 5), np.uint8)) > 0) & (lab > 0)])
|
| 372 |
+
line = rest.astype(bool) & ~np.isin(lab, touching)
|
| 373 |
+
return markers.astype(bool), line
|
| 374 |
+
|
| 375 |
+
|
| 376 |
def bg_for(ax: AxesResult) -> np.ndarray:
|
| 377 |
return np.asarray(ax.panel_bg, np.float32)
|
| 378 |
|
tests/test_tricky.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Regression checks on real figures that once failed (data/my_figs/tricky_examples).
|
| 2 |
+
|
| 3 |
+
The images are not in the repository (data/ is ignored); the tests are skipped when
|
| 4 |
+
they are missing. Expected values are read off the figures by eye.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pytest
|
| 13 |
+
|
| 14 |
+
from plotscribe import pipeline
|
| 15 |
+
|
| 16 |
+
DIR = Path("data/my_figs/tricky_examples")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def run(name: str):
|
| 20 |
+
p = DIR / name
|
| 21 |
+
if not p.exists():
|
| 22 |
+
pytest.skip(f"{p} not available")
|
| 23 |
+
return pipeline.run(str(p))
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def col(table, key: str) -> np.ndarray:
|
| 27 |
+
match = [c for c in table.columns if key in c]
|
| 28 |
+
assert match, f"no column containing {key!r}: {list(table.columns)}"
|
| 29 |
+
return table[match[0]].to_numpy(float)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_t1_dotted_lines_with_markers_log_axis():
|
| 33 |
+
# pgfplots: dotted lines with markers, coloured in-plot annotations, log y.
|
| 34 |
+
r = run("t_1.png")
|
| 35 |
+
t = r.table
|
| 36 |
+
assert r.chart_type == "line"
|
| 37 |
+
assert t["x"].round().tolist() == [20, 40, 50, 60, 70]
|
| 38 |
+
assert t.shape[1] == 5 # x + 4 legend series, no annotation series
|
| 39 |
+
np.testing.assert_allclose(col(t, "SBRNN")[1:], [3.8e-3, 9.3e-3, 5.6e-2, 0.11], rtol=0.15)
|
| 40 |
+
np.testing.assert_allclose(col(t, "Volterra")[1:], [2.0e-3, 5.0e-3, 6.6e-3, 1.1e-2], rtol=0.15)
|
| 41 |
+
np.testing.assert_allclose(col(t, "SFFNN"), [3.8e-5, 1.1e-3, 1.7e-3, 2.9e-3, 4.2e-3], rtol=0.15)
|
| 42 |
+
np.testing.assert_allclose(col(t, "auto-enc")[2:], [2.3e-5, 3.7e-4, 3.1e-3], rtol=0.15)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_t2_same_colour_marker_and_dashed_line():
|
| 46 |
+
# xmgrace: black diamonds and a black dashed line in one legend, black-outlined
|
| 47 |
+
# markers, an unlabelled red fit line.
|
| 48 |
+
r = run("t_2.png")
|
| 49 |
+
t = r.table
|
| 50 |
+
assert len(r.extra["legend_info"]["entries"]) == 7
|
| 51 |
+
greedy = col(t, "Greedy")
|
| 52 |
+
assert np.sum(np.isfinite(greedy)) >= 5
|
| 53 |
+
np.testing.assert_allclose(greedy[np.isfinite(greedy)], -0.693, atol=0.002)
|
| 54 |
+
parisi = col(t, "Parisi")
|
| 55 |
+
np.testing.assert_allclose(parisi[np.isfinite(parisi)], -0.763, atol=0.004)
|
| 56 |
+
eo = col(t, "EO-Heuristic")
|
| 57 |
+
assert np.sum(np.isfinite(eo)) >= 5
|
| 58 |
+
np.testing.assert_allclose(col(t, "GNN")[np.isfinite(col(t, "GNN"))], -0.612, atol=0.002)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def test_t3_grouped_bars_numeric_x_legend_with_bar_swatches():
|
| 62 |
+
r = run("t_3.png")
|
| 63 |
+
t = r.table
|
| 64 |
+
assert t["x"].tolist() == [10, 11, 12, 13, 14, 15]
|
| 65 |
+
np.testing.assert_allclose(col(t, "determination"), [0.646, 0.70, 0.729, 0.756, 0.788, 0.797], atol=0.01)
|
| 66 |
+
np.testing.assert_allclose(col(t, "pearson"), [0.966, 0.968, 0.971, 0.972, 0.975, 0.977], atol=0.01)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_t4_tinted_bars_against_spine():
|
| 70 |
+
# Light pink / lavender bars (tints of red / blue); last bar against the frame.
|
| 71 |
+
r = run("t_4.png")
|
| 72 |
+
t = r.table
|
| 73 |
+
assert t["x"].tolist() == pytest.approx([16, 32, 64])
|
| 74 |
+
assert t.shape[1] == 6
|
| 75 |
+
np.testing.assert_allclose(t.iloc[0, 1:].to_numpy(float), [12.7, 11.75, 12.1, 10.9, 10.8], atol=0.2)
|
| 76 |
+
np.testing.assert_allclose(t.iloc[2, 1:].to_numpy(float), [10.0, 7.6, 8.15, 7.05, 6.5], atol=0.2)
|