diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 6b58743..1a7765f 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -33,6 +33,14 @@ jobs: with: python-version: "3.12" enable-cache: true + # solver estimates plotted on the benchmark pages (orphan branch, missing + # before the first benchmark run) + - name: Fetch solver estimates + run: | + mkdir -p estimates + if git fetch --depth 1 origin estimates; then + git archive FETCH_HEAD | tar -x -C estimates + fi - name: Install run: uv sync --locked --no-dev --group doc - name: Build diff --git a/.github/workflows/pr_smoke.yml b/.github/workflows/pr_smoke.yml index 68de1c6..4a6e482 100644 --- a/.github/workflows/pr_smoke.yml +++ b/.github/workflows/pr_smoke.yml @@ -72,8 +72,8 @@ jobs: run: > uv run benchopt run benchmarks/${{ matrix.benchmark }} -r 1 --no-plot --no-display --no-cache - --output "$RUNNER_TEMP/${{ matrix.benchmark }}.csv" + --output "$RUNNER_TEMP/${{ matrix.benchmark }}.parquet" - name: Collect results (dry run) run: > uv run python scripts/collect_results.py ${{ matrix.benchmark }} - "$RUNNER_TEMP/${{ matrix.benchmark }}.csv" --dry-run + "$RUNNER_TEMP/${{ matrix.benchmark }}.parquet" --dry-run diff --git a/.github/workflows/run_benchmarks.yml b/.github/workflows/run_benchmarks.yml index e72fc22..fdcba71 100644 --- a/.github/workflows/run_benchmarks.yml +++ b/.github/workflows/run_benchmarks.yml @@ -84,16 +84,33 @@ jobs: uv run benchopt run benchmarks/${{ matrix.benchmark }} --config benchmarks/${{ matrix.benchmark }}/run_config.yml --no-plot --no-display --no-cache - --output "$RUNNER_TEMP/${{ matrix.benchmark }}.csv" + --output "$RUNNER_TEMP/${{ matrix.benchmark }}.parquet" + # the orphan `estimates` branch holds the solver estimates of all the + # rows in results/*.csv (it does not exist before the first run): the + # ones of this benchmark are needed to prune the stale files + - name: Fetch committed estimates + env: + BENCH: ${{ matrix.benchmark }} + run: | + mkdir -p estimates + if git fetch --depth 1 origin estimates \ + && git cat-file -e "FETCH_HEAD:$BENCH" 2>/dev/null; then + git archive FETCH_HEAD "$BENCH" | tar -x -C estimates + fi - name: Update result table run: > uv run python scripts/collect_results.py ${{ matrix.benchmark }} - "$RUNNER_TEMP/${{ matrix.benchmark }}.csv" + "$RUNNER_TEMP/${{ matrix.benchmark }}.parquet" - uses: actions/upload-artifact@v4 with: name: results-${{ matrix.benchmark }} path: results/${{ matrix.benchmark }}.csv if-no-files-found: error + - uses: actions/upload-artifact@v4 + with: + name: estimates-${{ matrix.benchmark }} + path: estimates/ + if-no-files-found: ignore commit: needs: run @@ -111,10 +128,47 @@ jobs: pattern: results-* merge-multiple: true path: results - - name: Commit results + - uses: actions/download-artifact@v4 + # no estimates are uploaded if every run failed + continue-on-error: true + with: + pattern: estimates-* + merge-multiple: true + path: ${{ runner.temp }}/estimates + - name: Configure git run: | git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + # the estimates are force-pushed to the orphan `estimates` branch as a + # single parentless commit, so that they never pile up in the history + - name: Publish estimates + run: | + tree_dir="$RUNNER_TEMP/estimates-tree" + mkdir -p "$tree_dir" + old_tree="" + if git fetch --depth 1 origin estimates; then + git archive FETCH_HEAD | tar -x -C "$tree_dir" + old_tree=$(git rev-parse "FETCH_HEAD^{tree}") + fi + # every artifact holds all the estimates of its benchmark + for dir in "$RUNNER_TEMP"/estimates/*/; do + [ -d "$dir" ] || continue + bench=$(basename "$dir") + rm -rf "${tree_dir:?}/$bench" + cp -r "$dir" "$tree_dir/$bench" + done + # build the commit in a separate index, leaving the checkout alone + export GIT_INDEX_FILE="$RUNNER_TEMP/estimates.index" + git -C "$tree_dir" --git-dir="$GITHUB_WORKSPACE/.git" --work-tree=. add -A + tree=$(git write-tree) + if [ "$tree" = "$old_tree" ]; then + echo "No estimate changes" + exit 0 + fi + commit=$(git commit-tree "$tree" -m "Update solver estimates") + git push --force origin "$commit:refs/heads/estimates" + - name: Commit results + run: | git add results/*.csv if git diff --cached --quiet; then echo "No result changes" diff --git a/.gitignore b/.gitignore index 5c51efc..65bb861 100644 --- a/.gitignore +++ b/.gitignore @@ -234,3 +234,6 @@ benchmarks/*/data/ # Generated docs pages docs/auto_benchmarks/ + +# Solver estimates (published on the `estimates` branch) +/estimates/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0cb642b..97db804 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -13,6 +13,7 @@ benchmarks// one BenchOpt benchmark per problem README.md description shown on the website benchmarks/_template/ copy-me skeleton results/.csv one result table per benchmark (written by CI) +estimates// solver estimates (written by CI to the `estimates` branch) scripts/ result collection docs/ Sphinx website built from results/ ``` @@ -47,6 +48,12 @@ uv sync --all-groups # creates .venv with the package, tests (dev) and docs that returns a matplotlib `Figure` of the true model and the data (import matplotlib inside the method). The website draws it for every dataset configuration in the result table and shows it above its leaderboard. +7. Optionally, add a `plot_estimate(self, x_true, x, meta)` method to each + dataset that returns a `Figure` comparing the estimate `x` of a solver with + the true model (e.g. true model, estimate and error, with the same colour + scales as `plot`). The website draws it for every row of the leaderboard + that has a saved estimate and links it from the *Figure* column; the solver + name and PSNR are added as a title. ## Add a solver @@ -57,7 +64,9 @@ of solver and regularizer/preconditioner: other hyperparameters exposed as `parameters` (lists of values are swept); - build all operators in `set_objective` (not timed) and only solve in `run` (timed); -- `get_result` returns `dict(x=...)` with `x` of shape `meta["dims"]`; +- `get_result` returns `dict(x=...)` with `x` of shape `meta["dims"]` + (the objective saves it with `save_final_results`, to plot it on the + website); - if the solver uses randomness (e.g. a starting vector for power iterations), seed it. @@ -78,20 +87,33 @@ to force a fresh run (e.g. to get new timings). To update the result table from a run (CI does this automatically): ```bash -uv run benchopt run benchmarks/ --no-plot --no-cache --output /tmp/raw.csv -uv run python scripts/collect_results.py /tmp/raw.csv +uv run benchopt run benchmarks/ --no-plot --no-cache --output /tmp/raw.parquet +uv run python scripts/collect_results.py /tmp/raw.parquet ``` Rows are keyed on objective, dataset, solver and all their parameters: a rerun replaces the corresponding row (and its `run_date`), a new configuration adds a row. +Only `.parquet` outputs hold the solver estimates: they are saved in +`estimates//.npz` (single precision) and the file name goes in the +`estimate` column of the table. Files no longer referenced by the table are +removed. A `.csv` output also works, but its rows get no estimate. + Build the website: ```bash uv run sphinx-build -W docs docs/_build/html ``` +The estimates are not stored on `main`, but on the orphan `estimates` +branch, which CI overwrites with a single commit at every run. To show them +on a local build, extract that branch into `estimates/`: + +```bash +git fetch origin estimates && mkdir -p estimates && git archive FETCH_HEAD | tar -x -C estimates +``` + ## Continuous integration All workflows install the locked environment with `uv sync --locked`. @@ -102,6 +124,8 @@ All workflows install the locked environment with `uv sync --locked`. - **Run benchmarks** (`run_benchmarks.yml`): on push to `main` (changed benchmarks only) or manually (one or all benchmarks, optionally against a PyLops git ref). Results are upserted into `results/.csv` and - committed by `github-actions[bot]`. + committed by `github-actions[bot]`. The solver estimates are merged with + those on the `estimates` branch, which is force-pushed as a single + parentless commit (so binaries never pile up in the history). - **Docs** (`docs.yml`): manually or weekly, builds the website from - `results/` and deploys it to GitHub Pages. + `results/` and the `estimates` branch, and deploys it to GitHub Pages. diff --git a/README.md b/README.md index c369e9b..5a864b1 100644 --- a/README.md +++ b/README.md @@ -20,8 +20,10 @@ the true model using PyLops' MAE and PSNR. | [`seismic_poststack`](benchmarks/seismic_poststack) | Seismic post-stack inversion | | [`seismic_prestack`](benchmarks/seismic_prestack) | Seismic pre-stack inversion | -Results are stored in [`results/`](results) (one CSV per benchmark) and -published at https://pylops.github.io/pylops-benchmarks. +Results are stored in [`results/`](results) (one CSV per benchmark), the +estimates of the solvers in the +[`estimates`](https://github.com/PyLops/pylops-benchmarks/tree/estimates) +branch, and both are published at https://pylops.github.io/pylops-benchmarks. ## Quick start @@ -48,10 +50,14 @@ To preview the pages with results from a local run instead of the committed ones, collect them into a separate folder and point the build to it: ```bash -uv run benchopt run benchmarks/seismic_interpolation --no-plot --no-cache --output /tmp/raw.csv -uv run python scripts/collect_results.py seismic_interpolation /tmp/raw.csv --results-dir /tmp/results -uv run sphinx-build -W -D results_dir=/tmp/results docs docs/_build/html +uv run benchopt run benchmarks/seismic_interpolation --no-plot --no-cache --output /tmp/raw.parquet +uv run python scripts/collect_results.py seismic_interpolation /tmp/raw.parquet --results-dir /tmp/results --estimates-dir /tmp/estimates +uv run sphinx-build -W -D results_dir=/tmp/results -D estimates_dir=/tmp/estimates docs docs/_build/html ``` +The leaderboards link a figure of the estimate of every solver, plotted from +the estimates stored on the `estimates` branch (see +[CONTRIBUTING.md](CONTRIBUTING.md)). + See [CONTRIBUTING.md](CONTRIBUTING.md) to add problems and solvers, and for details on the CI. diff --git a/asession/estimate-figures/SUMMARY.md b/asession/estimate-figures/SUMMARY.md new file mode 100644 index 0000000..947f093 --- /dev/null +++ b/asession/estimate-figures/SUMMARY.md @@ -0,0 +1,78 @@ +# Session summary: solver estimate figures on benchmark pages + +**Date:** 2026-10-23 +**Outcome:** PR [#17](https://github.com/PyLops/pylops-benchmarks/pull/17) from branch `estimate-figures` (based on `main`, separate from the PnP/RED work on `pnp-red`) + +## Goal + +The benchmark pages showed the true model and data of each dataset, and a +leaderboard of metrics. The user wanted to know whether a figure could be made +for every inversion, and then either shown on the page or linked from the +table rows. + +## Decisions taken with the user + +| Topic | Decision | +| ----- | -------- | +| Display | A **Figure** column in each leaderboard, with a `view` link to the PNG of that row. There is no gallery | +| Storage | An orphan **`estimates`** branch, force-pushed as a single parentless commit at every run, so it adds no git history | +| Format | Raw estimates (`.npz`), plotted at Sphinx build time like the dataset figures, so a change of plot style needs no re-run | +| CI git steps | The user did not want them tried locally against a bare remote, and will test them in CI | + +### Why this design + +- BenchOpt keeps only the metrics, and running the solvers again at docs time is not possible (runs take up to 6 h). +- BenchOpt 1.10 has an `Objective.save_final_results(**result)` hook. What it returns is stored inline in the **parquet** output (as safetensors/pickle bytes), and `benchopt.results.read_results` unpacks it back into an ndarray. A CSV output would turn the arrays into strings, so CI now writes `.parquet`. +- If the estimates were committed to `main`, every run would add MBs to the git history (Ascent is 512x512 per solver). Workflow artifacts expire after 90 days. + +## What was built + +``` +benchmarks/*/objective.py save_final_results(self, x): return x +pylops_bench/results.py update_results reads .csv/.parquet (benchopt read_results); + tidy keeps the last repetition's estimate (_estimate column); + estimate_key: md5 of the non-empty normalised key values; + save_estimates: .npz in float32/complex64, prunes + files no longer in the table; new `estimate` CSV column +scripts/collect_results.py --estimates-dir (default estimates/) +benchmarks/*/datasets/*.py optional plot_estimate(x_true, x, meta): true | estimate | error + (1D: overlay plus error; prestack: 3x3 grid, one row per parameter) +docs/generate_benchmarks.py _load_dataset (once per dataset configuration), _figure, + _estimate_figures (title " (): PSNR xx dB"), + Figure column in _leaderboard; config value estimates_dir +docs/conf.py estimates_dir = /estimates +.github/workflows/run_benchmarks.yml + run job --output .parquet; fetch this benchmark from the estimates + branch (git archive); collect; upload estimates- + commit job rebuild the tree from the branch plus the artifacts, then + GIT_INDEX_FILE + write-tree + commit-tree + force-push + to refs/heads/estimates; then the CSV commit as before +.github/workflows/docs.yml extract the estimates branch into estimates/ before the build +.github/workflows/pr_smoke.yml --output .parquet (dry-run collect) +.gitignore /estimates/ +README.md, CONTRIBUTING.md plot_estimate, the estimates branch, local preview commands +tests/ estimate saving/keying/overwrite/prune/dry-run/CSV tests; + a plot_estimate test per benchmark +``` + +## Findings along the way + +- **With `run_once`, every repetition row has the estimate** in `final_results`. `tidy` keeps the last one. +- **pandas `groupby.agg` rejects functions that return arrays**, so the estimates are aggregated with a list comprehension over the groups. +- **Keys must be stable.** Empty values are skipped in the hash, so that parameter columns added by other solvers, and integers read back as floats from the CSV, do not change a row's key. +- **MyST turns links to existing local files into download links** (`_downloads//...png`), so the figures need no extra Sphinx config. +- **Sizes:** the estimates were 40 KB for compressive sensing (9 rows) and 496 KB for image deblurring (12 rows). + +## Verification done + +- `uv run pytest`: 56 passed. +- `compressive_sensing` and `image_deblurring` were run locally with parquet output, collected into scratch folders and built with `sphinx-build -W -D results_dir=... -D estimates_dir=...`. The Figure column and the download links render. The deblurring, compressive sensing, poststack and template figures were checked visually. +- The CI git plumbing was **not** tested locally. + +## Follow-ups + +- Watch the first `run_benchmarks.yml` run after the merge (it re-runs every benchmark, because every `objective.py` changed). It creates the `estimates` branch. Check the publish step, and check that `download-artifact` with no matching artifacts does not block the CSV commit (`continue-on-error`). +- Trigger `docs.yml` by hand afterwards to see the links, instead of waiting for the Monday build. +- If all of a benchmark's estimates are pruned, it uploads no artifact, so its old folder stays on the branch. This is a rare edge case. +- The estimate figures of denoising, MRI, deblending, interpolation and prestack have tests but have not been checked visually. +- `benchmarks/_template/README.md` does not mention `plot_estimate` (CONTRIBUTING.md and the template dataset cover it). diff --git a/benchmarks/_template/datasets/blocky_signal.py b/benchmarks/_template/datasets/blocky_signal.py index 10f44a0..0440eea 100644 --- a/benchmarks/_template/datasets/blocky_signal.py +++ b/benchmarks/_template/datasets/blocky_signal.py @@ -44,3 +44,20 @@ def plot(self, x_true, Op, y, meta): ax.legend() fig.tight_layout() return fig + + def plot_estimate(self, x_true, x, meta): + """True model, estimate of a solver and error, shown on the benchmark + page (optional).""" + import matplotlib.pyplot as plt + + x = np.real(x).reshape(meta["dims"]) + fig, axs = plt.subplots( + 2, 1, sharex=True, figsize=(9, 4.5), height_ratios=(2, 1) + ) + axs[0].plot(x_true, "k", lw=2, label="True model") + axs[0].plot(x, "r", lw=1, label="Estimate") + axs[0].legend() + axs[1].plot(x - x_true, "k", lw=1) + axs[1].set_title("Error") + fig.tight_layout() + return fig diff --git a/benchmarks/_template/objective.py b/benchmarks/_template/objective.py index 86d63d2..a7e957a 100644 --- a/benchmarks/_template/objective.py +++ b/benchmarks/_template/objective.py @@ -36,6 +36,10 @@ def set_data(self, x_true, Op, y, meta): def evaluate_result(self, x): return compute_metrics(self.x_true, x) + def save_final_results(self, x): + # stored in the parquet output, then plotted on the benchmark page + return x + def get_one_result(self): return dict(x=np.zeros(self.meta["dims"])) diff --git a/benchmarks/compressive_sensing/datasets/sparse_spikes.py b/benchmarks/compressive_sensing/datasets/sparse_spikes.py index 6eea992..bdb0740 100644 --- a/benchmarks/compressive_sensing/datasets/sparse_spikes.py +++ b/benchmarks/compressive_sensing/datasets/sparse_spikes.py @@ -56,3 +56,21 @@ def plot(self, x_true, Op, y, meta): axs[1].set_title("Data") fig.tight_layout() return fig + + def plot_estimate(self, x_true, x, meta): + """True sparse vector, estimate and error.""" + import matplotlib.pyplot as plt + + x = np.real(x).reshape(meta["dims"]) + fig, axs = plt.subplots( + 2, 1, sharex=True, figsize=(10, 4.5), height_ratios=(2, 1) + ) + axs[0].stem( + x_true, linefmt="k-", markerfmt="ko", basefmt="k-", label="True model" + ) + axs[0].plot(x, "r.", ms=8, label="Estimate") + axs[0].legend() + axs[1].plot(x - x_true, "k.-", lw=1) + axs[1].set_title("Error") + fig.tight_layout() + return fig diff --git a/benchmarks/compressive_sensing/objective.py b/benchmarks/compressive_sensing/objective.py index c7cdbc7..716790b 100644 --- a/benchmarks/compressive_sensing/objective.py +++ b/benchmarks/compressive_sensing/objective.py @@ -33,6 +33,10 @@ def set_data(self, x_true, Op, y, meta): def evaluate_result(self, x): return compute_metrics(self.x_true, x) + def save_final_results(self, x): + # stored in the parquet output, then plotted on the benchmark page + return x + def get_one_result(self): return dict(x=np.zeros(self.meta["dims"])) diff --git a/benchmarks/image_deblurring/datasets/python_logo.py b/benchmarks/image_deblurring/datasets/python_logo.py index ab1803e..00b9cb8 100644 --- a/benchmarks/image_deblurring/datasets/python_logo.py +++ b/benchmarks/image_deblurring/datasets/python_logo.py @@ -69,3 +69,21 @@ def plot(self, x_true, Op, y, meta): ax.axis("off") fig.tight_layout() return fig + + def plot_estimate(self, x_true, x, meta): + """True image, deblurred image and error.""" + import matplotlib.pyplot as plt + + x = np.real(x).reshape(meta["dims"]) + opts = dict(cmap="viridis", vmin=0, vmax=250) + fig, axs = plt.subplots(1, 3, figsize=(10, 3.5)) + axs[0].imshow(x_true, **opts) + axs[0].set_title("True model") + axs[1].imshow(x, **opts) + axs[1].set_title("Estimate") + axs[2].imshow(x - x_true, cmap="RdBu_r", vmin=-50, vmax=50) + axs[2].set_title("Error") + for ax in axs: + ax.axis("off") + fig.tight_layout() + return fig diff --git a/benchmarks/image_deblurring/objective.py b/benchmarks/image_deblurring/objective.py index 0d21e9b..fcb718b 100644 --- a/benchmarks/image_deblurring/objective.py +++ b/benchmarks/image_deblurring/objective.py @@ -33,6 +33,10 @@ def set_data(self, x_true, Op, y, meta): def evaluate_result(self, x): return compute_metrics(self.x_true, x) + def save_final_results(self, x): + # stored in the parquet output, then plotted on the benchmark page + return x + def get_one_result(self): return dict(x=np.zeros(self.meta["dims"])) diff --git a/benchmarks/image_denoising/datasets/ascent.py b/benchmarks/image_denoising/datasets/ascent.py index be44475..6c57ed5 100644 --- a/benchmarks/image_denoising/datasets/ascent.py +++ b/benchmarks/image_denoising/datasets/ascent.py @@ -53,3 +53,21 @@ def plot(self, x_true, Op, y, meta): ax.axis("off") fig.tight_layout() return fig + + def plot_estimate(self, x_true, x, meta): + """True image, denoised image and error.""" + import matplotlib.pyplot as plt + + x = np.real(x).reshape(meta["dims"]) + opts = dict(cmap="gray", vmin=0, vmax=1) + fig, axs = plt.subplots(1, 3, figsize=(12, 4)) + axs[0].imshow(x_true, **opts) + axs[0].set_title("True model") + axs[1].imshow(x, **opts) + axs[1].set_title("Estimate") + axs[2].imshow(x - x_true, cmap="RdBu_r", vmin=-0.2, vmax=0.2) + axs[2].set_title("Error") + for ax in axs: + ax.axis("off") + fig.tight_layout() + return fig diff --git a/benchmarks/image_denoising/objective.py b/benchmarks/image_denoising/objective.py index 585b010..96d58c1 100644 --- a/benchmarks/image_denoising/objective.py +++ b/benchmarks/image_denoising/objective.py @@ -33,6 +33,10 @@ def set_data(self, x_true, Op, y, meta): def evaluate_result(self, x): return compute_metrics(self.x_true, x) + def save_final_results(self, x): + # stored in the parquet output, then plotted on the benchmark page + return x + def get_one_result(self): return dict(x=np.zeros(self.meta["dims"])) diff --git a/benchmarks/mri/datasets/shepp_logan.py b/benchmarks/mri/datasets/shepp_logan.py index c90c8c7..ba411bc 100644 --- a/benchmarks/mri/datasets/shepp_logan.py +++ b/benchmarks/mri/datasets/shepp_logan.py @@ -75,3 +75,21 @@ def plot(self, x_true, Op, y, meta): ax.axis("off") fig.tight_layout() return fig + + def plot_estimate(self, x_true, x, meta): + """True image, reconstruction and error.""" + import matplotlib.pyplot as plt + + x = np.real(x).reshape(meta["dims"]) + opts = dict(cmap="gray", vmin=0, vmax=1) + fig, axs = plt.subplots(1, 3, figsize=(10, 3.8)) + axs[0].imshow(x_true, **opts) + axs[0].set_title("True model") + axs[1].imshow(x, **opts) + axs[1].set_title("Estimate") + axs[2].imshow(x - x_true, cmap="RdBu_r", vmin=-0.2, vmax=0.2) + axs[2].set_title("Error") + for ax in axs: + ax.axis("off") + fig.tight_layout() + return fig diff --git a/benchmarks/mri/objective.py b/benchmarks/mri/objective.py index 3b63235..32136cd 100644 --- a/benchmarks/mri/objective.py +++ b/benchmarks/mri/objective.py @@ -34,6 +34,10 @@ def set_data(self, x_true, Op, y, meta): def evaluate_result(self, x): return compute_metrics(self.x_true, x) + def save_final_results(self, x): + # stored in the parquet output, then plotted on the benchmark page + return x + def get_one_result(self): return dict(x=np.zeros(self.meta["dims"])) diff --git a/benchmarks/seismic_deblending/datasets/mobil_avo.py b/benchmarks/seismic_deblending/datasets/mobil_avo.py index 4cf815a..01f84b7 100644 --- a/benchmarks/seismic_deblending/datasets/mobil_avo.py +++ b/benchmarks/seismic_deblending/datasets/mobil_avo.py @@ -92,3 +92,30 @@ def plot(self, x_true, Op, y, meta): axs[0].set_ylabel("t [s]") fig.tight_layout() return fig + + def plot_estimate(self, x_true, x, meta): + """True model, deblended data and error, with the same clipping.""" + import matplotlib.pyplot as plt + + ns, nt = meta["dims"] + x = np.real(x).reshape(meta["dims"]) + clip = 0.3 * np.abs(x_true).max() + opts = dict( + cmap="gray", + vmin=-clip, + vmax=clip, + aspect="auto", + interpolation="none", + extent=(0, ns, nt * meta["dt"], 0), + ) + + fig, axs = plt.subplots(1, 3, sharey=True, figsize=(12, 4)) + for ax, d, title in zip( + axs, (x_true, x, x - x_true), ("True model", "Estimate", "Error") + ): + ax.imshow(d.T, **opts) + ax.set_title(title) + ax.set_xlabel("Source") + axs[0].set_ylabel("t [s]") + fig.tight_layout() + return fig diff --git a/benchmarks/seismic_deblending/objective.py b/benchmarks/seismic_deblending/objective.py index 374c207..8f6bc77 100644 --- a/benchmarks/seismic_deblending/objective.py +++ b/benchmarks/seismic_deblending/objective.py @@ -33,6 +33,10 @@ def set_data(self, x_true, Op, y, meta): def evaluate_result(self, x): return compute_metrics(self.x_true, x) + def save_final_results(self, x): + # stored in the parquet output, then plotted on the benchmark page + return x + def get_one_result(self): return dict(x=np.zeros(self.meta["dims"])) diff --git a/benchmarks/seismic_interpolation/datasets/linear_events.py b/benchmarks/seismic_interpolation/datasets/linear_events.py index 7f454e4..9b4348d 100644 --- a/benchmarks/seismic_interpolation/datasets/linear_events.py +++ b/benchmarks/seismic_interpolation/datasets/linear_events.py @@ -89,3 +89,30 @@ def plot(self, x_true, Op, y, meta): axs[0].set_ylabel("t [s]") fig.tight_layout() return fig + + def plot_estimate(self, x_true, x, meta): + """True model, reconstruction and error, with the same clipping.""" + import matplotlib.pyplot as plt + + xaxis, taxis = meta["xaxis"], meta["taxis"] + x = np.real(x).reshape(meta["dims"]) + clip = np.abs(x_true).max() + opts = dict( + cmap="gray", + vmin=-clip, + vmax=clip, + aspect="auto", + interpolation="none", + extent=(xaxis[0], xaxis[-1], taxis[-1], taxis[0]), + ) + + fig, axs = plt.subplots(1, 3, sharey=True, figsize=(12, 4)) + for ax, d, title in zip( + axs, (x_true, x, x - x_true), ("True model", "Estimate", "Error") + ): + ax.imshow(d.T, **opts) + ax.set_title(title) + ax.set_xlabel("x [m]") + axs[0].set_ylabel("t [s]") + fig.tight_layout() + return fig diff --git a/benchmarks/seismic_interpolation/objective.py b/benchmarks/seismic_interpolation/objective.py index 005cdf5..944a4be 100644 --- a/benchmarks/seismic_interpolation/objective.py +++ b/benchmarks/seismic_interpolation/objective.py @@ -35,6 +35,10 @@ def set_data(self, x_true, Op, y, meta): def evaluate_result(self, x): return compute_metrics(self.x_true, x) + def save_final_results(self, x): + # stored in the parquet output, then plotted on the benchmark page + return x + def get_one_result(self): return dict(x=np.zeros(self.meta["dims"])) diff --git a/benchmarks/seismic_poststack/datasets/marmousi.py b/benchmarks/seismic_poststack/datasets/marmousi.py index 44fb1b8..d58137f 100644 --- a/benchmarks/seismic_poststack/datasets/marmousi.py +++ b/benchmarks/seismic_poststack/datasets/marmousi.py @@ -92,3 +92,30 @@ def plot(self, x_true, Op, y, meta): axs[0].set_ylabel("z [km]") fig.tight_layout() return fig + + def plot_estimate(self, x_true, x, meta): + """True model, inverted model and error.""" + import matplotlib.pyplot as plt + + xx, z = meta["x"], meta["z"] + x = np.real(x).reshape(meta["dims"]) + extent = (xx[0], xx[-1], z[-1], z[0]) + vmin, vmax = x_true.min(), x_true.max() + mopts = dict(cmap="gist_rainbow", vmin=vmin, vmax=vmax, extent=extent) + eclip = 0.2 * (vmax - vmin) + + fig, axs = plt.subplots(1, 3, sharey=True, figsize=(12, 4)) + axs[0].imshow(x_true, **mopts) + axs[0].set_title("True model") + axs[1].imshow(x, **mopts) + axs[1].set_title("Estimate") + axs[2].imshow( + x - x_true, cmap="RdBu_r", vmin=-eclip, vmax=eclip, extent=extent + ) + axs[2].set_title("Error") + for ax in axs: + ax.axis("tight") + ax.set_xlabel("x [km]") + axs[0].set_ylabel("z [km]") + fig.tight_layout() + return fig diff --git a/benchmarks/seismic_poststack/objective.py b/benchmarks/seismic_poststack/objective.py index c63d855..25de0d0 100644 --- a/benchmarks/seismic_poststack/objective.py +++ b/benchmarks/seismic_poststack/objective.py @@ -37,6 +37,10 @@ def set_data(self, x_true, Op, y, meta): def evaluate_result(self, x): return compute_metrics(self.x_true, x) + def save_final_results(self, x): + # stored in the parquet output, then plotted on the benchmark page + return x + def get_one_result(self): return dict(x=np.zeros(self.meta["dims"])) diff --git a/benchmarks/seismic_prestack/datasets/marmousi.py b/benchmarks/seismic_prestack/datasets/marmousi.py index 0c536e2..eaae6db 100644 --- a/benchmarks/seismic_prestack/datasets/marmousi.py +++ b/benchmarks/seismic_prestack/datasets/marmousi.py @@ -117,3 +117,36 @@ def plot(self, x_true, Op, y, meta): ax.axis("tight") fig.tight_layout() return fig + + def plot_estimate(self, x_true, x, meta): + """True models, inverted models and errors, one row per parameter.""" + import matplotlib.pyplot as plt + + xx, z = meta["x"], meta["z"] + x = np.real(x).reshape(meta["dims"]) + extent = (xx[0], xx[-1], z[-1], z[0]) + + fig, axs = plt.subplots(3, 3, sharex=True, sharey=True, figsize=(12, 9)) + for ip, param in enumerate((r"$V_P$", r"$V_S$", r"$\rho$")): + vmin, vmax = x_true[:, ip].min(), x_true[:, ip].max() + mopts = dict(cmap="gist_rainbow", vmin=vmin, vmax=vmax, extent=extent) + eclip = 0.2 * (vmax - vmin) + axs[ip, 0].imshow(x_true[:, ip], **mopts) + axs[ip, 0].set_title(rf"True $\ln$ {param}") + axs[ip, 1].imshow(x[:, ip], **mopts) + axs[ip, 1].set_title(rf"Estimated $\ln$ {param}") + axs[ip, 2].imshow( + x[:, ip] - x_true[:, ip], + cmap="RdBu_r", + vmin=-eclip, + vmax=eclip, + extent=extent, + ) + axs[ip, 2].set_title(rf"Error $\ln$ {param}") + axs[ip, 0].set_ylabel("z [km]") + for ax in axs.ravel(): + ax.axis("tight") + for ax in axs[-1]: + ax.set_xlabel("x [km]") + fig.tight_layout() + return fig diff --git a/benchmarks/seismic_prestack/objective.py b/benchmarks/seismic_prestack/objective.py index 2862c07..68187ce 100644 --- a/benchmarks/seismic_prestack/objective.py +++ b/benchmarks/seismic_prestack/objective.py @@ -39,6 +39,10 @@ def set_data(self, x_true, Op, y, meta): def evaluate_result(self, x): return compute_metrics(self.x_true, x) + def save_final_results(self, x): + # stored in the parquet output, then plotted on the benchmark page + return x + def get_one_result(self): return dict(x=np.zeros(self.meta["dims"])) diff --git a/docs/conf.py b/docs/conf.py index cf1df67..3ac925d 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -26,6 +26,7 @@ repo_root = Path(__file__).resolve().parents[1] benchmarks_dir = str(repo_root / "benchmarks") results_dir = str(repo_root / "results") +estimates_dir = str(repo_root / "estimates") github_url = "https://github.com/PyLops/pylops-benchmarks" github_branch = "main" diff --git a/docs/generate_benchmarks.py b/docs/generate_benchmarks.py index df897c9..b8787ea 100644 --- a/docs/generate_benchmarks.py +++ b/docs/generate_benchmarks.py @@ -6,7 +6,10 @@ - ``.md``: the benchmark README followed, for every dataset configuration, by the dataset docstring and a leaderboard sorted by PSNR; - ``figures/*.png``: the true model and data of every dataset configuration - in the result table, drawn by the optional ``plot`` method of the dataset. + in the result table, drawn by the optional ``plot`` method of the dataset, + and the estimate of every solver whose file is found in ``estimates_dir``, + drawn by the optional ``plot_estimate`` method and linked from the + leaderboard. """ from __future__ import annotations @@ -18,6 +21,7 @@ from pathlib import Path import matplotlib +import numpy as np import pandas as pd from sphinx.util import logging @@ -106,28 +110,70 @@ def _dataset_class(bench_dir: Path, name: str): return None if path is None else load_class(path, "Dataset") -def _figure(cls, bench_dir: Path, row: pd.Series, figdir: Path) -> str | None: - """Plot the true model and data of the dataset configuration in ``row`` - and return the figure path relative to the benchmark page, or ``None`` - if the dataset has no ``plot`` method.""" - if not hasattr(cls, "plot"): - return None - name = row["dataset"] +def _load_dataset(cls, row: pd.Series): + """Instance and data of the dataset configuration in ``row``, or + ``(None, None)`` if the dataset has nothing to plot or fails to load.""" + if not (hasattr(cls, "plot") or hasattr(cls, "plot_estimate")): + return None, None params = _dataset_params(row, default_parameters(cls)) - slug = re.sub(r"\W+", "_", name.lower()).strip("_") + try: + dataset = cls.get_instance(**params) + return dataset, dataset.get_data() + except Exception as exc: # a broken dataset must not block the results + name = row["dataset"] + logger.info(f"generate_benchmarks: cannot load {name!r} ({params}): {exc}") + return None, None + + +def _figure(dataset, data, bench_dir: Path, figdir: Path) -> str | None: + """Plot the true model and data of ``dataset`` and return the figure + path relative to the benchmark page, or ``None`` if the dataset has no + ``plot`` method.""" + if not hasattr(dataset, "plot"): + return None + params = {k: getattr(dataset, k) for k in default_parameters(type(dataset))} + slug = re.sub(r"\W+", "_", dataset.name.lower()).strip("_") key = hashlib.md5(repr(sorted(params.items())).encode()).hexdigest()[:8] fname = f"{bench_dir.name}_{slug}_{key}.png" try: - dataset = cls.get_instance(**params) - fig = dataset.plot(**dataset.get_data()) + fig = dataset.plot(**data) fig.savefig(figdir / fname, dpi=150, bbox_inches="tight") plt.close(fig) except Exception as exc: # a broken plot must not block the results - logger.info(f"generate_benchmarks: cannot plot {name!r} ({params}): {exc}") + logger.info(f"generate_benchmarks: cannot plot {dataset.name!r}: {exc}") return None return f"{FIGDIR}/{fname}" +def _estimate_figures( + dataset, data, df: pd.DataFrame, estimates: Path, figdir: Path, varying +) -> dict: + """Plot the estimate of every row of ``df`` whose file is in ``estimates`` + and map the row index to the figure path relative to the benchmark page.""" + if not hasattr(dataset, "plot_estimate") or "estimate" not in df: + return {} + figures = {} + for idx, row in df.dropna(subset=["estimate"]).iterrows(): + path = estimates / row["estimate"] + if not path.exists(): + continue + fname = f"{estimates.name}_{path.stem}.png" + params = _solver_params(row, varying) + solver = f"{row['solver']} ({params})" if params else row["solver"] + try: + x = np.load(path)["x"] + fig = dataset.plot_estimate(x_true=data["x_true"], x=x, meta=data["meta"]) + fig.suptitle(f"{solver}: PSNR {row['PSNR']:.2f} dB") + fig.tight_layout() + fig.savefig(figdir / fname, dpi=100, bbox_inches="tight") + plt.close(fig) + except Exception as exc: # a broken plot must not block the results + logger.info(f"generate_benchmarks: cannot plot estimate {solver!r}: {exc}") + continue + figures[idx] = f"{FIGDIR}/{fname}" + return figures + + def _readme(bench_dir: Path) -> tuple[str, str]: """Return title and body of the benchmark README.""" readme = bench_dir / "README.md" @@ -147,10 +193,10 @@ def _table(header: list[str], rows: list[list[str]]) -> str: return "\n".join(out) -def _leaderboard(df: pd.DataFrame, solver_url, varying) -> str: +def _leaderboard(df: pd.DataFrame, solver_url, varying, figures: dict) -> str: df = df.sort_values("PSNR", ascending=False) rows = [] - for rank, (_, row) in enumerate(df.iterrows(), start=1): + for rank, (idx, row) in enumerate(df.iterrows(), start=1): url = solver_url(row["solver"]) solver = f"[{row['solver']}]({url})" if url else row["solver"] rows.append( @@ -161,9 +207,14 @@ def _leaderboard(df: pd.DataFrame, solver_url, varying) -> str: f"{row['MAE']:.4g}", f"{row['PSNR']:.2f}", f"{row['time_s']:.3f}", + f"[view]({figures[idx]})" if idx in figures else "", ] ) header = ["Rank", "Solver", "Parameters", "MAE", "PSNR [dB]", "Time [s]"] + header.append("Figure") + if not figures: # no estimate to show + header.pop() + rows = [row[:-1] for row in rows] if not any(row[2] for row in rows): # no parameter tells entries apart header.pop(2) rows = [row[:2] + row[3:] for row in rows] @@ -191,6 +242,7 @@ def solver_url(solver): lines.append("This benchmark has not been run yet.") return "\n".join(lines) + "\n" + estimates = Path(cfg.estimates_dir) / name if cfg.estimates_dir else None csv_url = f"{blob}/results/{name}.csv" lines += [f"Raw results: [`results/{name}.csv`]({csv_url}).", ""] dataset_cols = ["objective", "dataset"] + [ @@ -207,10 +259,16 @@ def solver_url(solver): lines += [inspect.cleandoc(cls.__doc__), ""] if params: lines += [f"Dataset parameters: `{params}`", ""] - figure = None if cls is None else _figure(cls, bench_dir, first, figdir) + dataset, data = (None, None) if cls is None else _load_dataset(cls, first) + figure = None if dataset is None else _figure(dataset, data, bench_dir, figdir) if figure: lines += [f"![True model and data of {first['dataset']}]({figure})", ""] - lines += [_leaderboard(group, solver_url, varying), ""] + figures = {} + if dataset is not None and estimates is not None: + figures = _estimate_figures( + dataset, data, group, estimates, figdir, varying + ) + lines += [_leaderboard(group, solver_url, varying, figures), ""] return "\n".join(lines) + "\n" @@ -277,6 +335,7 @@ def generate(app) -> None: def setup(app): app.add_config_value("benchmarks_dir", "", "env") app.add_config_value("results_dir", "", "env") + app.add_config_value("estimates_dir", "", "env") app.add_config_value("github_url", "", "env") app.add_config_value("github_branch", "main", "env") app.connect("builder-inited", generate) diff --git a/pylops_bench/results.py b/pylops_bench/results.py index 5590814..3e213a9 100644 --- a/pylops_bench/results.py +++ b/pylops_bench/results.py @@ -4,18 +4,26 @@ per (objective, dataset, dataset parameters, solver, solver parameters) configuration. Re-running a configuration replaces its row (upsert) and updates its ``run_date``. + +If the raw results come from a parquet file with the solver estimates (saved +by ``Objective.save_final_results``), each estimate is written to +``estimates//.npz`` and its file name is stored in the +``estimate`` column of the table. """ from __future__ import annotations +import hashlib from importlib.metadata import PackageNotFoundError, version from pathlib import Path import numpy as np import pandas as pd +from benchopt.results import read_results METRICS = ["MAE", "PSNR"] ID_COLUMNS = ["objective", "dataset", "solver"] +ESTIMATE = "estimate" def _package_version(name: str) -> str: @@ -50,6 +58,24 @@ def key_columns(df: pd.DataFrame) -> list[str]: return ID_COLUMNS + param_columns(df) +def estimate_key(row: pd.Series, keys: list[str]) -> str: + """Short hash of the configuration of ``row``. + + Empty values are skipped, so that the key does not change when other + solvers add parameter columns to the table. + """ + items = sorted((k, _norm(row[k])) for k in keys if _norm(row[k]) != "") + return hashlib.md5(repr(items).encode()).hexdigest()[:12] + + +def _last_valid(values: pd.Series): + """Last value that is not missing (estimates of the last repetition).""" + for value in reversed(values.tolist()): + if value is not None and not (isinstance(value, float) and np.isnan(value)): + return value + return None + + def tidy(raw: pd.DataFrame) -> pd.DataFrame: """Aggregate a raw BenchOpt result table into one row per configuration. @@ -80,6 +106,9 @@ def tidy(raw: pd.DataFrame) -> pd.DataFrame: df[m] = raw[f"objective_{m}"] df["time_s"] = raw["time"] df["run_date"] = pd.to_datetime(raw["run_date"]) + estimates = "final_results" in raw + if estimates: + df["_estimate"] = raw["final_results"] keys = key_columns(df) # group on normalised keys so that NaN parameters (not used by a given @@ -96,6 +125,10 @@ def tidy(raw: pd.DataFrame) -> pd.DataFrame: } ).reset_index(drop=True) out["n_repetitions"] = grouped.size().to_numpy() + if estimates: + # ``_estimate`` holds arrays: it is dropped by ``update_results`` + # once they are saved, and never written to the result table + out["_estimate"] = [_last_valid(s) for _, s in grouped["_estimate"]] out["run_date"] = out["run_date"].dt.strftime("%Y-%m-%d %H:%M:%S") out["pylops_version"] = _package_version("pylops") out["benchopt_version"] = _package_version("benchopt") @@ -105,7 +138,7 @@ def tidy(raw: pd.DataFrame) -> pd.DataFrame: def _order(df: pd.DataFrame) -> pd.DataFrame: keys = key_columns(df) rest = [c for c in df.columns if c not in keys] - first = ["MAE", "PSNR", "time_s", "n_repetitions"] + first = ["MAE", "PSNR", "time_s", "n_repetitions", ESTIMATE] rest = [c for c in first if c in rest] + [c for c in rest if c not in first] df = df[keys + rest] sort_key = df[keys].apply(lambda col: col.map(_norm)) @@ -128,18 +161,57 @@ def results_path(results_dir: Path | str, benchmark: str) -> Path: return Path(results_dir) / f"{benchmark}.csv" +def _compact(x) -> np.ndarray: + """Single precision copy of an estimate, to halve its size on disk.""" + x = np.asarray(x) + return x.astype(np.complex64 if np.iscomplexobj(x) else np.float32) + + +def save_estimates( + new: pd.DataFrame, merged: pd.DataFrame, estimates_dir: Path | str +) -> None: + """Write the estimates of ``new`` in ``estimates_dir`` and remove the + files no longer referenced by the ``merged`` result table.""" + estimates_dir = Path(estimates_dir) + estimates_dir.mkdir(parents=True, exist_ok=True) + if ESTIMATE in new: + for _, row in new.dropna(subset=[ESTIMATE]).iterrows(): + x = _compact(row["_estimate"]) + np.savez_compressed(estimates_dir / row[ESTIMATE], x=x) + used = set(merged[ESTIMATE].dropna()) if ESTIMATE in merged else set() + for path in estimates_dir.glob("*.npz"): + if path.name not in used: + path.unlink() + + def update_results( - raw_csv: Path | str, + raw_file: Path | str, benchmark: str, results_dir: Path | str = "results", + estimates_dir: Path | str | None = None, dry_run: bool = False, ) -> pd.DataFrame: - """Tidy ``raw_csv`` and upsert it into ``results/.csv``.""" - new = tidy(pd.read_csv(raw_csv)) + """Tidy ``raw_file`` (``.csv`` or ``.parquet``) and upsert it into + ``results/.csv``. + + If ``estimates_dir`` is given, the solver estimates held by the raw file + are saved in ``estimates_dir//``, and the files there that + are no longer referenced by the table are removed. + """ + new = tidy(read_results(raw_file)) + if estimates_dir is not None and "_estimate" in new: + keys = key_columns(new) + has_estimate = new["_estimate"].notna() + new.loc[has_estimate, ESTIMATE] = [ + f"{estimate_key(row, keys)}.npz" for _, row in new[has_estimate].iterrows() + ] + new = _order(new) path = results_path(results_dir, benchmark) existing = pd.read_csv(path) if path.exists() else None - merged = upsert(existing, new) + merged = upsert(existing, new.drop(columns="_estimate", errors="ignore")) if not dry_run: path.parent.mkdir(parents=True, exist_ok=True) merged.to_csv(path, index=False) + if estimates_dir is not None: + save_estimates(new, merged, Path(estimates_dir) / benchmark) return merged diff --git a/scripts/collect_results.py b/scripts/collect_results.py index 2a08340..b392f4d 100644 --- a/scripts/collect_results.py +++ b/scripts/collect_results.py @@ -2,11 +2,15 @@ Usage:: - python scripts/collect_results.py [--dry-run] + python scripts/collect_results.py [--dry-run] ```` is the name of the folder in ``benchmarks/``. Run this script in the same environment used to run the benchmark, as the PyLops and BenchOpt versions are read from it. + +The raw file can be a ``.csv`` or a ``.parquet`` file, but only the latter +holds the solver estimates, which are saved in +``//`` and plotted on the benchmark page. """ import argparse @@ -22,8 +26,11 @@ def main(): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("benchmark", help="benchmark folder name in benchmarks/") - parser.add_argument("raw_csv", type=Path, help="raw BenchOpt output (.csv)") + parser.add_argument( + "raw_file", type=Path, help="raw BenchOpt output (.parquet or .csv)" + ) parser.add_argument("--results-dir", type=Path, default=ROOT / "results") + parser.add_argument("--estimates-dir", type=Path, default=ROOT / "estimates") parser.add_argument( "--dry-run", action="store_true", help="print the table, do not write it" ) @@ -33,7 +40,11 @@ def main(): parser.error(f"unknown benchmark {args.benchmark!r}") table = update_results( - args.raw_csv, args.benchmark, args.results_dir, dry_run=args.dry_run + args.raw_file, + args.benchmark, + args.results_dir, + estimates_dir=args.estimates_dir, + dry_run=args.dry_run, ) with pd.option_context("display.width", 200, "display.max_columns", None): print(table) diff --git a/tests/test_compressive_sensing.py b/tests/test_compressive_sensing.py index 835e0c0..ba119c2 100644 --- a/tests/test_compressive_sensing.py +++ b/tests/test_compressive_sensing.py @@ -67,3 +67,19 @@ def test_dataset_plot(bench_loader, data): fig = bench_loader(DATASET, "Dataset").plot(**data) assert isinstance(fig, Figure) plt.close(fig) + + +def test_dataset_plot_estimate(bench_loader, data): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.figure import Figure + + # estimates are stored in single precision + x = data["x_true"].astype("float32") + fig = bench_loader(DATASET, "Dataset").plot_estimate( + x_true=data["x_true"], x=x, meta=data["meta"] + ) + assert isinstance(fig, Figure) + plt.close(fig) diff --git a/tests/test_image_deblurring.py b/tests/test_image_deblurring.py index 20b1b7c..6d34740 100644 --- a/tests/test_image_deblurring.py +++ b/tests/test_image_deblurring.py @@ -56,3 +56,19 @@ def test_dataset_plot(bench_loader, data): fig = bench_loader(DATASET, "Dataset").plot(**data) assert isinstance(fig, Figure) plt.close(fig) + + +def test_dataset_plot_estimate(bench_loader, data): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.figure import Figure + + # estimates are stored in single precision + x = data["x_true"].astype("float32") + fig = bench_loader(DATASET, "Dataset").plot_estimate( + x_true=data["x_true"], x=x, meta=data["meta"] + ) + assert isinstance(fig, Figure) + plt.close(fig) diff --git a/tests/test_image_denoising.py b/tests/test_image_denoising.py index 85b3099..55bd57f 100644 --- a/tests/test_image_denoising.py +++ b/tests/test_image_denoising.py @@ -56,3 +56,19 @@ def test_dataset_plot(bench_loader, data): fig = bench_loader(DATASET, "Dataset").plot(**data) assert isinstance(fig, Figure) plt.close(fig) + + +def test_dataset_plot_estimate(bench_loader, data): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.figure import Figure + + # estimates are stored in single precision + x = data["x_true"].astype("float32") + fig = bench_loader(DATASET, "Dataset").plot_estimate( + x_true=data["x_true"], x=x, meta=data["meta"] + ) + assert isinstance(fig, Figure) + plt.close(fig) diff --git a/tests/test_mri.py b/tests/test_mri.py index 423c8e5..369398f 100644 --- a/tests/test_mri.py +++ b/tests/test_mri.py @@ -70,3 +70,19 @@ def test_dataset_plot(bench_loader, data): fig = bench_loader(DATASET, "Dataset").plot(**data) assert isinstance(fig, Figure) plt.close(fig) + + +def test_dataset_plot_estimate(bench_loader, data): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.figure import Figure + + # estimates are stored in single precision + x = data["x_true"].astype("float32") + fig = bench_loader(DATASET, "Dataset").plot_estimate( + x_true=data["x_true"], x=x, meta=data["meta"] + ) + assert isinstance(fig, Figure) + plt.close(fig) diff --git a/tests/test_results.py b/tests/test_results.py index 0d21e6d..10dd689 100644 --- a/tests/test_results.py +++ b/tests/test_results.py @@ -1,7 +1,14 @@ +import numpy as np import pandas as pd import pytest -from pylops_bench.results import tidy, update_results, upsert +from pylops_bench.results import ( + estimate_key, + key_columns, + tidy, + update_results, + upsert, +) def _raw(niter_values, psnr=30.0, run_date="2026-01-01T10:00:00", nrep=1): @@ -86,3 +93,85 @@ def test_dry_run_does_not_write(tmp_path): def test_upsert_without_existing(): new = tidy(_raw([10])) assert upsert(None, new).equals(upsert(pd.DataFrame(), new)) + + +def _raw_with_estimates(raw: pd.DataFrame, value=1.0) -> pd.DataFrame: + raw = raw.copy() + raw["final_results"] = [np.full(4, value + i) for i in range(len(raw))] + return raw + + +def _write_parquet(raw: pd.DataFrame, path): + from benchopt.results import to_parquet + from benchopt.results.parquet import pack + + raw = raw.copy() + raw["final_results"] = raw["final_results"].map(pack) + to_parquet(raw, path) + return path + + +def test_estimates_are_saved(tmp_path): + raw = _write_parquet( + _raw_with_estimates(_raw([10], nrep=2)), tmp_path / "r.parquet" + ) + table = update_results(raw, "toy", tmp_path, estimates_dir=tmp_path / "est") + assert table["estimate"].notna().all() + files = sorted(p.name for p in (tmp_path / "est" / "toy").glob("*.npz")) + assert files == sorted(table["estimate"]) + lsqr = table[table.solver == "LSQR"].iloc[0] + x = np.load(tmp_path / "est" / "toy" / lsqr["estimate"])["x"] + # last repetition, in single precision + assert x.dtype == np.float32 + np.testing.assert_array_equal(x, np.full(4, 2.0)) + + +def test_estimate_key_is_stable(): + raw = _raw([10]) + new = tidy(raw) + keys = key_columns(new) + row = new[new.solver == "LSQR"].iloc[0] + # the key does not depend on parameter columns added by other solvers, + # nor on integers read back as floats from the CSV + wider = row.copy() + wider["solver_param_tau"] = np.nan + wider["dataset_param_seed"] = 0.0 + assert estimate_key(row, keys) == estimate_key(wider, keys + ["solver_param_tau"]) + other = new[new.solver == "FISTA"].iloc[0] + assert estimate_key(row, keys) != estimate_key(other, keys) + + +def test_estimates_are_replaced_and_pruned(tmp_path): + est = tmp_path / "est" + raw1 = _write_parquet(_raw_with_estimates(_raw([10])), tmp_path / "r1.parquet") + first = update_results(raw1, "toy", tmp_path, estimates_dir=est) + + # rerunning a configuration overwrites its file + raw2 = _write_parquet( + _raw_with_estimates(_raw([10]), value=5.0), tmp_path / "r2.parquet" + ) + second = update_results(raw2, "toy", tmp_path, estimates_dir=est) + assert sorted(first["estimate"]) == sorted(second["estimate"]) + lsqr = second[second.solver == "LSQR"].iloc[0] + assert np.load(est / "toy" / lsqr["estimate"])["x"][0] == 5.0 + + # a stale file, not referenced by the table, is removed + (est / "toy" / "stale.npz").write_bytes(b"") + update_results(raw2, "toy", tmp_path, estimates_dir=est) + assert not (est / "toy" / "stale.npz").exists() + assert len(list((est / "toy").glob("*.npz"))) == 2 + + +def test_estimates_dry_run_and_csv(tmp_path): + est = tmp_path / "est" + raw = _write_parquet(_raw_with_estimates(_raw([10])), tmp_path / "r.parquet") + update_results(raw, "toy", tmp_path, estimates_dir=est, dry_run=True) + assert not est.exists() + assert not (tmp_path / "toy.csv").exists() + + # CSV raw results have no estimates + raw_csv = tmp_path / "raw.csv" + _raw([10]).to_csv(raw_csv, index=False) + table = update_results(raw_csv, "toy", tmp_path, estimates_dir=est) + assert "estimate" not in table + assert "_estimate" not in pd.read_csv(tmp_path / "toy.csv") diff --git a/tests/test_seismic_deblending.py b/tests/test_seismic_deblending.py index f86d58d..163230c 100644 --- a/tests/test_seismic_deblending.py +++ b/tests/test_seismic_deblending.py @@ -46,3 +46,19 @@ def test_objective(bench_loader, data): metrics = objective.evaluate_result(data["x_true"]) assert metrics["MAE"] == 0.0 assert np.isinf(metrics["PSNR"]) + + +def test_dataset_plot_estimate(bench_loader, data): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.figure import Figure + + # estimates are stored in single precision + x = data["x_true"].astype("float32") + fig = bench_loader(DATASET, "Dataset").plot_estimate( + x_true=data["x_true"], x=x, meta=data["meta"] + ) + assert isinstance(fig, Figure) + plt.close(fig) diff --git a/tests/test_seismic_interpolation.py b/tests/test_seismic_interpolation.py index c72d1a5..e08cc7a 100644 --- a/tests/test_seismic_interpolation.py +++ b/tests/test_seismic_interpolation.py @@ -54,3 +54,19 @@ def test_dataset_plot(bench_loader, data): fig = bench_loader(DATASET, "Dataset").plot(**data) assert isinstance(fig, Figure) plt.close(fig) + + +def test_dataset_plot_estimate(bench_loader, data): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.figure import Figure + + # estimates are stored in single precision + x = data["x_true"].astype("float32") + fig = bench_loader(DATASET, "Dataset").plot_estimate( + x_true=data["x_true"], x=x, meta=data["meta"] + ) + assert isinstance(fig, Figure) + plt.close(fig) diff --git a/tests/test_seismic_prestack.py b/tests/test_seismic_prestack.py index 9038c91..d197ad5 100644 --- a/tests/test_seismic_prestack.py +++ b/tests/test_seismic_prestack.py @@ -58,3 +58,19 @@ def test_dataset_plot(bench_loader, data): fig = bench_loader(DATASET, "Dataset").plot(**data) assert isinstance(fig, Figure) plt.close(fig) + + +def test_dataset_plot_estimate(bench_loader, data): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.figure import Figure + + # estimates are stored in single precision + x = data["x_true"].astype("float32") + fig = bench_loader(DATASET, "Dataset").plot_estimate( + x_true=data["x_true"], x=x, meta=data["meta"] + ) + assert isinstance(fig, Figure) + plt.close(fig)