"""Scoring of extracted tables against ground truth. Errors are fractions of the axis range (in log10 space for log axes), so 0.01 means "1% of the axis range". Shared by the synthetic and real-image evaluators. """ from __future__ import annotations import math from dataclasses import dataclass, field from typing import Any import numpy as np import pandas as pd from scipy.optimize import linear_sum_assignment MISSING = float("nan") @dataclass class AxisInfo: lo: float hi: float log: bool = False def norm(self, v: np.ndarray) -> np.ndarray: v = np.asarray(v, float) if self.log: with np.errstate(divide="ignore", invalid="ignore"): return (np.log10(np.where(v > 0, v, np.nan)) - math.log10(self.lo)) / ( math.log10(self.hi) - math.log10(self.lo)) return (v - self.lo) / (self.hi - self.lo) @dataclass class TableScore: point_errors: list[float] = field(default_factory=list) n_gt_points: int = 0 n_matched_points: int = 0 n_pred_points: int = 0 n_gt_series: int = 0 n_pred_series: int = 0 category_acc: float | None = None notes: list[str] = field(default_factory=list) @property def recall(self) -> float: return self.n_matched_points / self.n_gt_points if self.n_gt_points else 0.0 @property def median(self) -> float: return float(np.median(self.point_errors)) if self.point_errors else MISSING @property def p90(self) -> float: return float(np.percentile(self.point_errors, 90)) if self.point_errors else MISSING @property def max(self) -> float: return float(np.max(self.point_errors)) if self.point_errors else MISSING def summary(self) -> dict[str, Any]: return { "median_err": self.median, "p90_err": self.p90, "max_err": self.max, "recall": self.recall, "n_gt_series": self.n_gt_series, "n_pred_series": self.n_pred_series, "series_count_ok": self.n_gt_series == self.n_pred_series, "category_acc": self.category_acc, "notes": self.notes, } def _series_cols(df: pd.DataFrame) -> list[str]: return [c for c in df.columns[1:]] def _base_name(col: str) -> str: return col.replace(" (segment)", "").split(" [")[0].strip().lower() def _norm_cat(s: Any) -> str: return "".join(ch for ch in str(s).lower() if ch.isalnum()) def _pair_errors_numeric_x(px: np.ndarray, py: np.ndarray, gx: np.ndarray, gy: np.ndarray, xa: AxisInfo, ya: AxisInfo) -> tuple[list[float], int]: """Interpolate the predicted polyline at the GT x positions (normalised space).""" ok = np.isfinite(px) & np.isfinite(py) px, py = px[ok], py[ok] if len(px) == 0: return [], 0 nx, ny = xa.norm(px), ya.norm(py) fin = np.isfinite(nx) & np.isfinite(ny) nx, ny = nx[fin], ny[fin] if len(nx) == 0: return [], 0 order = np.argsort(nx) nx, ny = nx[order], ny[order] gnx, gny = xa.norm(gx), ya.norm(gy) tol = 0.01 errs = [] for x, y in zip(gnx, gny): if x < nx[0] - tol or x > nx[-1] + tol: continue e = abs(float(np.interp(x, nx, ny)) - y) if np.isfinite(e): errs.append(e) return errs, len(errs) def _pair_errors_points(px: np.ndarray, py: np.ndarray, gx: np.ndarray, gy: np.ndarray, xa: AxisInfo, ya: AxisInfo, gate: float = 0.05) -> tuple[list[float], int]: """Optimal 1-1 point matching (scatter); errors are max(|dx|, |dy|) normalised.""" ok = np.isfinite(px) & np.isfinite(py) px, py = px[ok], py[ok] if len(px) == 0 or len(gx) == 0: return [], 0 P = np.stack([xa.norm(px), ya.norm(py)], 1) G = np.stack([xa.norm(gx), ya.norm(gy)], 1) d = np.max(np.abs(G[:, None, :] - P[None, :, :]), axis=2) d = np.nan_to_num(d, nan=10.0) r, c = linear_sum_assignment(d) errs = [float(d[i, j]) for i, j in zip(r, c) if d[i, j] < gate] return errs, len(errs) def _pair_errors_categorical(pcat: list[str], pv: np.ndarray, gcat: list[str], gv: np.ndarray, ya: AxisInfo) -> tuple[list[float], int]: if len(pcat) == len(gcat): idx = list(range(len(gcat))) else: lookup = {_norm_cat(c): i for i, c in enumerate(pcat)} idx = [lookup.get(_norm_cat(c), -1) for c in gcat] errs = [] for gi, pi in enumerate(idx): if pi < 0 or not np.isfinite(pv[pi]): continue e = abs(float(ya.norm(pv[pi]) - ya.norm(gv[gi]))) if np.isfinite(e): errs.append(e) return errs, len(errs) def score_table(pred: pd.DataFrame | None, gt: pd.DataFrame, kind: str, xa: AxisInfo | None, ya: AxisInfo) -> TableScore: """Score a predicted table (plotscribe CSV layout) against the GT table. ``kind``: ``scatter`` (point matching), ``categorical`` (rows by category) or ``numeric`` (polyline interpolation at GT x). For stacked bars the values are segment heights; ``ya`` should then span the segment range (handled by caller). """ s = TableScore() gcols = _series_cols(gt) s.n_gt_series = len(gcols) s.n_gt_points = int(sum(gt[c].notna().sum() for c in gcols)) if pred is None or pred.shape[1] < 2: s.notes.append("no prediction") return s pcols = _series_cols(pred) s.n_pred_series = len(pcols) if kind != "categorical": x_num = pd.to_numeric(pred.iloc[:, 0], errors="coerce") if x_num.isna().mean() > 0.5: s.notes.append("predicted x axis is not numeric") return s pred = pred.assign(**{pred.columns[0]: x_num}) s.n_pred_points = int(sum(pred[c].notna().sum() for c in pcols)) if kind == "categorical": gcat = [str(v) for v in gt.iloc[:, 0]] pcat = [str(v) for v in pred.iloc[:, 0]] if len(pcat) == len(gcat): s.category_acc = float(np.mean([_norm_cat(a) == _norm_cat(b) for a, b in zip(pcat, gcat)])) else: s.category_acc = 0.0 s.notes.append(f"category count {len(pcat)} vs {len(gcat)}") pair: dict[tuple[int, int], list[float]] = {} cost = np.full((len(gcols), len(pcols)), 10.0) for i, gc in enumerate(gcols): gmask = gt[gc].notna().to_numpy() for j, pc in enumerate(pcols): pmask = pred[pc].notna().to_numpy() if kind == "scatter": errs, _ = _pair_errors_points( pred.iloc[:, 0].to_numpy(float)[pmask], pred[pc].to_numpy(float)[pmask], gt.iloc[:, 0].to_numpy(float)[gmask], gt[gc].to_numpy(float)[gmask], xa, ya) elif kind == "categorical": errs, _ = _pair_errors_categorical( [str(v) for v in pred.iloc[:, 0]], pred[pc].to_numpy(float), [str(v) for v in gt.iloc[:, 0]], gt[gc].to_numpy(float), ya) else: errs, _ = _pair_errors_numeric_x( pred.iloc[:, 0].to_numpy(float)[pmask], pred[pc].to_numpy(float)[pmask], gt.iloc[:, 0].to_numpy(float)[gmask], gt[gc].to_numpy(float)[gmask], xa, ya) pair[(i, j)] = errs n_g = int(gmask.sum()) # Cost: mean error with missing points penalised as 0.5 (half the axis range). miss = n_g - len(errs) c = (sum(min(e, 0.5) for e in errs) + 0.5 * miss) / max(n_g, 1) if _base_name(gc) == _base_name(pc): c -= 0.05 cost[i, j] = c r, c = linear_sum_assignment(np.nan_to_num(cost, nan=10.0, posinf=10.0)) for i, j in zip(r, c): errs = pair[(i, j)] s.point_errors.extend(errs) s.n_matched_points += len(errs) return s def calibration_error(cal: Any, ticks: list[dict[str, Any]], axis: AxisInfo) -> float: """Max normalised error of a numeric calibration evaluated at the GT tick pixels.""" if cal is None or cal.kind == "categorical" or not ticks: return MISSING px = np.array([t["px"] for t in ticks]) vals = np.array([t["value"] for t in ticks]) with np.errstate(all="ignore"): pred = cal.to_value(px) err = np.abs(axis.norm(pred) - axis.norm(vals)) return float(np.nanmax(err)) if np.isfinite(err).any() else 1.0 def tick_recall(pred_px: list[float], gt_px: list[float], tol: float) -> float: if not gt_px: return MISSING p = np.asarray(pred_px) if p.size == 0: return 0.0 return float(np.mean([np.min(np.abs(p - g)) <= tol for g in gt_px])) def rnss(pred: pd.DataFrame | None, gt: pd.DataFrame) -> float: """Relative Number Set Similarity (ChartQA / DePlot chart-to-table metric), in [0, 1]. Compares only the unordered sets of numeric values (series cells): pairwise cost min(1, |p - t| / |t|), optimal 1-1 matching, normalised by the larger set size. """ def nums(df: pd.DataFrame | None) -> np.ndarray: if df is None or df.shape[1] < 2: return np.zeros(0) v = pd.to_numeric(df.iloc[:, 1:].stack(), errors="coerce").to_numpy(float) return v[np.isfinite(v)] p, t = nums(pred), nums(gt) if len(t) == 0: return float(len(p) == 0) if len(p) == 0: return 0.0 with np.errstate(divide="ignore", invalid="ignore"): cost = np.minimum(1.0, np.abs(p[None, :] - t[:, None]) / np.abs(t[:, None])) cost = np.nan_to_num(cost, nan=1.0, posinf=1.0) r, c = linear_sum_assignment(cost) return float(1.0 - cost[r, c].sum() / max(len(p), len(t)))