Files
scientific-agent-skills/skills/openpiv/scripts/run_example.py
T
Alex LiberzonandTimothy Kassis dde19062f3 Add OpenPIV skill under skills/openpiv (#216)
* add OpenPIV skill under skills/openpiv

* Fix spec violations and unverified APIs in the OpenPIV skill

Verified everything against openpiv 0.25.4 in a clean venv; all 14 SKILL.md
snippets and both reference snippets now execute, and runner.py/run_example.py
run end to end on OpenPIV's bundled test1 pair.

Spec adherence:
- metadata was a JSON flow mapping, which strictyaml rejects outright -- the
  skill failed `skills-ref validate` and would not have registered at all.
  Converted to a block mapping.
- compatibility claimed Python 3.8+; openpiv 0.25.4 requires >=3.10.
- Added allowed-tools and a version-pinned install line.

APIs that do not exist and now do:
- `openpiv.masking` -> `openpiv.preprocess.dynamic_masking`, which returns
  (image, mask). method="shirai" is not a method; it is "edges" or "intensity".
  The masked image is returned already zeroed, so multiplying the frame by the
  mask is wrong -- for "edges" the mask is uint8 0/255 and rescales by 255.
- `pyprocess.iterative_warping_piv` -> `openpiv.windef.simple_multipass`.
- `openpiv.smooth.smooth` -> `openpiv.smoothn.smoothn`.
- `global_val(u, v, u_threshold=, v_threshold=)` -> positional (min, max) tuples
  as u_thresholds/v_thresholds.
- `local_median_val(u, v)` -> u_threshold and v_threshold are required.
- `replace_outliers(method="disc")` -> "disk"; an unknown method is not
  rejected, it silently yields an all-zero kernel.
- Combining flags with np.maximum -> boolean OR; validators return bool arrays
  where True marks a spurious vector.

references/advanced_algorithms.md described algorithms that do not exist in
OpenPIV ("epi-div_div", "pritzmd_piv", EDD, PrTrZMD) alongside invented
throughput and memory figures. Replaced with the real correlation, subpixel,
s2n, multi-pass, 3D, and phase-separation APIs plus the full PIVSettings table.

Two units traps found while testing and now documented:
- windef ignores settings.dt and settings.scaling_factor -- first_pass calls
  extended_search_area_piv without dt, so the chain returns px/frame.
- global_val/local_median_val thresholds are in the units of u and v. After
  extended_search_area_piv(dt=0.02) that is px/s, so the conventional (-30, 30)
  px/frame limit rejects the entire field.

Scripts:
- runner.py: dropped --algorithm and --threads, which were accepted and never
  used (--algorithm even offered a nonexistent "synthetic_aperture"), and
  --mask static, which nothing implemented. --mask dynamic silently did nothing
  because it caught the ImportError from the nonexistent module. Selects
  correlation_method="linear" when search_area > window_size, since the default
  "circular" aliases via FFT wrap-around. Validates argument ranges, pins the
  Agg backend before pyplot, and no longer NaNs out the vectors it just
  interpolated -- that is now opt-in via --drop_invalid.
- analyze.py: class was named PypivAnalyzer and documented as "using pivpy"
  while importing neither. Renamed to PIVAnalyzer, added compute_strain and
  compute_statistics to match what SKILL.md advertises, and derived the physical
  grid spacing from the saved coordinates so the gradients are per unit length.
- run_example.py: was a subprocess wrapper around a hardcoded relative path.
  Rewritten as a self-contained smoke test on OpenPIV's bundled image pair.

Security scan: SAFE, 0 findings.

---------

Co-authored-by: Timothy Kassis <timothy.kassis@k-dense.ai>
2026-07-26 10:08:21 -07:00

79 lines
2.8 KiB
Python

"""End-to-end smoke test of the OpenPIV pipeline on OpenPIV's own bundled data.
Runs the full runner.py pipeline against the exp1_001 image pair that ships inside the
openpiv package, so it needs no external files. Use it to confirm an install works
before pointing the CLI at real experiment data.
python skills/openpiv/scripts/run_example.py --output_dir /tmp/openpiv-demo
"""
import argparse
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from analyze import PIVAnalyzer # noqa: E402
from runner import run_openpiv # noqa: E402
def bundled_image_pair() -> tuple[Path, Path]:
"""Locate the exp1_001 pair inside the installed openpiv package."""
import openpiv
data_dir = Path(openpiv.__file__).parent / "data" / "test1"
frame_a = data_dir / "exp1_001_a.bmp"
frame_b = data_dir / "exp1_001_b.bmp"
if not frame_a.exists() or not frame_b.exists():
raise FileNotFoundError(
f"OpenPIV's bundled test1 images are missing from {data_dir}. "
"Pass your own image pair to runner.py instead."
)
return frame_a, frame_b
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output_dir", default="openpiv-example")
parser.add_argument("--window_size", type=int, default=32)
parser.add_argument("--overlap", type=int, default=12)
parser.add_argument("--search_area", type=int, default=38)
args = parser.parse_args()
frame_a, frame_b = bundled_image_pair()
print(f"Using bundled pair: {frame_a.name}, {frame_b.name}")
# dt and scaling here are the values from OpenPIV's own test1 tutorial (px/mm).
output_path = run_openpiv(
image1=str(frame_a),
image2=str(frame_b),
output_dir=args.output_dir,
window_size=args.window_size,
overlap=args.overlap,
search_area=args.search_area,
dt=0.02,
scaling_factor=96.52,
threshold=1.05,
verbose=True,
)
analyzer = PIVAnalyzer(output_path / "params.npz")
dx, dy = analyzer.grid_spacing
stats = analyzer.compute_statistics()
vorticity = analyzer.compute_vorticity()
print(f"\nField shape: {analyzer.u.shape}")
print(f"Grid spacing: dx={dx:.4f}, dy={dy:.4f} (physical units)")
print(f"Flagged vectors: {int(analyzer.flags.sum())}/{analyzer.flags.size}")
print(f"Mean velocity: u={stats['u_mean']:.4f}, v={stats['v_mean']:.4f}")
print(f"RMS: u={stats['rms_u']:.4f}, v={stats['rms_v']:.4f}, tke={stats['tke']:.4f}")
print(f"Vorticity range: {vorticity.min():.4f} to {vorticity.max():.4f}")
analyzer.plot_vector_field(save_path=str(output_path / "quiver.png"))
print(f"\nWrote quiver.png alongside runner.py's output in {output_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())