debug-inversion
Use this skill whenever a user shares PyLops code or results that misbehave and asks what is wrong - load it first, before running the user's code, testing a hypothesis or answering, even when the bug looks obvious from the code. Covers a crash or traceback (dtype/casting errors, shape mismatches), a solver (lsqr, cgls, cg, fista, ista, spgl1, regularized_inversion, splitbregman) that stalls, diverges, returns NaNs, zeros, ringing or a wrong model, one dataset or block being ignored in a stacked/joint inversion, or a custom FunctionOperator/LinearOperator that may have a wrong adjoint. Diagnoses with evidence (block-by-block dot-tests incl. complex, dtype and dims checks, operator/data scaling, solver and eps/damp choice), then proposes the smallest fix and verifies it. Not for choosing a solver for a new, working setup (use solve-inverse-problem) or picking regularisation weights (use tune-regularization).
- License 许可
- LGPL-2.1
- 最近更新
- 2026-11-02
- Stars
- ★ 1
- Forks
- 0
01 前言 Front Matter
- name
- debug-inversion
- description
- Use this skill whenever a user shares PyLops code or results that misbehave and asks what is wrong - load it first, before running the user's code, testing a hypothesis or answering, even when the bug looks obvious from the code. Covers a crash or traceback (dtype/casting errors, shape mismatches), a solver (lsqr, cgls, cg, fista, ista, spgl1, regularized_inversion, splitbregman) that stalls, diverges, returns NaNs, zeros, ringing or a wrong model, one dataset or block being ignored in a stacked/joint inversion, or a custom FunctionOperator/LinearOperator that may have a wrong adjoint. Diagnoses with evidence (block-by-block dot-tests incl. complex, dtype and dims checks, operator/data scaling, solver and eps/damp choice), then proposes the smallest fix and verifies it. Not for choosing a solver for a new, working setup (use solve-inverse-problem) or picking regularisation weights (use tune-regularization).
02 资源文件 1
- 脚本reference/diagnostics.py6.0 KB
03 SKILL.md 正文
Goal: find why the user's inversion misbehaves, with evidence for each claim, and propose the smallest fix. Diagnose first; change the user's code only after reporting the findings (or when asked to fix). Never make a failing dot-test pass by loosening its tolerance.
Carry out these steps yourself, now, in this conversation: nothing runs in the background and no one else will report back. Do not end your turn until you have given the user the report of section 2.
0. Reproduce
- Use the project's Python runner; note
pylops.__version__, NumPy/SciPy (and CuPy/JAX if used) versions. - Run the user's script as is and capture: solver output (
show=True), return tuple (istop, iterations, cost history), shapes and dtypes ofOp,y,x0. - If it is slow, reproduce on a smaller size (fewer samples, fewer sources) that still shows the problem. Keep that reduced case for the checks below.
- If the user described the problem in words and gave no script, do not stop to
ask for one: build a minimal reproduction from the numbers they gave (operator
type, sizes, amplitudes, solver call), or reason from those numbers directly
(e.g. compare
eps,damp,tolwith‖Op‖and‖Opᴴ y‖). Ask for the code only if the description does not pin down the problem. - If Python or PyLops cannot be run here, say so once and reason from the code and the numbers the user gave. Never present a value as measured (dot-test result, error, cost, norm) unless a command you ran printed it; label anything else as an estimate.
reference/diagnostics.py contains helpers for the checks below (import or copy
them next to the user's script; do not add them to the user's package unless
asked).
1. Run the checks in this order
When a check fails, note the finding and its fix, then continue with the remaining checks: an inversion often has more than one problem (e.g. a wrong adjoint and badly scaled blocks), and fixing only the first may not improve the result. After fixing a problem, re-run the inversion; if the result is still poor, the next check is where to look.
- Adjoint (dot-test) –
pylops.utils.dottest(Op, *Op.shape, complexflag=...)on the full operator and on every block (dottest_blockswalksVStack/HStack/BlockDiagand products). Usecomplexflag=3if any part is complex. A failure localises the wrong adjoint → fix it (seewrap-operator). CustomFunctionOperators with an "adjoint" that is actually an inverse or a non-conjugated transpose are the usual culprits. - Shapes and ordering –
Op.dims/Op.dimsdvs howywas built:y.ravel()in C order matchingdimsd, no silent transpose (e.g.(nx, nt)vs(nt, nx)), no broadcasting(n,)vs(n, 1). CompareOp @ xtrue(orOp @ xfor a simple test model) with the observed data visually: they must look alike. - dtypes – mixing
float32operators withfloat64data, complex operators on real data (and vice-versa), or integer arrays.describe_problemprints them. For a complex operator and a real model, see the PyLops "Real/complex inversion" tutorial (Op.toreal(),Op.toimag()). - NaN / Inf – in
y,x0, operator internals (e.g. divisions by zero in aDiagonal,logof a velocity model). Checknp.isfiniteeverywhere. - Scaling and conditioning –
Op.eigs(neigs=1)(largest singular value) and, for small problems,Op.cond();‖y‖,‖Opᴴ y‖. Signs: data at 1e-10 or 1e+10, columns of the operator with norms spanning many orders of magnitude (e.g. stacked blocks with different physical units), regularisation weights orders of magnitude too large or small relative to‖Op‖. Fix by normalising data, weighting blocks, or preconditioning. - Solver vs problem –
cgon a non-symmetric / non-square operator;lsqr/cglson a hugeniterwithout regularisation on noisy data (semi-convergence: error goes down then up);fistawith a user-setalphalarger than1/‖Op‖²(diverges) – leavealpha=Noneor compute it fromOp.eigs;fistawith anSOpthat is not orthogonal/tight-frame;regularized_inversion/preconditioned_inversionwithengine="scipy"(default) while passingniter– SciPy'slsqrtakesiter_limand raisesTypeError; either useiter_lim=...orengine="pylops", niter=.... - Stopping – look at the cost curve (
plot_convergence): flat from the start ⇒ wrong setup (x0 already optimal, zero data, zero operator block); stops early withistopmeaning "tolerance reached" at a bad model ⇒tol/atoltoo loose relative to data scale; still decreasing atniter⇒ increaseniteror precondition. - Regularisation and noise – residual far below the noise level ⇒ overfitting
(increase regularisation / stop earlier); far above ⇒ over-regularised or
modelling error. Use the
tune-regularizationskill to pick weights properly. - Modelling error – the operator is right, but does not explain the data
(wrong wavelet, sampling, units, geometry). Evidence: residual has coherent
structure, not noise. Compare data and
Op @ xfor a best-guess model. - Backend – CuPy/JAX runs: arrays on different devices, operators built
with NumPy arrays but applied to CuPy data,
float64on consumer GPUs being very slow. Seeaccelerate-on-gpu.
2. Report
For each finding, give: the check, the evidence (numbers, plot path, the failing block name), the likely cause, and the proposed fix. Rank by impact. Then either apply fixes (if the user asked) and re-run to show the improvement, or list the exact changes to make.
Keep what you ran apart from what you did not:
- Mark each check as run (quote the command's output it rests on) or not run (say why, and label any statement about it as an expectation). Do not report a check as passed for a part you did not test, e.g. "every block passes the dot-test" when only the full operator was tested.
- For each proposed fix, say whether you tested it and what it changed. If a fix you tested did not help, say so explicitly and check your implementation of it before concluding that the problem is elsewhere.
Say the result is limited by the physics / data (null space, noise, limited aperture) only when the operator and the data weighting are correct and a tested fix did not improve it - not as a fallback when a fix did not work. In that case say so explicitly rather than tweaking parameters.
04 同仓库更多 Skills
solve-nonsmooth-problem
Use this skill whenever the user wants to solve an inverse problem on PyLops operators with a non-smooth, constrained or non-convex term - load it before writing the objective, choosing a solver or writing optimisation code, even when a SciPy bounded solver or a hand-written FISTA/ADMM loop would also work. Covers total variation, L1/sparsity in a transform, joint sparsity across signals sharing the same components, bounds/positivity/ball/affine constraints, low-rank matrix completion (nuclear norm) and plug-and-play priors with a denoiser (median filter, BM3D), solved with PyProximal (ProximalGradient, ADMM, PrimalDual, ...), step sizes from operator norms. E.g. "add TV regularisation", "keep the model within physical bounds", "recover several signals that share their components", "fill in missing entries of a low-rank matrix", "use PyProximal". Not for purely quadratic regularisation (Tikhonov, damping, derivative smoothing), which is plain least squares - use the pylops skill solve-inverse-problem.
wrap-operator
Wrap a user's own forward model as a PyLops linear operator inside their project (not inside the PyLops library), with a verified adjoint, a dot-test and a small test suite. Use when the user wants to turn existing forward/adjoint code, a script at a URL, or a mathematical description into a PyLops operator they can pass to PyLops solvers (e.g. "make my blurring function a PyLops operator", "wrap this forward model so I can invert it with lsqr", "I have a forward and adjoint, plug them into PyLops").
tune-regularization
Choose regularisation weights and thresholds for a PyLops inversion (epsRs in regularized_inversion, damp in cgls/lsqr, eps in ista/fista, epsRL1s in splitbregman, sigma/tau in spgl1, niter as implicit regularisation) with a principled, reproducible sweep - L-curve, discrepancy principle, GCV for small problems, or a synthetic test with a known model. Use when the user asks "how do I choose epsilon / lambda / damping", "my inversion is too smooth / too noisy", "make an L-curve", or after solve-inverse-problem produced a working but untuned inversion.
solve-inverse-problem
Use this skill whenever the user has (or can build) a PyLops operator and data and wants to invert it - load it before choosing a solver or writing any inversion code, even when the right solver or regularisation seems obvious. It sets up and runs the inversion in the user's project - choose the solver (lsqr, cgls, cg, regularized_inversion, preconditioned_inversion, fista, spgl1, omp, irls, splitbregman), the regularisation and the stopping parameters, and write a runnable script that reports convergence. E.g. "invert my data with this operator", "which PyLops solver should I use", "add Tikhonov / smoothness / sparsity regularisation to my inversion", "solve y = Op x". Not for an inversion that already misbehaves (use debug-inversion) or for choosing regularisation weights with an L-curve or sweep (use tune-regularization).
sliding-patch-processing
Set up PyLops windowed operators - Sliding1D, Sliding2D, Sliding3D, Patch2D, Patch3D - to apply a local transform or operator over overlapping windows of 1-D/2-D/3-D data, choosing window size, overlap, taper and model size with the *_design and *_pad_to_next helpers, checking coverage and the dot-test, and using them for local denoising, interpolation or inversion. Use when the user asks "apply FFT/Radon/any operator in overlapping windows", "local transform / patching with PyLops", "Patch2D gives artefacts at the edges", "how do I pick nwin, nover, nop".
pick-sparsifying-transform
Choose a sparsifying transform for a signal or image in a PyLops sparsity-promoting inversion (FFT/FFT2D/FFTND, DCT, DWT/DWT2D/DWTND, DTCWT, Seislet, curvelets via UDCT, Radon/FourierRadon/ChirpRadon, windowed versions with Sliding/Patch), check its optional dependencies and frame properties, compare candidates quantitatively with a best-k-term compressibility test, and wire the winner into fista/spgl1 in synthesis or analysis form. Use when the user asks "which transform should I use for sparsity", "wavelets or curvelets for my data", "make my model sparse for fista/spgl1", "compressive sensing / interpolation with PyLops".